Computation Graphs and Compilation

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

Why an Eight-Op Activation Moves 9× the Needed Bytes

Motivation

  • Redundant DRAM round trips: In eager mode, the 8-op 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).
  • Per-kernel host dispatch: On small tensors, Python pays launch latency h (10\text{--}100\,\mu\text{s}) for each of the 8 kernels.
  • Compiler cure: Operator fusion keeps intermediates in registers (9\times less DRAM traffic) and CUDA graph replay collapses host dispatch to 1 call.

Eager Autograd vs. Ahead-of-Time Graph Capture

Computation Graphs

  • Why eager autograd arrives too late: Eager mode builds a backward tape dynamically during the forward pass—by the time the tape exists, every forward operation has already paid host launch latency h and flushed its output to GPU DRAM.
  • Ahead-of-time graph capture: To fuse add into relu or schedule memory reuse, a compiler must capture the forward and backward computation graphs before executing the kernels.

Symbolic Tracing and Compilation Pipelines

Tracing Placeholders

  • How tracing works: On the first call, the framework executes the Python function using symbolic placeholders (tracers) carrying shape and dtype but no numerical values, recording every tensor primitive into a graph while unrolling static Python loops.
  • Lowering & caching (torch.compile): TorchDynamo intercepts bytecode, AOTAutograd traces the backward pass, and Inductor emits fused Triton/C++ kernels guarded by shape/dtype checks.

Three Ways a Tracer Handles Data-Dependent Branches

Control Flow

  • 1. Freeze (torch.jit.trace): Records only the branch taken by one example input—fast, but silently wrong when new inputs take the other branch.
  • 2. Refuse (fullgraph=True): Raises a trace-time error and requires graph primitives (torch.where or torch.cond) inside a single fused program.
  • 3. Fall back (torch.compile default): Inserts a graph break, synchronizing the GPU with Python to evaluate if before launching Graph 2.

Graph Breaks vs. torch.where in torch.compile

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,)
  • Two graphs, one break: Graph 1 computes 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).
  • Single-graph rewrite: Replacing 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).

Shape Guards and Symbolic Dimensions in Dynamo

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,)
  • Automatic symbolic generalization: Dynamo compiles once for n = 8, reuses the cached kernel on the second n = 8 call, and on seeing n = 16 recompiles with a symbolic integer dimension (SymInt s77) that handles n = 32 without further compilation.

Handling Ragged Sequences Without Recompilation

Bucketing & Padding

  • Unpadded ragged lengths (100, 128, 75): Every new sequence length triggers a multi-second compilation pause, thrashing the training loop.
  • Power-of-two / multiple-of-64 bucketing: Padding lengths 100 and 75 with masked tokens to bucket 128 compiles and caches only 1 kernel.
  • Epoch tail batches: Always pass drop_last=True (or pad the final batch) when compiling for static shapes or replaying CUDA graphs.

Operator Fusion Eliminates Off-Chip DRAM Round Trips

Operator Fusion

  • Register-resident intermediates: A fused kernel loads each element x_i from DRAM once, evaluates all 8 operations of 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\times

Fused gelu_ish Runs 9× Faster as Predicted by Bytes

Measuring 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.

Impact of Activation Fusion Inside a 1B GPT Block

Transformer FFN Fusion

\frac{t_{\textrm{act (eager)}}}{t_{\textrm{FFN matmuls}}} \;=\; \frac{9 I^*}{d} \;\approx\; 0.72

  • Independent of token count M: On M = 8{,}192 tokens (d = 2048, hidden 4d = 8192), the two bf16 FFN GEMMs take \sim 3.3\text{ ms} at 165\text{ TFLOP/s}.
  • Eager vs. fused activation: Unfused 8-op 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).

What Compilers Fuse vs. Hand-Tiled Kernel Algorithms

Scope of Fusion

  • Automatically fused: Elementwise chains (activations, residual adds, AdamW) and SRAM-resident row reductions (RMSNorm, row softmax) collapse into 1 read + 1 write.
  • Delegated to library GEMMs: Dense matrix products (\mathbf{X}\mathbf{W}) already run near P via cuBLAS/CUTLASS tiles, optionally fusing bias/activation epilogues.
  • Requires custom tiled algorithms: Avoiding the T \times T attention matrix in DRAM requires FlashAttention’s online softmax rescaling across K/V tiles.

Accounting for a Complete 4-Layer MLP Training Step

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}):

  • Compute floor (0.14\text{ ms}): Four forward and seven backward matmuls (the first layer needs no input gradient) perform 11 \times 2 \cdot 512 \cdot 1024^2 \approx 1.18 \times 10^{10}\text{ FLOPs}, taking 0.14\text{ ms} at 82.6\text{ TFLOP/s}.
  • Bandwidth floor (0.10\text{ ms}): Streaming the 16\text{ MiB} of parameters and 2\text{ MiB} activations across \sim 6 passes moves \sim 96\text{ MiB}, taking 0.10\text{ ms} at 1\text{ TB/s} (\sim \mathbf{0.25\text{ ms}} total device work).
  • Eager launch floor (> 1.0\text{ ms}): Eager execution dispatches > 100 small operations at h \ge 10\,\mu\text{s} each, making the eager step overhead-bound by a factor of 5\text{--}10\times.

Compiling the Training Step: Graph Breaks and Launches

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
  • Why default 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.

Compilation Break-Even Step Count n*

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}}}

  • Worked example: If compilation takes t_{\textrm{compile}} = 30\text{ s} and saves t_{\textrm{eager}} - t_{\textrm{compiled}} = 10\text{ ms/step}, the run breaks even at n^* = 3{,}000\text{ steps}—tiny next to a 100{,}000-step training run, but a net loss for a 200-step quick evaluation.
  • Persistent compilation caches: Compilers can cache compiled binaries on disk, reducing t_{\textrm{compile}} on subsequent process runs from tens of seconds to a fraction of a second.

When Fusion Is Not Enough: Thin-Layer Launch Overhead

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):

  • Device work per layer (< 2\,\mu\text{s}): Each layer performs 2 \cdot 64 \cdot 256^2 = 8.4 \times 10^6\text{ FLOPs} and moves 384\text{ KiB} (< 0.5\,\mu\text{s} on the roofline, or \sim 1\text{--}2\,\mu\text{s} above the hardware kernel-start floor).
  • Host launch cost (120\,h): Launching even 60 fused kernels one by one from Python costs 60 \times 13\,\mu\text{s} \approx 0.8\text{ ms} of CPU dispatch vs. \sim 0.15\text{ ms} of GPU work, leaving the GPU idle > 80\% of the time.

CUDA Graphs: Record Once, Replay in One Host Launch

Kernel Replay

  • Capture phase: A warm-up run on a dedicated stream records every kernel descriptor, grid shape, and exact GPU memory pointer into a static graph.
  • Replay phase (cudaGraphLaunch): One CPU call hands the entire 60+ kernel graph to the GPU hardware scheduler, eliminating per-kernel Python/driver overhead h.
  • Static contract: Shapes and buffer addresses are baked in—no dynamic shapes or host sync barriers (item(), print) are allowed inside the graph.

CUDA Graph Replay Speeds Up the 60-Layer Stack 7×

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.

Replaying the MLP Training Step Under 1 Millisecond

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
  • Remaining gap: The GPU is busy for our predicted 0.25\text{ ms}, while the remaining \sim 0.5\text{ ms} is spent in Python at the autograd.grad graph break between the two replayed graphs.

When Not to Compile: Practical Failure Modes

Practical Pitfalls

Before compiling a model or training step, check four practical failure modes:

  • Short runs (N_{\textrm{steps}} < n^*): If a script runs only a few dozen evaluation batches, compilation time t_{\textrm{compile}} will exceed the total execution time saved.
  • Ragged shapes per step: Calling a compiled function on a sequence that grows by 1 token every step triggers continuous recompilation unless padded into fixed buckets.
  • In-graph host reads & logging: Calling 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.
  • Line-by-line debugging: Stack traces and breakpoints inside fused kernels do not map line-by-line to Python; always debug numerical correctness in eager mode first.

Concept Check: Fusion Speedups, Replay, and Padding

Check Your Understanding

Test your understanding with three compiler design scenarios:

  1. A row-wise softmax over an R \times d 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?
  2. A step launches 400 small kernels at h = 8\,\mu\text{s} of host dispatch time each, while total GPU kernel execution time is 1.5\text{ ms}. Which regime binds, and what is the maximum speedup from CUDA graph replay?
  3. A single step consists of one 8192 \times 8192 bfloat16 matrix product. How much will compiling it speed it up?

Answers:

  1. \mathbf{4\times} speedup: The 5 eager kernels perform 5\text{ reads} + 3\text{ writes} = 8 Rd transfers (ignoring O(R) row scalars); a single fused SRAM reduction performs 1\text{ read} + 1\text{ write} = 2 Rd transfers (8/2 = 4\times).
  2. Overhead-bound: Host dispatch takes 400 \times 8\,\mu\text{s} = 3.2\text{ ms} > 1.5\text{ ms}. CUDA graph replay collapses host dispatch to one launch, shrinking step time from 3.2\text{ ms} \to 1.5\text{ ms} (\approx 2.1\times speedup).
  3. 1.0\times (no speedup): The 8192^2 GEMM is already compute-bound near 165\text{ TFLOP/s} inside a single cuBLAS kernel; there are no elementwise transfers to fuse and no launch gaps to hide.

Summary: Graph Capture, Operator Fusion, and Replay

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