Dive into Deep Learning · §13.3
Compilers, Operator Fusion, and Graph Capture
graph capture & tracing · value branches & dynamic shapes · operator fusion · whole-step compilation · CUDA graphs
Motivation
gelu_ish(x) launches 8 separate kernels that read 10 arrays and write 8 arrays (18 \times 61\text{ MiB} = 1.07\text{ GiB} vs. 122\text{ MiB} minimum).Computation Graphs
add into relu or schedule memory reuse, a compiler must capture the forward and backward computation graphs before executing the kernels.Tracing Placeholders
shape and dtype but no numerical values, recording every tensor primitive into a graph while unrolling static Python loops.torch.compile): TorchDynamo intercepts bytecode, AOTAutograd traces the backward pass, and Inductor emits fused Triton/C++ kernels guarded by shape/dtype checks.Control Flow
torch.jit.trace): Records only the branch taken by one example input—fast, but silently wrong when new inputs take the other branch.fullgraph=True): Raises a trace-time error and requires graph primitives (torch.where or torch.cond) inside a single fused program.torch.compile default): Inserts a graph break, synchronizing the GPU with Python to evaluate if before launching Graph 2.Value Branches in PyTorch
Inspecting a function with a data-dependent if x.sum() > 0: via torch._dynamo.explain reveals how TorchDynamo splits the program across the branch:
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 and the boolean scalar x.sum() > 0; Python blocks on the device to read that boolean and dispatches Graph 2 (x + 1 or x - 1).if with torch.where(x.sum() > 0, x + 1, x - 1) (or torch.cond) eliminates the host sync barrier and captures a single graph (fullgraph=True).Dynamic Shapes
Because compiled kernels specialize tile sizes and loop bounds to tensor shapes, changing input lengths triggers guard failures and recompilation:
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) that handles n = 32 without further compilation.Bucketing & Padding
drop_last=True (or pad the final batch) when compiling for static shapes or replaying CUDA graphs.Operator Fusion
gelu_ish inside on-chip registers, and writes the final result to DRAM once: \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\timesMeasuring Fusion
Even after fusion, gelu_ish performs only \sim 12\text{ FLOPs} per 8\text{ B} in float32 (I \approx 1.5 \ll 82\text{ FLOP/byte}), so both eager and compiled versions remain bandwidth-bound:
eager: 1.25 ms/call, 920 GB/s
compiled: 0.15 ms/call, 878 GB/s
Always verify allclose first because compiler fusion can reorder floating-point additions. Both versions stream at 0.6\text{--}0.9\text{ TB/s}, and the compiled kernel runs 8\text{--}11\times faster, matching our 9\times byte-count ratio.
Transformer FFN Fusion
\frac{t_{\textrm{act (eager)}}}{t_{\textrm{FFN matmuls}}} \;=\; \frac{9 I^*}{d} \;\approx\; 0.72
bf16 FFN GEMMs take \sim 3.3\text{ ms} at 165\text{ TFLOP/s}.gelu_ish moves 2.25\text{ GiB} (\sim 2.4\text{ ms}, or 72\% of GEMM time); fusion cuts traffic 9\times to 256\text{ MiB} (\sim 0.27\text{ ms}, < 8\% of GEMM time).Scope of Fusion
Whole-Step Prediction
Consider one full training step (forward, MSE loss, backward, and SGD update) for a 4-layer MLP of width 1024 with gelu_ish activations on batch B = 512 in float32 (tf32 Tensor Cores, P = 82.6\text{ TFLOP/s}):
Whole-Step Compilation
Applying default torch.compile(train_step) to our 4-layer MLP step yields less than a 2\times speedup over eager execution, remaining 5\text{--}10\times slower than the 0.25\text{ ms} device floor:
first call: 0.6 s
eager: 2.93 ms, compiled: 2.08 ms
break-even: about 700 steps
graphs: 2
torch.compile stays overhead-bound here: Calling torch.autograd.grad inside train_step causes a graph break (graphs: 2), and Inductor’s Python wrapper still issues each compiled kernel individually from the CPU.Amortizing Compile Time
Because graph capture, optimization, and kernel code generation take an upfront wall-clock time t_{\textrm{compile}} on the first step, compilation pays off only after n^* steps:
n^* \;=\; \frac{t_{\textrm{compile}}}{t_{\textrm{eager}} - t_{\textrm{compiled}}}
Overhead Regime
Operator fusion cannot merge consecutive matrix multiplications. Consider a 60-layer network of 256 \times 256 linear layers and \tanh activations on batch B = 64 (120 operations per forward call):
Kernel Replay
cudaGraphLaunch): One CPU call hands the entire 60+ kernel graph to the GPU hardware scheduler, eliminating per-kernel Python/driver overhead h.item(), print) are allowed inside the graph.Measuring Replay
Comparing eager, default torch.compile (fused), and torch.compile(..., mode='reduce-overhead') (replayed) on our 60-layer stack separates fusion from launch replay:
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
Default torch.compile leaves the GPU busy for only \sim 15\% of the call because Python still launches each layer’s cuBLAS and Triton kernels one by one; mode='reduce-overhead' replays all kernels in one launch, cutting call time 7\times down to the \sim 0.3\text{ ms} device busy time.
Step Replay
Applying mode='reduce-overhead' to our 4-layer MLP training step records CUDA graphs for the forward/backward and update graphs, cutting step time to under a millisecond:
training step, reduce-overhead: 0.71 ms/call, GPU busy 0.25 ms
autograd.grad graph break between the two replayed graphs.Practical Pitfalls
Before compiling a model or training step, check four practical failure modes:
print(loss) or if loss.item() < 0.1: inside the compiled step forces graph breaks or trace errors; keep logging outside the compiled step function.Check Your Understanding
Test your understanding with three compiler design scenarios:
float32 matrix runs in eager mode as 5 kernels: m = max(x) (1 read), y = x - m (1 read, 1 write), e = exp(y) (1 read, 1 write), s = sum(e) (1 read), p = e / s (1 read, 1 write). Assuming each row fits in on-chip SRAM, what is the memory-traffic speedup of fusing softmax into 1 kernel?bfloat16 matrix product. How much will compiling it speed it up?Answers:
Key Takeaways
| Compiler Mechanism | Target Regime | How It Works | Concrete Chapter Benchmark |
|---|---|---|---|
| Symbolic Tracing | Prerequisite | Runs Python once on shape/dtype placeholders (TorchDynamo) |
Captures static loops; value branches need torch.where or torch.cond |
| Shape Specialization | Prerequisite | Specializes tile sizes to input shapes (SymInt guards) |
Ragged sequences must be padded/bucketed to avoid recompilation |
| Operator Fusion | Bandwidth-bound | Merges elementwise chains & SRAM row reductions into 1 DRAM read + 1 write | 8-op gelu_ish traffic cut from 18 \to 2 arrays (9\times speedup) |
| CUDA Graph Replay | Overhead-bound | Records kernel launch descriptors & pointers; replays all in 1 host call | 60-layer width-256 stack sped up 7\times |
| Break-Even Step n^* | Cost check | n^* = t_{\textrm{compile}} / (t_{\textrm{eager}} - t_{\textrm{compiled}}) | Amortizes multi-second compile cost over > 10^3 training steps |