Dive into Deep Learning · §13.8
案例研究:一步步加速 Transformer
剖析驱动的阿姆达尔上界 · 融合与 CUDA 图 · bf16 与 FlashAttention · 批量大小 · 多 GPU 扩展 · MFU
动机
bf16)下仅需 5.7\text{ ms}。fp32 基线(\sim 25\text{ ms}):比 bf16 计算下限慢 > 4\times(MFU 仅 \sim 23\%)。tf32 与 bf16 张量核心速率之差;其余 \sim 13\text{ ms} 来自未融合的带宽受限内核与派发缝隙。Roofline 定位
I \;=\; \frac{2 n d d'}{b\,(n d + d d' + n d')}
tf32 达 I = 125\text{--}185\text{ FLOP/B}(> I^* = 82),在 bf16 达 250\text{--}370\text{ FLOP/B}(> I^* = 164)。tf32 翻倍至 bf16 才能把 GEMM 耗时直接减半。基准规范
为了在同一标尺下评判每项优化,我们的基准在所有阶梯间保持模型、数据流水线和计时协议完全不变:
tokens_per_second):先预热 20 步,再在设备同步屏障间计时 3 个各 50 步的窗口,报告中位 \text{tokens/s}、增量加速比与窗口极差(\textrm{range}/\textrm{median})。allclose)。预测方法
tf32 \to bf16):当 GEMM 占单步比例 f 时,将 GEMM 速率翻倍带来 \ge \frac{1}{1 - f/2} 加速(若激活流量同步减半则趋近 2.0\times)。基线剖析
在批量大小 64(每步 8{,}192 词元)下剖析即时模式 float32 基线(tf32 矩阵乘、融合 AdamW),定位这 \sim 25\text{ ms} 的去向:
wall clock 25.78 ms per step, device busy 24.44 ms (95%), matrix products 64%
3.28 ms 13% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
3.08 ms 13% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_t
2.84 ms 12% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
2.41 ms 10% vectorized_elementwise_kernel<4, BinaryFunctor<float
编译与重放
用 torch.compile(model, dynamic=False, mode='reduce-overhead') 编译模型,将 Inductor 算子融合与静态形状 CUDA 图重放结合起来:
relative difference of the compiled logits: 1.5e-05
+ compile: 368,688 tokens/s (1.16x), windows within 0.0%
第二次剖析
第 1 阶后的剖析显示 GPU 在 99\text{--}100\% 的时间内忙碌,矩阵乘法占去设备时间的 f \approx 65\text{--}71\%:
wall clock 22.22 ms per step, device busy 22.27 ms (100%), matrix products 71%
4.01 ms 18% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
3.05 ms 14% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_t
2.83 ms 13% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
1.44 ms 6% fmha_cutlassB_f32_aligned_64x64_k64_sm80
bfloat16 混合精度):将张量核心 GEMM 从 tf32(82.6\text{ TFLOP/s})切换到 bfloat16(165.2\text{ TFLOP/s})可使矩阵乘法时间减半。降低精度
启用 torch.autocast('cuda', torch.bfloat16),让线性层与融合 FlashAttention(F.scaled_dot_product_attention)以 bfloat16 运行,同时将主权重、规范化、残差流与损失留在 float32:
relative difference of the bf16 logits: 2.0e-03
+ bf16: 643,350 tokens/s (1.74x), windows within 0.1%
bfloat16 GEMM 的张量核心效率高于 tf32,且中间融合内核搬运 2 字节 bfloat16 张量而非 4 字节 float32 张量。精度与带宽
拆解 torch.autocast('cuda', torch.bfloat16) 带来的 1.75\times 加速,可以看出降精度如何同时加快 Roofline 的两个区域:
float32 的部分(使其未达完整的 2.0\times):为保证数值稳定性,主权重、梯度、AdamW 矩估计(28\text{ B/param})、RMSNorm 归约、残差流相加与交叉熵对数概率仍保持 32 位。摊薄固定工作
由于 GPU 已 100\% 忙碌,将批量从 64 \to 512 个窗口放大 8\times(每步 65{,}536 词元)只能摊薄随参数量 N = 19\text{M} 而非词元数 n 缩放的设备工作:
fp32 权重、梯度、两矩估计),混合精度在 fp32 与 bf16 间转换权重/梯度(12\text{ B/param}),在 1\text{ TB/s} 带宽下耗时 \sim 0.75\text{ ms}(占批量 64 时 12.5\text{ ms} 单步的 \sim 6\%)。+ batch 512: 653,141 tokens/s (1.02x), windows within 0.0%
memory beyond weights and optimizer state: 8.6 GiB
第三次剖析
在批量大小 512 下,激活显存消耗 \sim 8\text{ GiB}(24\text{ GiB} GPU 仍空余三分之二),剖析揭示了最终单 GPU 配置的耗时平衡:
wall clock 100.34 ms per step, device busy 100.33 ms (100%), matrix products 57%
11.62 ms 12% ampere_bf16_s1688gemm_bf16_128x128_ldg8_f2f_stages_3
10.78 ms 11% ampere_bf16_s16816gemm_bf16_128x64_ldg8_f2f_tn
7.45 ms 7% Kernel2<cutlass_80_tensorop_bf16_s16816gemm_relu_bf1
5.62 ms 6% triton_poi_fused__unsafe_view_mm_mul_silu_silu_backw
fp32/bf16 类型转换)占其余 \sim 40\%。检查点预测
尽管批量大小 512 轻松放进 24\text{ GiB},开启逐块激活检查点(kept=False 分支)会发生什么?我们可以用两种方式界定吞吐量保留比例:
forward pass 30.8 ms of a 100.3 ms step: repeating it keeps at least 0.77 of the throughput
检查点实测
用 Checkpointed 包装全部 6 个 Transformer 块可将激活显存削减三分之二(7\text{--}9\text{ GiB} \to 2.6\text{--}3.2\text{ GiB}),同时保留 0.79\text{--}0.85\times 吞吐量——同时优于 0.75\times 的 FLOP 下界与 0.77\times 的前向计时下界:
+ checkpointing: 556,390 tokens/s (0.85x), windows within 0.0%
memory beyond weights and optimizer state: 3.2 GiB
forward pass alone: products 17.4 ms, other kernels 13.4 ms
added to the step: products 14.5 ms, other kernels 3.1 ms
单 GPU 结果
将所有单 GPU 阶梯并排汇总,把词元吞吐量换算为实测 TFLOP/s(6N\text{ FLOPs/token})和模型浮点运算利用率(\textrm{MFU} = \textrm{achieved FLOP/s} / 165.2\text{ TFLOP/s}):
configuration tokens/s step total TFLOP/s MFU
baseline 317,736 1.00x 1.00x 36.2 22%
+ compile 368,688 1.16x 1.16x 42.1 25%
+ bf16 643,350 1.74x 2.02x 73.4 44%
+ batch 512 653,141 1.02x 2.06x 74.5 45%
---------------------------------------------------------
+ checkpointing 556,390 0.85x 63.5 38% (not kept)
bfloat16 张量核心与算子/注意力融合驱动。数据并行代价模型
\textrm{Speedup}(k) \;\gtrsim\; \frac{k\, t_{\textrm{step}}(1)}{t_{\textrm{step}}(1) + t_{\textrm{allreduce}}(k)}
fp32 梯度耗时 31\text{ ms}(k=2)和 47\text{ ms}(k=4)。多 GPU 实测
在 k = 1, 2, 4 块 GPU 上运行生产级数据并行,检验两条方向相反的预测:
fp32, batch 64 per GPU: 364,947 tokens/s on one GPU
2 GPUs: allreduce 31 ms, speedup predicted 0.83x, measured 0.91x
4 GPUs: allreduce 48 ms, speedup predicted 1.27x, measured 1.36x
bf16, batch 512 per GPU: 662,971 tokens/s on one GPU
2 GPUs: allreduce 31 ms, speedup predicted 1.52x, measured 1.63x
4 GPUs: allreduce 48 ms, speedup predicted 2.69x, measured 2.92x
两条预测全部应验:独立 76\text{ MB} 全归约实测为 31\text{ ms}(k=2)和 48\text{ ms}(k=4)。批量 64 下,增加第二块 GPU 拖慢训练(\sim 0.85\text{--}0.95\times);bfloat16 批量 512 下,4 块 GPU 达到 \sim 2.9\text{--}3.2\times 单 GPU 吞吐量(\sim 1.9\text{--}2.3\text{M tokens/s},即相对单 GPU 基线达 6\text{--}7\times),反向分桶重叠贡献了高出无重叠下界的余量。
数值验证
快 2\times 的单 GPU 单步只有学到与 float32 基线相同的表征才有效。我们用两个初始化完全相同的模型(一个跑 baseline,一个跑 final,即 bf16 下的 + batch 512),在完全相同的 200 个 512 窗口小批量上训练(\sim 13\text{M} 词元,配合 50 步线性学习率预热):
loss at step 1 50 100 200 mean of last 20 validation
baseline 5.66 2.52 2.03 1.49 1.52 1.47
final 5.66 2.51 2.06 1.50 1.53 1.47
优化警示
compile、bf16、FlashAttention、强扩展 DP)总能缩短达到目标损失的时间;增大批量的改动只有在 b \lesssim b_{\textrm{noise}} 时才有益。最终核算
将内核剖析归一化为每 8{,}192 词元的毫秒数,把基线与最终单步的每一毫秒都与理想张量核心峰值时间(bf16 为 5.7\text{ ms},tf32 为 11.3\text{ ms})逐一对照:
ms per 8,192 tokens step at peak products other
baseline (tf32) 25.8 11.3 15.6 8.8
+ batch 512 (bf16) 12.5 5.7 7.1 5.4
检验理解
根据最终的毫秒核算(每 8{,}192 词元:接近 bf16 峰值的矩阵乘法 7\text{ ms} + 带宽受限非矩阵乘法内核 5\text{ ms} = 12\text{ ms}),回答三个问题:
bfloat16(165\text{ TFLOP/s})切到 fp8(330\text{ TFLOP/s}),把矩阵乘法时间从 7\text{ ms} \to 3.5\text{ ms} 减半,而保持 5\text{ ms} 非矩阵乘法内核不变。整步加速比是多少?bfloat16 矩阵乘法仍为 7\text{ ms}。整步加速比是多少?解答:
fp8 矩阵乘法:单步时间从 12\text{ ms} \to 3.5 + 5.0 = 8.5\text{ ms},加速比仅为 12 / 8.5 \approx 1.41\times(远低于 2\times)。fp8 矩阵乘法(7 \to 3.5\text{ ms})并收窄/融合激活访存流量(5 \to 2.5\text{ ms})。核心要点
| 优化阶梯 | 针对的瓶颈 | 阿姆达尔预测 | 实测收益 | 累积加速比 / MFU |
|---|---|---|---|---|
0. 基线(fp32/tf32) |
参考(26\text{ ms} / 8192 词元) | — | 1.00\times | 1.00\times(\sim 22\% MFU) |
1. torch.compile |
非矩阵乘法流量与主机派发 | \le 1.6\times | 1.16\times | 1.16\times(\sim 25\% MFU) |
2. bf16(FlashAttention 已开启) |
张量核心 GEMM | 1.5\text{--}2.0\times | 1.74\times | \approx 2.0\times(\sim 44\% MFU) |
| 3. 批量 64 \to 512 | 固定 40\text{ B/param} 单步工作(0.75\text{ ms}) | \approx 1.05\times | 1.02\times | \approx 2.1\times(\sim 45\% MFU) |
| 分支:激活检查点 | 激活显存(8.6 \to 3.2\text{ GiB}) | \ge 0.77\times | 0.85\times | 节省显存(未保留) |
| 4. 4 GPU 数据并行 | 单 GPU 上限(48\text{ ms} 全归约) | \approx 2.7\times(批量 512) | 相对 1 GPU \approx 2.9\times | 相对 1 GPU 基线 \approx 6\times |