GPU架构层次、FlashAttention、Triton kernel、CUDA编程、算子融合、profiling
理解Kernel工程的第一步是理解GPU硬件架构。大模型训练和推理的几乎所有性能瓶颈都源于对GPU内存层次和并行模型的误解。本节从最底层的SM(Streaming Multiprocessor)出发,逐层构建对GPU计算模型的理解。
现代GPU(以NVIDIA H100为例)由多个SM组成。H100 GH100芯片包含144个SM(满血版),每个SM内部包含:
Warp是GPU的基本执行单元。一个Warp由32个线程组成,这些线程在同一时钟周期执行相同的指令(SIMT模型)。当Warp内线程执行不同的分支时,发生Warp Divergence(分支发散),导致串行执行两个分支路径,性能减半。
# Warp divergence 示意:奇偶分支导致性能减半
# 32个线程中,16个走if分支,16个走else分支
# GPU会串行执行两个分支,有效利用率只有50%
if thread_id % 2 == 0:
result[thread_id] = a[thread_id] + b[thread_id] # 16个线程执行
else:
result[thread_id] = a[thread_id] * b[thread_id] # 16个线程执行
# 优化:尽量让同一Warp内线程走相同分支
# 或使用无分支写法:
is_even = 1 - (thread_id & 1)
result[thread_id] = is_even * (a + b) + (1 - is_even) * (a * b)
CUDA编程模型将计算组织为三层层次结构:
GPU的内存层次决定了Kernel性能的上限。理解各级带宽和延迟对于编写高效Kernel至关重要:
| 内存层级 | 容量 (H100) | 带宽 | 延迟 | 作用域 | 是否需要显式管理 |
|---|---|---|---|---|---|
| Register | 256KB/SM | ~13 TB/s | 1 cycle | Thread | 编译器自动分配 |
| Shared Memory / L1 | 228KB/SM | ~12 TB/s | ~30 cycles | Block | 显式 __shared__ |
| L2 Cache | 50MB (H100) | ~12 TB/s | ~200 cycles | Global (所有SM) | 硬件自动管理 |
| HBM3 | 80GB (H100) | 3.35 TB/s | ~400-600 cycles | Global | 显式 cudaMalloc |
| Host Memory | 系统RAM | ~64 GB/s (PCIe) | ~1000+ cycles | CPU-GPU | 显式传输 |
Tensor Core是NVIDIA Volta架构(V100)之后引入的专用矩阵乘加单元。它在一个时钟周期内完成一个MMA操作:D = A * B + C,其中A为m*k,B为k*n,C/D为m*n。
不同精度下的Tensor Core操作尺寸:
| 精度 | MMA形状 (m*n*k) | 每周期FLOPS/SM | 架构 |
|---|---|---|---|
| FP64 | 8*8*4 | 256 | Volta+ |
| FP16/BF16 | 16*8*16 | 1024 | Volta+ |
| TF32 | 16*8*8 | 512 | Ampere+ |
| INT8 | 16*8*32 | 2048 | Ampere+ |
| FP8 (E4M3/E5M2) | 16*8*32 | 2048 | Hopper+ |
H100的FP16 Tensor Core理论算力:144 SM * 4 TC * 1024 FLOPS * 1.98 GHz = 989 TFLOPS。而FP32 CUDA Core理论算力仅144 * 128 * 2 * 1.98 = 73 TFLOPS。差距达13.5倍——这就是为什么大模型训练必须利用Tensor Core。
标准Attention的计算过程为 O = softmax(QK^T / sqrt(d)) * V。朴素实现需要将完整的 N*N 注意力矩阵写入HBM,导致 O(N^2) 的HBM读写。对于 N=128K 的长序列,仅注意力矩阵就需要 128K * 128K * 2 bytes (FP16) = 32GB,远超GPU显存。FlashAttention通过分块计算(Tiling)和在线Softmax(Online Softmax)将HBM读写降至 O(N^2*d/M),其中 M 为SRAM大小。
标准Softmax:s_i = exp(q_i - max(q)) / sum(exp(q_j - max(q)))。问题在于max和sum需要遍历完整向量。FlashAttention的核心创新是在线Softmax——逐块更新max和sum,无需存储完整注意力矩阵。
# Online Softmax 算法核心推导
# 给定两个块 [x1, x2, ..., xm] 和 [xm+1, ..., xn]
# 已知块1的 max1, sum1 = sum(exp(xi - max1))
# 已知块2的 max2, sum2 = sum(exp(xj - max2))
# 合并后的全局 max 和 sum:
def online_softmax_merge(max1, sum1, max2, sum2):
"""合并两个块的softmax统计量"""
max_global = max(max1, max2)
# 缩放因子:将旧的exp(x - max_old)转换为exp(x - max_global)
scale1 = exp(max1 - max_global)
scale2 = exp(max2 - max_global)
sum_global = sum1 * scale1 + sum2 * scale2
return max_global, sum_global
# 对于输出 O 的合并:
# O_new = (O1 * sum1 * scale1 + O2 * sum2 * scale2) / sum_global
def merge_output(O1, sum1, O2, sum2, max1, max2):
max_global = max(max1, max2)
scale1 = exp(max1 - max_global)
scale2 = exp(max2 - max_global)
sum_global = sum1 * scale1 + sum2 * scale2
O_global = (O1 * sum1 * scale1 + O2 * sum2 * scale2) / sum_global
return O_global, max_global, sum_global
FlashAttention-1(Dao et al., 2022)将Q、K、V分块,逐块计算注意力并在线更新Softmax统计量。算法在SRAM中完成所有中间计算,仅读写Q、K、V和输出O到HBM。
# FlashAttention-1 完整伪代码
# 输入: Q, K, V in R^{N*d}, 分块大小 Br (Q行), Bc (KV列)
# 输出: O in R^{N*d}
def flash_attention_v1(Q, K, V, Br=128, Bc=64):
N, d = Q.shape
Tr = N // Br # Q的块数
Tc = N // Bc # KV的块数
scale = 1.0 / sqrt(d)
# 初始化输出和统计量
O = zeros(N, d)
L = zeros(N) # log-sum-exp (用于数值稳定)
for j in range(Tc): # 外层循环:遍历KV块
Kj = K[j*Bc:(j+1)*Bc] # 加载K块到SRAM
Vj = V[j*Bc:(j+1)*Bc] # 加载V块到SRAM
for i in range(Tr): # 内层循环:遍历Q块
Qi = Q[i*Br:(i+1)*Br] # 加载Q块到SRAM
Oi = O[i*Br:(i+1)*Br] # 加载当前输出
Li = L[i*Br:(i+1)*Br] # 加载当前LSE
# 在SRAM中计算分块注意力分数
Sij = (Qi @ Kj.T) * scale # Br*Bc, 不写入HBM
# 在线Softmax更新
m_ij = rowmax(Sij) # 每行最大值
P_ij = exp(Sij - m_ij[:, None]) # 减去max防溢出
l_ij = rowsum(P_ij) # 每行求和
# 更新全局统计量
m_new = maximum(Li, m_ij) # 新的全局max
alpha = exp(Li - m_new)
beta = exp(m_ij - m_new)
# 更新输出
Oi_new = Oi * alpha[:, None] + (P_ij @ Vj) * beta[:, None]
Li_new = m_new + log(alpha * exp(Li - Li) + beta * l_ij)
# 写回HBM
O[i*Br:(i+1)*Br] = Oi_new
L[i*Br:(i+1)*Br] = Li_new
# 最终归一化
O = O / exp(L)[:, None]
return O
FlashAttention-2(Dao, 2023)在V1基础上做了三项关键优化:
# FlashAttention-2 核心改进:外层循环遍历Q块
# 这样不同Q块可以完全并行,无需同步
def flash_attention_v2(Q, K, V, Br=128, Bc=64):
N, d = Q.shape
Tr = N // Br
Tc = N // Bc
scale = 1.0 / sqrt(d)
O = zeros(N, d)
for i in range(Tr): # 外层:Q块(可并行)
Qi = Q[i*Br:(i+1)*Br]
Oi = zeros(Br, d)
li = zeros(Br) # 累积sum
mi = full(Br, -inf) # 累积max
for j in range(Tc): # 内层:KV块(串行)
Kj = K[j*Bc:(j+1)*Bc]
Vj = V[j*Bc:(j+1)*Bc]
Sij = (Qi @ Kj.T) * scale
m_ij = rowmax(Sij)
P_ij = exp(Sij - m_ij[:, None])
l_ij = rowsum(P_ij)
# V2关键改进:先更新mi, 再统一rescale
m_new = maximum(mi, m_ij)
alpha = exp(mi - m_new)
beta = exp(m_ij - m_new)
# V2改进:rescale O和l一起做
Oi = Oi * alpha[:, None] + P_ij @ Vj * beta[:, None]
li = li * alpha + l_ij * beta
mi = m_new
# 循环结束后统一归一化
O[i*Br:(i+1)*Br] = Oi / li[:, None]
return O
FlashAttention-3(Shah et al., 2024)针对Hopper架构(H100)做了深度优化:
// FlashAttention-3 核心异步流水线 (Hopper架构)
// 利用 TMA (Tensor Memory Accelerator) 异步加载
// 利用 WGMMA (Warpgroup MMA) 异步计算
__global__ void flash_attn3_kernel(
const float* __restrict__ Q,
const float* __restrict__ K,
const float* __restrict__ V,
float* __restrict__ O,
int N, int d, float scale) {
// TMA异步加载Q块 (不阻塞,后台执行)
cp_async_bulk(smem_Q, Q + q_offset, q_size);
cp_async_bulk(smem_K, K + k_offset, k_size);
cp_async_commit_group();
for (int j = 0; j < Tc; ++j) {
// 等待上一轮K加载完成
cp_async_wait_group(0);
__syncthreads();
// 异步发起下一轮KV的TMA加载 (流水线)
if (j + 1 < Tc) {
cp_async_bulk(smem_K_next, K + next_k_offset, k_size);
cp_async_bulk(smem_V_next, V + next_v_offset, v_size);
cp_async_commit_group();
}
// WGMMA异步矩阵乘法 (Tensor Core后台执行)
wgmma_fence();
wgmma_async(frag_S, smem_Q, smem_K, scale);
wgmma_commit_group();
// 在WGMMA执行期间,用CUDA Core做Softmax
// 这就是FA3的核心:GEMM和Softmax重叠
softmax_in_place(frag_S, frag_m, frag_l);
// 等待WGMMA完成
wgmma_wait_group(0);
__syncthreads();
// 第二次WGMMA: P @ V
wgmma_async(frag_O, frag_P, smem_V);
wgmma_commit_group();
wgmma_wait_group(0);
// 更新累积输出和统计量
rescale_and_accumulate(frag_O, frag_m, frag_l);
}
// 最终归一化并写回HBM
normalize_and_store(O, frag_O, frag_l);
}
| 方法 | GPU | 精度 | 序列长度 | 吞吐量 (TFLOPS) | 理论峰值占比 |
|---|---|---|---|---|---|
| PyTorch SDPA | A100 | FP16 | 4096 | ~120 | ~35% |
| FlashAttention-1 | A100 | FP16 | 4096 | ~180 | ~52% |
| FlashAttention-2 | A100 | FP16 | 4096 | ~240 | ~70% |
| FlashAttention-2 | H100 | FP16 | 4096 | ~560 | ~57% |
| FlashAttention-3 | H100 | FP16 | 4096 | ~740 | ~75% |
| FlashAttention-3 | H100 | FP8 | 4096 | ~1200 | ~75% |
Triton是OpenAI开发的GPU Kernel编程语言/编译器,提供Python语法的高层抽象,同时生成接近手写CUDA的性能。Triton的核心设计理念是"块级编程"——程序员以Block为单位思考,编译器处理Warp调度和共享内存管理。
import triton
import triton.language as tl
import torch
# Triton Kernel: 向量加法
# @triton.jit 将Python函数编译为GPU Kernel
@triton.jit
def vector_add_kernel(
x_ptr, y_ptr, z_ptr, # 指针参数
n, # 标量参数
BLOCK_SIZE: tl.constexpr, # 编译期常量
):
# 获取当前程序ID (类似CUDA的blockIdx)
pid = tl.program_id(axis=0)
# 计算当前块处理的元素范围
block_start = pid * BLOCK_SIZE
offsets = block_start + tl.arange(0, BLOCK_SIZE)
# 边界检查掩码
mask = offsets < n
# 从HBM加载数据 (带掩码,越界返回0)
x = tl.load(x_ptr + offsets, mask=mask, other=0.0)
y = tl.load(y_ptr + offsets, mask=mask, other=0.0)
# 计算
z = x + y
# 写回HBM
tl.store(z_ptr + offsets, z, mask=mask)
# 包装函数:处理Grid大小和启动
def vector_add(x: torch.Tensor, y: torch.Tensor):
z = torch.empty_like(x)
n = x.numel()
# 计算Grid大小:ceil(n / BLOCK_SIZE)
grid = (triton.cdiv(n, 1024),)
vector_add_kernel[grid](x, y, z, n, BLOCK_SIZE=1024)
return z
# 测试
x = torch.randn(10000, device='cuda')
y = torch.randn(10000, device='cuda')
z = vector_add(x, y)
assert torch.allclose(z, x + y)
# Triton GEMM: C = A @ B, A: M*K, B: K*N, C: M*N
# 使用分块(tiling) + L2缓存优化
@triton.jit
def matmul_kernel(
A_ptr, B_ptr, C_ptr,
M, N, K,
stride_am, stride_ak,
stride_bk, stride_bn,
stride_cm, stride_cn,
BLOCK_M: tl.constexpr,
BLOCK_N: tl.constexpr,
BLOCK_K: tl.constexpr,
GROUP_M: tl.constexpr,
):
# L2缓存优化:重排Block执行顺序
pid = tl.program_id(axis=0)
num_pid_m = tl.cdiv(M, BLOCK_M)
num_pid_n = tl.cdiv(N, BLOCK_N)
num_pid_in_group = GROUP_M * num_pid_n
group_id = pid // num_pid_in_group
first_pid_m = group_id * GROUP_M
group_size_m = min(num_pid_m - first_pid_m, GROUP_M)
pid_m = first_pid_m + (pid % group_size_m)
pid_n = (pid % num_pid_in_group) // group_size_m
# 计算当前Block的行列范围
offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
offs_k = tl.arange(0, BLOCK_K)
# A和B的指针
A_ptrs = A_ptr + offs_m[:, None] * stride_am + offs_k[None, :] * stride_ak
B_ptrs = B_ptr + offs_k[:, None] * stride_bk + offs_n[None, :] * stride_bn
# 累加器
acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
# 沿K维度循环
for k in range(0, tl.cdiv(K, BLOCK_K)):
a = tl.load(A_ptrs, mask=offs_m[:, None] < M, other=0.0)
b = tl.load(B_ptrs, mask=offs_n[None, :] < N, other=0.0)
acc += tl.dot(a, b) # 调用Tensor Core
A_ptrs += BLOCK_K * stride_ak
B_ptrs += BLOCK_K * stride_bk
# 写回结果
C_ptrs = C_ptr + offs_m[:, None] * stride_cm + offs_n[None, :] * stride_cn
tl.store(C_ptrs, acc, mask=(offs_m[:, None] < M) & (offs_n[None, :] < N))
# 用Triton实现FlashAttention (FA2风格)
@triton.jit
def flash_attn_kernel(
Q_ptr, K_ptr, V_ptr, O_ptr,
L_ptr, # log-sum-exp
N,
scale,
BLOCK_M: tl.constexpr,
BLOCK_N: tl.constexpr,
D: tl.constexpr, # head_dim, 编译期常量
):
pid_m = tl.program_id(0)
# Q块索引
offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
offs_d = tl.arange(0, D)
# 加载Q块到SRAM [BLOCK_M, D]
Q_ptrs = Q_ptr + offs_m[:, None] * D + offs_d[None, :]
Q = tl.load(Q_ptrs, mask=offs_m[:, None] < N, other=0.0)
# 初始化累加器
m_i = tl.full([BLOCK_M], -float('inf'), dtype=tl.float32)
l_i = tl.zeros([BLOCK_M], dtype=tl.float32)
acc = tl.zeros([BLOCK_M, D], dtype=tl.float32)
# 遍历KV块
for pid_n in range(tl.cdiv(N, BLOCK_N)):
offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
# 加载K, V块
K_ptrs = K_ptr + offs_n[:, None] * D + offs_d[None, :]
V_ptrs = V_ptr + offs_n[:, None] * D + offs_d[None, :]
K = tl.load(K_ptrs, mask=offs_n[:, None] < N, other=0.0)
V = tl.load(V_ptrs, mask=offs_n[:, None] < N, other=0.0)
# 计算QK^T [BLOCK_M, BLOCK_N]
S = tl.dot(Q, tl.trans(K)) * scale
# 在线Softmax
m_ij = tl.max(S, axis=1)
P = tl.exp(S - m_ij[:, None])
l_ij = tl.sum(P, axis=1)
# 更新统计量
m_new = tl.maximum(m_i, m_ij)
alpha = tl.exp(m_i - m_new)
beta = tl.exp(m_ij - m_new)
# 更新累加器
acc = acc * alpha[:, None] + tl.dot(P.to(V.dtype), V) * beta[:, None]
l_i = l_i * alpha + l_ij * beta
m_i = m_new
# 归一化并写回
acc = acc / l_i[:, None]
O_ptrs = O_ptr + offs_m[:, None] * D + offs_d[None, :]
tl.store(O_ptrs, acc, mask=offs_m[:, None] < N)
tl.store(L_ptr + offs_m, m_i + tl.log(l_i), mask=offs_m < N)
# Triton自动调优:自动搜索最优配置
@triton.autotune(
configs=[
triton.Config({'BLOCK_M': 64, 'BLOCK_N': 64, 'BLOCK_K': 32}, num_warps=4),
triton.Config({'BLOCK_M': 128, 'BLOCK_N': 64, 'BLOCK_K': 32}, num_warps=4),
triton.Config({'BLOCK_M': 128, 'BLOCK_N': 128, 'BLOCK_K': 32}, num_warps=8),
triton.Config({'BLOCK_M': 128, 'BLOCK_N': 256, 'BLOCK_K': 64}, num_warps=8),
triton.Config({'BLOCK_M': 64, 'BLOCK_N': 128, 'BLOCK_K': 64}, num_warps=4),
],
key=['M', 'N', 'K'], # 当这些参数变化时重新调优
)
@triton.jit
def matmul_autotuned(...):
# kernel实现同上
pass
// 基硧CUDA: 向量加法
// 展示Thread/Block/Grid配置和边界处理
__global__ void vector_add_cuda(
const float* x, const float* y, float* z, int n) {
// 全局线程索引
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx < n) { // 边界检查
z[idx] = x[idx] + y[idx];
}
}
// Host端启动配置
void launch_vector_add(const float* d_x, const float* d_y, float* d_z, int n) {
int threads_per_block = 256; // 每Block 256线程
int blocks_per_grid = (n + threads_per_block - 1) / threads_per_block;
vector_add_cuda<<<blocks_per_grid, threads_per_block>>>(d_x, d_y, d_z, n);
cudaDeviceSynchronize();
}
// 共享内存分块矩阵乘法
// A: M*K, B: K*N, C: M*N
// 使用共享内存减少全局内存访问
__global__ void sgemm_shared(
const float* A, const float* B, float* C,
int M, int N, int K) {
// Block大小
const int BM = 32;
const int BN = 32;
const int BK = 32;
// 共享内存分配
__shared__ float s_A[BM][BK]; // A的分块
__shared__ float s_B[BK][BN]; // B的分块
// 当前线程负责的C元素
int row = blockIdx.y * BM + threadIdx.y;
int col = blockIdx.x * BN + threadIdx.x;
float acc = 0.0f;
// 沿K维度分块循环
for (int k = 0; k < K; k += BK) {
// 协作加载A和B的分块到共享内存
s_A[threadIdx.y][threadIdx.x] = (row < M && k + threadIdx.x < K)
? A[row * K + k + threadIdx.x] : 0.0f;
s_B[threadIdx.y][threadIdx.x] = (k + threadIdx.y < K && col < N)
? B[(k + threadIdx.y) * N + col] : 0.0f;
// 同步:确保共享内存加载完成
__syncthreads();
// 在共享内存中计算分块乘法
for (int i = 0; i < BK; ++i) {
acc += s_A[threadIdx.y][i] * s_B[i][threadIdx.x];
}
// 同步:确保计算完成后再加载下一块
__syncthreads();
}
// 写回结果
if (row < M && col < N) {
C[row * N + col] = acc;
}
}
// Warp Shuffle: 线程间数据交换,不经过共享内存
// 比共享内存更快,用于Warp内Reduce
__device__ float warp_reduce_sum(float val) {
// __shfl_xor_sync: 与所有lane交换数据并累加
val += __shfl_xor_sync(0xffffffff, val, 16); // 与lane+16交换
val += __shfl_xor_sync(0xffffffff, val, 8); // 与lane+8交换
val += __shfl_xor_sync(0xffffffff, val, 4); // 与lane+4交换
val += __shfl_xor_sync(0xffffffff, val, 2); // 与lane+2交换
val += __shfl_xor_sync(0xffffffff, val, 1); // 与lane+1交换
return val;
}
// Block级Reduce: 先Warp Reduce,再跨Warp Reduce
__device__ float block_reduce_sum(float val, __shared__ float* smem) {
int lane = threadIdx.x % 32;
int wid = threadIdx.x / 32;
val = warp_reduce_sum(val); // Warp内Reduce
if (lane == 0) smem[wid] = val; // 每个Warp的lane 0写入共享内存
__syncthreads();
val = (threadIdx.x < blockDim.x / 32) ? smem[lane] : 0.0f;
if (wid == 0) val = warp_reduce_sum(val); // 第一个Warp做最终Reduce
return val;
}
Liger-Kernel是LinkedIn开源的Triton预融合算子库,通过将多个小算子融合为单个Kernel,显著减少HBM读写和Kernel启动开销。对于常见的LLM前向/反向传播,Liger-Kernel可以减少约40%的GPU显存占用和提升约20%的训练吞吐量。
# 安装 Liger-Kernel
# pip install liger-kernel
from liger_kernel.transformers import apply_liger_kernel_to_gemma
from liger_kernel.transformers import apply_liger_kernel_to_llama
from liger_kernel.transformers import apply_liger_kernel_to_mistral
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
# 方式1: 全局打补丁 (推荐)
# 自动替换模型中的RMSNorm, RoPE, SwiGLU, CrossEntropy等算子
apply_liger_kernel_to_llama()
# 然后正常加载模型,内部已使用融合Kernel
model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Llama-3-8B",
torch_dtype=torch.bfloat16,
device_map="auto",
)
# 方式2: 仅打补丁特定模型类
from transformers import LlamaForCausalLM
apply_liger_kernel_to_llama(model=LlamaForCausalLM)
| 融合算子 | 原始算子序列 | 融合后 | 显存节省 |
|---|---|---|---|
| RMSNorm | square -> mean -> add_eps -> rsqrt -> mul -> mul | 单次Kernel | ~60% |
| RoPE | cos -> sin -> rotate_half -> mul -> mul -> add | 单次Kernel | ~70% |
| SwiGLU | silu -> mul | 单次Kernel | ~50% |
| CrossEntropy | log_softmax -> nll_loss | 单次Kernel (无中间矩阵) | ~80% |
| FusedLinearCE | linear -> log_softmax -> nll_loss | 单次Kernel | ~90% |
| GeGLU | gelu -> mul | 单次Kernel | ~50% |
# Liger-Kernel 性能基准测试
import torch
import time
from transformers import AutoModelForCausalLM
from liger_kernel.transformers import apply_liger_kernel_to_llama
def benchmark(model, input_ids, num_warmup=5, num_iter=20):
for _ in range(num_warmup):
with torch.no_grad():
model(input_ids)
torch.cuda.synchronize()
start = time.time()
for _ in range(num_iter):
with torch.no_grad():
model(input_ids)
torch.cuda.synchronize()
return (time.time() - start) / num_iter
input_ids = torch.randint(0, 128000, (1, 4096), device='cuda')
# 原始模型
model_orig = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3-8B", torch_dtype=torch.bfloat16, device_map="cuda")
time_orig = benchmark(model_orig, input_ids)
mem_orig = torch.cuda.max_memory_allocated() / 1e9
torch.cuda.reset_peak_memory_stats()
# Liger-Kernel模型
apply_liger_kernel_to_llama()
model_liger = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3-8B", torch_dtype=torch.bfloat16, device_map="cuda")
time_liger = benchmark(model_liger, input_ids)
mem_liger = torch.cuda.max_memory_allocated() / 1e9
print(f"原始: {time_orig*1000:.1f}ms, {mem_orig:.1f}GB")
print(f"Liger: {time_liger*1000:.1f}ms, {mem_liger:.1f}GB")
print(f"加速: {time_orig/time_liger:.2f}x, 显存节省: {(mem_orig-mem_liger)/mem_orig*100:.1f}%")
# 典型结果 (Llama-3-8B, seq=4096, A100):
# 原始: 52.3ms, 18.2GB
# Liger: 43.1ms, 12.8GB
# 加速: 1.21x, 显存节省: 29.7%
考虑RMSNorm的计算:y = x / sqrt(mean(x^2) + eps) * weight。朴素实现需要5个独立Kernel:
总HBM读写:5次读 + 4次临时写 + 1次最终写 = 10次N元素传输。融合后仅需1次读 + 1次写 = 2次N元素传输,减少80%访存。
# 算子融合分析: RMSNorm为例
import torch
# 未融合: 5个独立Kernel
def rmsnorm_unfused(x, weight, eps=1e-6):
t1 = x * x # Kernel 1: 读x, 写t1
t2 = t1.mean(dim=-1, keepdim=True) # Kernel 2: 读t1, 写t2
t3 = t2 + eps # Kernel 3: 读t2, 写t3
t4 = torch.rsqrt(t3) # Kernel 4: 读t3, 写t4
y = x * t4 * weight # Kernel 5: 读x,t4,w, 写y
return y # 总计: 10次N元素HBM读写
# 融合: 1个Triton Kernel
import triton
import triton.language as tl
@triton.jit
def rmsnorm_fused_kernel(
x_ptr, w_ptr, y_ptr,
N, eps,
BLOCK: tl.constexpr,
):
row = tl.program_id(0)
cols = tl.arange(0, BLOCK)
mask = cols < N
# 一次加载x
x = tl.load(x_ptr + row * N + cols, mask=mask, other=0.0)
# 所有计算在寄存器/SRAM中完成
var = tl.sum(x * x, axis=0) / N
rsqrt_var = 1.0 / tl.sqrt(var + eps)
# 一次加载weight
w = tl.load(w_ptr + cols, mask=mask, other=0.0)
# 一次写回y
y = x * rsqrt_var * w
tl.store(y_ptr + row * N + cols, y, mask=mask)
# 总计: 2次N元素HBM读写 (读x+w, 写y)
| 可融合模式 | 示例 | 融合收益 |
|---|---|---|
| 逐元素操作链 | add -> mul -> relu -> add | 高(每次省一次读写) |
| 归约 + 广播 | RMSNorm, LayerNorm, Softmax | 高(消除中间矩阵) |
| GEMM + 逐元素 | Linear + GELU, Linear + SiLU | 中(需epilogue融合) |
| 损失 + 归约 | Linear + LogSoftmax + NLLLoss | 极高(消除logits矩阵) |
| 不可融合 | 两个独立GEMM, 需全局归约后分发 | — |
PyTorch的Autograd为每个前向算子生成独立的反向Kernel。手动融合反向传播可以显著减少训练时的显存占用和Kernel启动开销。
# 手动融合反向传播: SwiGLU = SiLU(xW_gate) * (xW_up)
class FusedSwiGLU(torch.autograd.Function):
@staticmethod
def forward(ctx, x, W_gate, W_up):
gate = x @ W_gate
up = x @ W_up
# SiLU(gate) = gate * sigmoid(gate)
sig = torch.sigmoid(gate)
silu_gate = gate * sig
out = silu_gate * up
# 保存反向传播需要的中间值
ctx.save_for_backward(x, W_gate, W_up, sig, silu_gate, up)
return out
@staticmethod
def backward(ctx, grad_out):
x, W_gate, W_up, sig, silu_gate, up = ctx.saved_tensors
# d(silu)/d(gate) = sig + gate * sig * (1 - sig)
# = sig * (1 + gate * (1 - sig))
dsilu = sig * (1 + (1 - sig) * silu_gate / sig)
grad_up = grad_out * silu_gate
grad_gate = grad_out * up * dsilu
grad_x = grad_gate @ W_gate.T + grad_up @ W_up.T
grad_W_gate = x.T @ grad_gate
grad_W_up = x.T @ grad_up
return grad_x, grad_W_gate, grad_W_up
# nsys: 追踪CPU-GPU交互、Kernel启动、CUDA API调用
# 适合分析整体性能瓶颈和GPU空闲时间
nsys profile -o trace_name \
--trace=cuda,nvtx,osrt \
--stats=true \
python train.py --config config.yaml
# 关键输出:
# - CUDA Kernel Statistics: 每个Kernel的调用次数/总时间
# - CUDA API Statistics: cudaMemcpy等API耗时
# - Timeline View: 可视化Kernel执行时间线
# - GPU Idle: GPU空闲时间 (理想<5%)
# 常用分析命令
nsys stats trace_name.nsys-rep --report cuda_kern_exec
# ncu: 深度分析单个Kernel的微架构指标
# 包括Occupancy, Memory Throughput, Compute Throughput等
ncu --set full \
--kernel-name regex:"flash_attn" \
--launch-skip 10 --launch-count 1 \
python train.py
# 关键指标解读:
# - Occupancy: 活跃Warp/最大Warp (理想>75%)
# - SM Compute Throughput: 算力利用率 (理想>80%)
# - Memory Throughput: 带宽利用率 (理想>80%)
# - L1/TEX Cache Hit Rate: L1命中率
# - L2 Cache Hit Rate: L2命中率
# - Warp Stall Reasons: Warp停顿原因分析
# * Long Scoreboard: 等待内存加载
# * Wait: 等待同步
# * Math Pipeline: 算术流水线满
# PyTorch Profiler: 分析PyTorch层面的性能
from torch.profiler import profile, ProfilerActivity, schedule
def profile_training(model, dataloader, optimizer):
with profile(
activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
schedule=schedule(
wait=1, # 跳过第1步 (warmup)
warmup=1, # warmup 1步
active=3, # 正式记录3步
repeat=1,
),
on_trace_ready=torch.profiler.tensorboard_trace_handler('./logs'),
record_shapes=True,
profile_memory=True,
with_stack=True,
) as prof:
for step, batch in enumerate(dataloader):
if step >= 5:
break
optimizer.zero_grad()
loss = model(batch)
loss.backward()
optimizer.step()
prof.step() # 通知profiler步进
# 打印统计
print(prof.key_averages().table(
sort_by="cuda_time_total", row_limit=20
))
# 内存分配统计
print(prof.key_averages().table(
sort_by="self_cuda_memory_alloc", row_limit=10
))
Roofline模型将Kernel性能表示为算术强度(FLOPs/Bytes)的函数,上界由峰值算力和峰值带宽决定:Performance = min(峰值算力, 算术强度 * 峰值带宽)
# Roofline模型分析
import numpy as np
# A100 80GB SXM4 参数
PEAK_FLOPS_FP16 = 312e12 # 312 TFLOPS
PEAK_BW_HBM = 2.0e12 # 2.0 TB/s
ARITH_INTENSITY_KNEE = PEAK_FLOPS_FP16 / PEAK_BW_HBM # 156 FLOPs/Byte
def roofline(arith_intensity):
"""计算Roofline上界"""
bw_bound = arith_intensity * PEAK_BW_HBM
compute_bound = PEAK_FLOPS_FP16
return min(bw_bound, compute_bound)
# 常见操作的算术强度分析
operations = {
'GEMM (4096x4096)': 2 * 4096 / (3 * 4), # ~682 FLOPs/Byte
'Attention (N=4096)': 2 * 4096 / (4 * 4), # ~512 FLOPs/Byte (理论)
'Attention (naive)': 2 * 1 / (4 * 4), # ~0.125 FLOPs/Byte (实际)
'RMSNorm': 3 / (6 * 4), # ~0.125 FLOPs/Byte
'Softmax': 5 / (4 * 4), # ~0.3125 FLOPs/Byte
}
print(f"拐点算术强度: {ARITH_INTENSITY_KNEE:.1f} FLOPs/Byte")
print(f"{'操作':<25} {'算术强度':>12} {'Roofline(TFLOPS)':>18} {'瓶颈':>10}")
for name, ai in operations.items():
perf = roofline(ai) / 1e12
bottleneck = "计算" if ai >= ARITH_INTENSITY_KNEE else "带宽"
print(f"{name:<25} {ai:>12.1f} {perf:>18.1f} {bottleneck:>10}")
# 输出示例:
# 拐点算术强度: 156.0 FLOPs/Byte
# GEMM (4096x4096) 682.7 312.0 计算
# Attention (N=4096) 512.0 312.0 计算
# Attention (naive) 0.1 0.3 带宽
# RMSNorm 0.1 0.1 带宽
# Softmax 0.3 0.3 带宽
| 格式 | 总位数 | 指数位 | 尾数位 | 最大值 | 最小正数 | 动态范围 |
|---|---|---|---|---|---|---|
| FP32 | 32 | 8 | 23 | 3.4e38 | 1.4e-45 | ~83 decades |
| FP16 | 16 | 5 | 10 | 65504 | 5.96e-8 | ~10 decades |
| BF16 | 16 | 8 | 7 | 3.4e38 | 1.18e-38 | ~76 decades |
| FP8 E4M3 | 8 | 4 | 3 | 448 | 1.95e-3 | ~5 decades |
| FP8 E5M2 | 8 | 5 | 2 | 57344 | 6.10e-5 | ~8 decades |
import torch
from torch.cuda.amp import autocast, GradScaler
# 混合精度训练: 前向用FP16/BF16, 主权重用FP32
model = MyModel().cuda()
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4)
# FP16需要GradScaler防止梯度下溢
# BF16不需要 (动态范围与FP32相同)
use_fp16 = True
scaler = GradScaler() if use_fp16 else None
for batch in dataloader:
optimizer.zero_grad()
# 前向传播: 自动混合精度
with autocast(dtype=torch.float16 if use_fp16 else torch.bfloat16):
loss = model(batch)
# 反向传播
if use_fp16:
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
else:
loss.backward()
optimizer.step()
# BF16更简单 (推荐用于新硬件)
# BF16 = FP32截断, 无需GradScaler
with autocast(dtype=torch.bfloat16):
loss = model(batch)
loss.backward()
optimizer.step()
# FP8训练 (需要H100/H200, TransformerEngine库)
# pip install transformer-engine
import transformer_engine.pytorch as te
from transformer_engine.common.recipe import Format, DelayedScaling
# 使用TE的FP8 Linear层替换标准Linear
model = te.TransformerLayer(
hidden_size=4096,
ffn_hidden_size=11008,
num_attention_heads=32,
)
# FP8训练循环
for batch in dataloader:
optimizer.zero_grad()
# 设置FP8缩放因子更新策略
with te.fp8_autocast(
enabled=True,
calibrations=DelayedScaling(
fp8_format=Format.HYBRID, # 前向E4M3, 反向E5M2
amax_history_len=16,
),
):
loss = model(batch)
loss.backward()
optimizer.step()
# FP8性能 (H100, Llama-7B, seq=2048):
# FP16: ~340 TFLOPS (68% 峰值)
# BF16: ~350 TFLOPS (70% 峰值)
# FP8: ~620 TFLOPS (63% 峰值, 但峰值翻倍)
# FP8 vs BF16: ~1.77x 加速
# 自定义CUDA算子: 融合Dropout + Residual + LayerNorm
# 1. 编写CUDA Kernel (C++)
# 2. 编写Python binding
# 3. 使用torch.utils.cpp_extension编译
cuda_source = r"""
#include <torch/extension.h>
#include <cuda_runtime.h>
__global__ void fused_dropout_residual_layernorm_kernel(
const float* input,
const float* residual,
const float* weight,
const float* bias,
float* output,
float* dropout_mask,
int N, int D,
float dropout_prob,
float eps
) {
int row = blockIdx.x;
int col = threadIdx.x;
if (col < D) {
int idx = row * D + col;
// Dropout + Residual
float val = input[idx];
if (dropout_mask[idx] > dropout_prob) {
val = val / (1.0f - dropout_prob) + residual[idx];
} else {
val = residual[idx];
}
// 存到共享内存做归约
__shared__ float s_val[1024];
s_val[col] = val;
__syncthreads();
// 计算mean (块内归约)
__shared__ float s_mean;
if (col == 0) {
float sum = 0.0f;
for (int i = 0; i < D; ++i) sum += s_val[i];
s_mean = sum / D;
}
__syncthreads();
// 计算variance
__shared__ float s_rstd;
if (col == 0) {
float var = 0.0f;
for (int i = 0; i < D; ++i) {
float diff = s_val[i] - s_mean;
var += diff * diff;
}
s_rstd = rsqrtf(var / D + eps);
}
__syncthreads();
// LayerNorm
output[idx] = (val - s_mean) * s_rstd * weight[col] + bias[col];
}
}
torch::Tensor fused_dropout_residual_layernorm(
torch::Tensor input,
torch::Tensor residual,
torch::Tensor weight,
torch::Tensor bias,
float dropout_prob,
float eps
) {
int N = input.size(0);
int D = input.size(1);
auto output = torch::empty_like(input);
auto dropout_mask = torch::rand_like(input);
fused_dropout_residual_layernorm_kernel<<<N, D>>>(
input.data_ptr<float>(),
residual.data_ptr<float>(),
weight.data_ptr<float>(),
bias.data_ptr<float>(),
output.data_ptr<float>(),
dropout_mask.data_ptr<float>(),
N, D, dropout_prob, eps
);
return output;
}
"""
from torch.utils.cpp_extension import load_inline
# JIT编译CUDA扩展
fused_op = load_inline(
name="fused_dropout_residual_layernorm",
cpp_sources=[],
cuda_sources=[cuda_source],
functions=["fused_dropout_residual_layernorm"],
verbose=True,
)
# 使用
output = fused_op.fused_dropout_residual_layernorm(
input, residual, weight, bias, 0.1, 1e-5
)
| 优化项 | 检查方法 | 目标值 |
|---|---|---|
| Occupancy | ncu --metrics sm__warps_active.avg.pct_of_peak_sustained_active | >75% |
| Compute Throughput | ncu --metrics sm__pipe_tensor_op_hmma_cycles_active.avg.pct_of_peak_sustained_active | >80% |
| Memory Throughput | ncu --metrics dram__throughput.avg.pct_of_peak_sustained_elapsed | >80% |
| L2 Hit Rate | ncu --metrics l2_tex_t_sector_hit_rate.pct | >60% |
| Warp Divergence | ncu --metrics sm__branch_divergent_threads.avg.pct_of_peak_sustained_active | <5% |
| Kernel Launch Overhead | nsys stats --report cuda_api_sum | <5% 总时间 |
| GPU Idle Time | nsys timeline view | <5% |