Dive into Deep Learning · §13.3
编译器、算子融合与图捕获
图捕获与追踪 · 值分支与动态形状 · 算子融合 · 整步编译 · CUDA 图
动机
gelu_ish(x) 启动 8 个独立内核,读 10 个数组、写 8 个数组(18 \times 61\text{ MiB} = 1.07\text{ GiB},而最低仅需 122\text{ MiB})。计算图
add 融合进 relu 或调度显存复用,编译器必须在内核执行之前捕获前向与反向计算图。追踪占位符
shape 与 dtype 但无数值的符号占位符(追踪器)执行 Python 函数,将每个张量原语记录成图,同时展开静态 Python 循环。torch.compile):TorchDynamo 拦截字节码,AOTAutograd 追踪反向传播,Inductor 生成带形状/数据类型守卫的融合 Triton/C++ 内核。控制流
torch.jit.trace):仅记录单个示例输入走的分支——速度快,但新输入应走另一分支时会悄然出错。fullgraph=True):抛出追踪期错误,要求在单个融合程序内改用图原语(torch.where 或 torch.cond)。torch.compile 默认):插入图断点,令 GPU 与 Python 同步以求值 if,随后再启动图 2。PyTorch 中的值分支
借助 torch._dynamo.explain 检视含数据依赖 if x.sum() > 0: 的函数,可见 TorchDynamo 如何在分支处拆分程序:
graphs: 2, breaks: 1
def forward(self, L_x_ : torch.Tensor):
l_x_ = L_x_
x = l_x_ * 2; l_x_ = None
sum_1 = x.sum()
gt = sum_1 > 0; sum_1 = None
return (gt, x)
def forward(self, L_x_ : torch.Tensor):
l_x_ = L_x_
sub = l_x_ - 1; l_x_ = None
return (sub,)
x * 2 与布尔标量 x.sum() > 0;Python 阻塞等待设备读回该布尔值,再调度图 2(x + 1 或 x - 1)。torch.where(x.sum() > 0, x + 1, x - 1)(或 torch.cond)替换 if,消除主机同步屏障并捕获单张图(fullgraph=True)。动态形状
由于编译内核会按张量形状特化分块大小与循环边界,改变输入长度会触发守卫失败与重编译:
compilations: 2
def forward(self, s77 : torch.SymInt, L_x_ : torch.Tensor):
l_x_ = L_x_
sin = torch.sin(l_x_); l_x_ = None
add = sin + 1; sin = None
return (add,)
SymInt s77)重编译,随后处理 n = 32 无需再次编译。分桶与填充
drop_last=True(或填充最后一个小批量)。算子融合
gelu_ish 全部 8 个运算,最后写回 DRAM 一次: \textrm{Traffic Reduction} \;=\; \frac{\textrm{bytes moved (eager)}}{\textrm{bytes moved (fused)}} \;=\; \frac{(10\textrm{ reads} + 8\textrm{ writes})\, n b}{(1\textrm{ read} + 1\textrm{ write})\, n b} \;=\; 9\times实测融合
即便融合后,gelu_ish 在 float32 下每 8\text{ B} 也仅执行 \sim 12\text{ FLOPs}(I \approx 1.5 \ll 82\text{ FLOP/byte}),因此即时与编译两个版本均保持访存受限:
eager: 1.25 ms/call, 920 GB/s
compiled: 0.15 ms/call, 878 GB/s
由于编译器融合可能重排浮点加法,务必先用 allclose 校验数值一致性。两版本均以 0.6\text{--}0.9\text{ TB/s} 流式访存,编译内核快了 8\text{--}11\times,与 9\times 的字节数比值相符。
Transformer FFN 融合
\frac{t_{\textrm{act (eager)}}}{t_{\textrm{FFN matmuls}}} \;=\; \frac{9 I^*}{d} \;\approx\; 0.72
bf16 FFN GEMM 在 165\text{ TFLOP/s} 下耗时 \sim 3.3\text{ ms}。gelu_ish 搬运 2.25\text{ GiB}(\sim 2.4\text{ ms},占 GEMM 耗时的 72\%);融合将流量缩减 9\times 至 256\text{ MiB}(\sim 0.27\text{ ms},占 GEMM 耗时的 < 8\%)。融合边界
整步预测
考虑宽度 1024、带 gelu_ish 激活的四层 MLP 在批量 B = 512、float32(tf32 张量核心,P = 82.6\text{ TFLOP/s})下的完整训练步(前向、均方误差损失、反向与 SGD 更新):
整步编译
对四层 MLP 训练步应用默认 torch.compile(train_step) 相对即时执行的加速不足 2\times,仍比 0.25\text{ ms} 的设备下界慢 5\text{--}10\times:
first call: 0.6 s
eager: 2.93 ms, compiled: 2.08 ms
break-even: about 700 steps
graphs: 2
torch.compile 在此仍开销受限:在 train_step 内调用 torch.autograd.grad 引发图断点(graphs: 2),且 Inductor 的 Python 封装器仍从 CPU 逐一发起每个编译内核。摊销编译耗时
由于图捕获、优化与内核代码生成在第一步付出前期挂钟时间 t_{\textrm{compile}},编译仅在运行超过 n^* 步后才划算:
n^* \;=\; \frac{t_{\textrm{compile}}}{t_{\textrm{eager}} - t_{\textrm{compiled}}}
开销区间
算子融合无法合并连续的矩阵乘法。考虑批量 B = 64 上 60 层 256 \times 256 线性层与 \tanh 激活构成的堆叠(每次前向 120 个运算):
内核重放
cudaGraphLaunch):单次 CPU 调用把整个 60+ 内核图交给 GPU 硬件调度器,消除逐内核 Python/驱动开销 h。item()、print)。实测重放
在 60 层堆叠上对比 eager、默认 torch.compile(fused)与 torch.compile(..., mode='reduce-overhead')(replayed),可将融合与启动重放分离开来:
eager: 2.14 ms/call, 17.8 µs per operation
compiled: 2.02 ms/call, 16.8 µs per operation
reduce-overhead: 0.28 ms/call, 2.4 µs per operation
wall clock 2.02 ms per step, device busy 0.31 ms (15%), matrix products 55%
0.17 ms 55% Kernel2<cutlass_80_tensorop_s1688gemm_64x64_16x6_tn_
0.08 ms 25% splitKreduce_kernel<32, 16, int, float, float, float
0.06 ms 20% triton_poi_fused_tanh_0
默认 torch.compile 仅让 GPU 忙碌 \sim 15\%,因为 Python 仍在逐个启动每层的 cuBLAS 与 Triton 内核;mode='reduce-overhead' 在一次启动中重放全部内核,将调用耗时压缩 7\times 至 \sim 0.3\text{ ms} 的设备忙碌时间。
训练步重放
对四层 MLP 训练步启用 mode='reduce-overhead' 会为前后向图与更新图分别录制 CUDA 图,将步时压至一毫秒以内:
training step, reduce-overhead: 0.71 ms/call, GPU busy 0.25 ms
autograd.grad 图断点处的 Python 开销上。实践陷阱
编译模型或训练步之前,先检查四种常见失效模式:
print(loss) 或 if loss.item() < 0.1: 会引发图断点或追踪错误;日志记录应留在编译函数之外。检验理解
用以下三个编译器设计场景检验理解:
float32 矩阵上的按行 softmax 在即时模式下运行 5 个内核:m = max(x)(1 读)、y = x - m(1 读 1 写)、e = exp(y)(1 读 1 写)、s = sum(e)(1 读)、p = e / s(1 读 1 写)。假设每行都能装入片上 SRAM,将 softmax 融合为 1 个内核的访存流量加速比是多少?bfloat16 矩阵乘。编译它能带来多少倍加速?解答:
核心要点
| 编译机制 | 目标区间 | 工作原理 | 本章具体基准 |
|---|---|---|---|
| 符号追踪 | 前置条件 | 在形状/数据类型占位符上运行一次 Python(TorchDynamo) |
捕获静态循环;值分支需 torch.where 或 torch.cond |
| 形状特化 | 前置条件 | 按输入形状特化分块大小(SymInt 守卫) |
不等长序列须填充/分桶以避免重编译 |
| 算子融合 | 访存带宽受限 | 将逐元素链与 SRAM 行归约合并为 1 次 DRAM 读 + 1 次写 | 8 算子 gelu_ish 流量从 18 \to 2 数组(9\times 加速) |
| CUDA 图重放 | 开销受限 | 录制内核启动描述符与指针;单次主机调用全部重放 | 60 层宽度 256 堆叠提速 7\times |
| 回本步数 n^* | 成本核算 | n^* = t_{\textrm{compile}} / (t_{\textrm{eager}} - t_{\textrm{compiled}}) | 在 > 10^3 训练步上摊销数秒编译耗时 |