13.3 Computation Graphs and Compilation

In Section 13.1, the eight-operation activation chain gelu_ish took eight to nine times as long as a single addition on the same tensor: each operation ran as a separate GPU kernel that read its inputs from DRAM and wrote its output back (18 array transfers instead of 2). On a small tensor, the same chain is slow for a second reason: every operation is dispatched from Python, and the host takes longer to launch each kernel than the GPU takes to run it.

Both costs stem from eager execution, which runs operations one at a time as Python reaches them. Handing the whole program to a compiler before execution addresses both: operation fusion merges elementwise chains into a single kernel that reads the input once and writes the output once (curing the bandwidth-bound cost), and kernel replay records a sequence of kernel launches and replays them with a single host call (curing the overhead-bound cost). A large compute-bound matrix product gains from neither on its own, though compiling the elementwise operations around it still pays off.

import os
torch.set_float32_matmul_precision('high')  # fp32 matmuls may use tf32
# Detach PyTorch's profiler from the GPU when a profile ends; without this,
# every kernel launch after the first profile stays about 30% slower
os.environ['TEARDOWN_CUPTI'] = '1'

13.3.1 Graph Capture#

13.3.1.1 Computation Graphs#

The operations of a neural network form a directed computation graph whose nodes are primitive operations and whose edges carry tensors (Figure 13.3.1). While eager autograd (Section 1.5) records a backward tape during the forward pass, that record arrives too late to optimize the forward pass itself: by the time the tape exists, every operation has already paid host dispatch time hh and made its own round trip through GPU memory. Optimizing the program requires graph capture—obtaining the computation graph before the operations execute.

Figure 13.3.1:

The computation graph of a two-layer network with a loss. Automatic differentiation walks it backward; a compiler that has the whole graph before the forward pass can rewrite it.

13.3.1.2 Tracing#

Modern frameworks capture graphs by tracing: running the Python function once on symbolic placeholders that carry shape and dtype but no concrete numerical values (Figure 13.3.2). Every tensor operation on a placeholder is recorded as a node in the graph, while ordinary Python control flow that depends only on static shapes or loop bounds unrolls during tracing. A compiler then lowers the captured graph into fused GPU kernels and caches them for future calls with matching input shapes and dtypes.

Figure 13.3.2:

Graph capture. The first call traces the function on placeholders; a compiler turns the recorded graph into kernels, which later calls with the same shapes and dtypes reuse. A branch on a tensor's value cannot be recorded, and a new shape or dtype may start a new capture.

In PyTorch, torch.compile intercepts Python bytecode via TorchDynamo (Ansel et al., 2024), traces tensor operations into a graph, uses AOTAutograd to capture the backward graph ahead of time, and compiles both into fused Triton and C++ kernels via Inductor. Dynamo attaches guards on input shapes and dtypes so subsequent calls jump straight to the compiled kernels when guards pass.

13.3.1.3 Branches on Values#

Because placeholders carry no numerical values, a tracer cannot evaluate a data-dependent Python branch such as if x.sum() > 0:. A capture system has three possible responses:

  1. Freeze the branch taken by a concrete example input—fast, and silently wrong when future inputs should take the other branch.
  2. Refuse with an error, requiring the programmer to express the branch as a graph primitive: either a select (which evaluates both branches and picks one) or a conditional op.
  3. Fall back to Python by inserting a graph break: end the first graph at the condition, let Python evaluate the branch on the materialized value, and resume in a second compiled graph.

Branches on static tensor shapes (if x.shape[0] > 4:) are known at trace time and require no special handling. Let us see how our framework handles a data-dependent branch.

def f(x):
    x = x * 2
    if x.sum() > 0:        # Python needs the value of this comparison
        return x + 1
    return x - 1

explanation = torch._dynamo.explain(f)(torch.randn(8, device=d2l.try_gpu()))
print(f'graphs: {explanation.graph_count}, '
      f'breaks: {explanation.graph_break_count}')
for graph in explanation.graphs:
    print(graph.code.strip())
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,)

By default, torch.compile inserts a graph break: Graph 1 computes x * 2 and x.sum() > 0, returns control to Python to evaluate the if, and dispatches Graph 2 for the chosen branch. Passing fullgraph=True (or using torch.export) refuses graph breaks instead, while rewriting the branch with torch.where(x.sum() > 0, x + 1, x - 1) captures a single graph. The older torch.jit.trace freezes the branch of its example input.

13.3.1.4 Shapes and Recompilation#

Because compilers specialize kernels to tensor shapes (tile sizes, loop bounds, memory layouts), changing input shapes—such as a short final minibatch of an epoch or variable sequence lengths—triggers recompilation unless the compiler generalizes to symbolic dimensions. In practice, we either pad inputs to a small set of bucketed shapes or mark varying axes as dynamic.

compilations = []
def recording_backend(gm, example_inputs):  # Called once per compilation
    compilations.append(gm)
    return gm.forward                       # Run the captured graph as is

g = torch.compile(lambda x: torch.sin(x) + 1, backend=recording_backend)
for n in (8, 8, 16, 32):
    g(torch.ones(n, device=d2l.try_gpu()))
print(f'compilations: {len(compilations)}')
print(compilations[-1].code.strip())
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,)

Dynamo compiles on the first call (n=8n = 8), reuses that graph on the second call (n=8n = 8), and upon seeing n=16n = 16 recompiles with a symbolic dimension (SymInt s77), which then handles n=32n = 32 without further compilation.

13.3.2 Operation Fusion#

13.3.2.1 Counting Memory Traffic#

In eager execution, gelu_ish(x) runs eight elementwise kernels (six unary ops that each read one array and write one, plus two binary ops that each read two arrays and write one), moving 10+8=1810 + 8 = 18 arrays of size nbnb bytes. A fused kernel reads x once, holds all seven intermediate values in registers, and writes the output once (Figure 13.3.3), cutting memory traffic by

bytes moved, eagerbytes moved, fused=(10+8) nb(1+1) nb=9.\frac{\textrm{bytes moved, eager}}{\textrm{bytes moved, fused}} = \frac{(10 + 8)\, n b}{(1 + 1)\, n b} = 9.

Because even the fused kernel performs only ~12 FLOPs per 8 bytes in fp32 (I≈1.5≪82I \approx 1.5 \ll 82 FLOP/byte), both versions are bandwidth-bound and fusion should speed up gelu_ish by roughly 9×9\times.

Figure 13.3.3:

Memory traffic of gelu_ish. Eager execution runs eight kernels that read ten arrays and write eight; the fused kernel reads the input once, keeps the seven intermediate results in registers, and writes the result once.

x = torch.randn(4000, 4000, device=d2l.try_gpu())
compiled = torch.compile(d2l.gelu_ish)
assert torch.allclose(d2l.gelu_ish(x), compiled(x), atol=1e-6)  # Same answer
arrays_moved = {'eager': 18, 'compiled': 2}  # In units of x.nbytes
for desc, fn in (('eager', d2l.gelu_ish), ('compiled', compiled)):
    b = d2l.Benchmark(lambda: fn(x), desc=desc)
    print(f'{b}, {arrays_moved[desc] * x.nbytes / b.time / 1e9:.0f} GB/s')
eager: 1.25 ms/call, 920 GB/s
compiled: 0.15 ms/call, 878 GB/s

Both versions stream through memory at 0.6–0.9 TB/s, and the compiled version runs 8×8\times to 11×11\times faster—right around the 9×9\times byte-count prediction—simply by eliminating 16 of the 18 DRAM transfers.

How much does activation fusion matter inside a Transformer block? In a 1B-parameter GPT of width d=2048d = 2048 and FFN hidden width 4d=81924d = 8192 in bf16, an unfused 8-op activation on MM tokens moves 18⋅4dM⋅2=144 dM18 \cdot 4dM \cdot 2 = 144\,dM bytes, while the two surrounding FFN matrix products perform 2⋅2⋅M⋅d⋅4d=16 d2M2 \cdot 2 \cdot M \cdot d \cdot 4d = 16\,d^2M FLOPs. Their time ratio is independent of the token count MM:

tactivationtproducts=144 dM/β16 d2M/P=9I∗d≈0.72\frac{t_\textrm{activation}}{t_\textrm{products}} = \frac{144\, dM/\beta}{16\, d^2 M/P} = \frac{9 I^*}{d} \approx 0.72

for I∗=164I^* = 164 FLOP/byte and d=2048d = 2048. Unfused, the activation takes nearly three quarters as long as the two matrix products; fused, under a tenth.

13.3.2.2 Fusion Patterns#

Compilers routinely fuse two patterns:

  • Elementwise chains (activations, residual adds, dropout masks, optimizer updates), where each thread computes element ii of the output in registers.
  • Row reductions (softmax, LayerNorm, RMSNorm), where each row fits in on-chip SRAM so the kernel reads the row once, computes the reduction and normalization on chip, and writes the output once.

Compilers do not invent new algorithms: they cannot speed up a compute-bound matrix product, nor can they discover tiled algorithms like FlashAttention (Section 10.5, (Dao et al., 2022)), which avoids materializing the T×TT \times T attention matrix via online softmax rescaling (written by hand in CUDA or Triton (Tillet et al., 2019)).

13.3.3 Compiling a Training Step#

Now let us compile a complete training step—forward pass, squared loss, backward pass, and SGD update—for a 4-layer MLP of width 1,024 with gelu_ish activations on a batch of 512 examples.

class MLP(nn.Module):
    """Linear layers with the gelu_ish chain between them."""
    def __init__(self, width=1024, depth=4):
        super().__init__()
        self.layers = nn.ModuleList(nn.Linear(width, width)
                                    for _ in range(depth))

    def forward(self, X):
        for layer in self.layers[:-1]:
            X = d2l.gelu_ish(layer(X))
        return self.layers[-1](X)

def train_step(net, X, Y, lr=0.1):  # Forward, backward, SGD update
    loss = ((net(X) - Y) ** 2).mean()
    grads = torch.autograd.grad(loss, list(net.parameters()))
    with torch.no_grad():
        for p, g in zip(net.parameters(), grads):
            p -= lr * g
    return loss

Let us predict the step time. The four forward products and seven backward products (the first layer needs no input gradient) perform ~11×2⋅512⋅10242≈1.2×101011 \times 2 \cdot 512 \cdot 1024^2 \approx 1.2 \times 10^{10} FLOPs (0.14 ms at 82.6 TFLOP/s in tf32), while reading and updating the 16 MiB of parameters moves ~96 MiB (0.10 ms at 1 TB/s), for ~0.25 ms of actual device work. Eager execution, however, issues over 100 individual operations at h≥10h \ge 10 µs each (> 1 ms of host launch overhead), making the eager step overhead-bound.

Because compilation costs tcompilet_\textrm{compile} on the first call and saves teager−tcompiledt_\textrm{eager} - t_\textrm{compiled} per step, it breaks even after

n∗=tcompileteager−tcompiled(13.3.1)n^* = \frac{t_\textrm{compile}}{t_\textrm{eager} - t_\textrm{compiled}} \tag{13.3.1}

steps.

net = MLP().to(d2l.try_gpu())
X, Y = (torch.randn(512, 1024, device=d2l.try_gpu()) for _ in range(2))
compiled_step = torch.compile(train_step)
t_first = d2l.Benchmark(lambda: compiled_step(net, X, Y),
                        warmup=0, repeats=1).time  # Includes compilation
t_eager = d2l.Benchmark(lambda: train_step(net, X, Y)).time
t_compiled = d2l.Benchmark(lambda: compiled_step(net, X, Y)).time
saved = t_eager - t_compiled  # Per step; a difference of two short times
print(f'first call: {t_first:.1f} s\n'
      f'eager: {1000 * t_eager:.2f} ms, compiled: {1000 * t_compiled:.2f} ms\n'
      'break-even: ' + (f'about {float(f"{t_first / saved:.1g}"):,.0f} steps'
                        if saved > 0 else 'never, compiled is not faster'))
# explain is internal to torch; it clears the compile cache and recompiles
print('graphs:', torch._dynamo.explain(train_step)(net, X, Y).graph_count)
first call: 0.6 s
eager: 2.93 ms, compiled: 2.08 ms
break-even: about 700 steps
graphs: 2

Default torch.compile speeds up the step by less than 2×2\times, remaining 5–10× above the 0.25 ms of device work: torch.autograd.grad causes a graph break between the forward/backward pass and the parameter update, and Inductor's generated wrapper still launches each kernel individually from Python.

13.3.4 Kernel Replay#

Fusion cannot merge matrix multiplications, and when the remaining kernels are short, per-kernel host launches dominate step time. Consider a stack of 60 bias-free linear layers of width 256 with tanh⁡\tanh activations on a batch of 64 examples (120 operations per call). Each layer performs only 8.4×1068.4 \times 10^6 FLOPs and moves 384 KiB (< 0.5 µs on the roofline, and ~4–5 µs of actual device execution, at ~1–3 µs per kernel above the hardware kernel-start floor), whereas eager execution pays hh per operation (120 h120\,h in total).

To eliminate per-kernel host dispatch, NVIDIA GPUs support CUDA graphs: the runtime records the sequence of kernel launches and their fixed buffer addresses once, then replays the entire sequence with a single host launch. Because buffer addresses and shapes are baked into the recording, inputs are copied into fixed buffers before replay and outputs are overwritten on the next replay.

Figure 13.3.4:

Host and device timelines for a stack of short kernels. With one launch per kernel, the GPU waits for the host before every kernel and idles in between. A CUDA graph replays the whole sequence after a single launch, so the kernels run back to back.

Figure 13.3.4 compares the two timelines. The kernels themselves take the same time in both; what the replay removes is the idle time between them.

deep = nn.Sequential(*[m for _ in range(60)  # 120 operations per call
                       for m in (nn.Linear(256, 256, bias=False), nn.Tanh())])
deep = deep.to(d2l.try_gpu())
x = torch.randn(64, 256, device=d2l.try_gpu())

fused = torch.compile(deep)  # Inductor kernels, launched one at a time
replayed = torch.compile(deep, mode='reduce-overhead')  # As a CUDA graph
with torch.no_grad():  # Inference: every call is a complete step
    fused(x)
    replayed(x)  # Compiles and warms up; the next call records
    times = {}
    for desc, f in (('eager', deep), ('compiled', fused),
                    ('reduce-overhead', replayed)):
        t = times[desc] = d2l.Benchmark(lambda: f(x), repeats=100).time
        print(f'{desc}: {1000 * t:.2f} ms/call, '
              f'{1e6 * t / 120:.1f} µs per operation')
    # The kernels of the compiled stack, against the time of a call
    d2l.show_profile(d2l.kernel_times(lambda: fused(x)),
                     1000 * times['compiled'], rows=3)
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 (fused) is barely faster than eager execution: because Inductor delegates the matrix products to cuBLAS, it cannot fuse the tanh⁡\tanh into them, and it still launches all kernels one by one from Python (leaving the GPU busy for only ~15% of the call). Enabling CUDA graphs via mode='reduce-overhead' replays the entire sequence in one launch, cutting the call time by ~7×7\times down to the ~0.3 ms of actual GPU execution.

Applying mode='reduce-overhead' to the MLP training step of Section 13.3.3 similarly cuts the step time to under a millisecond, with the GPU busy for the predicted 0.25 ms and the remainder spent in Python at the autograd.grad graph break.

replayed_step = torch.compile(train_step, mode='reduce-overhead')
t = d2l.Benchmark(lambda: replayed_step(net, X, Y)).time
busy = sum(d2l.kernel_times(lambda: replayed_step(net, X, Y)).values())
print(f'training step, reduce-overhead: {1000 * t:.2f} ms/call, '
      f'GPU busy {busy:.2f} ms')
training step, reduce-overhead: 0.71 ms/call, GPU busy 0.25 ms

13.3.5 Limits of Compilation#

Compilation pays off only when a program runs for more than n∗n^* steps and spends significant time in bandwidth-bound chains or host-launch overhead. Keep three practical caveats in mind:

  • Branches on tensor values: Logging a scalar loss, testing if loss < 0.1:, or data-dependent indexing (x[x > 0]) forces graph breaks or errors. Keep host reads outside compiled functions and express in-graph branches with where / select or cond.
  • Changing shapes: Variable sequence lengths or a short final minibatch in an epoch can trigger repeated recompilations. Drop or pad the final minibatch, and bucket variable-length sequences.
  • Debugging: Compiled kernels do not execute line-by-line in Python. Verify and debug in eager mode first, then compile.

13.3.6 Summary#

Eager execution runs one operation at a time, paying host dispatch latency hh per kernel and a DRAM round trip per elementwise operation. Tracing captures a computation graph on symbolic placeholders ahead of execution; data-dependent branches must be rewritten with select/conditional primitives or incur graph breaks, and shape changes trigger recompilation unless dimensions are symbolic. Operation fusion merges elementwise chains and on-chip row reductions into single kernels—cutting gelu_ish memory traffic and run time ninefold—while CUDA graph replay eliminates per-kernel host launch overhead for small models and batches.

13.3.7 Exercises#

  1. [code] Value-dependent branches. The function f of Section 13.3.1 breaks the graph at its if.

    1. Compile f with fullgraph=True and read the error. Rewrite the branch with torch.cond, verify with torch._dynamo.explain that it captures one graph, and compare torch.cond with torch.where.
    2. Time the compiled original and the compiled torch.where version with d2l.Benchmark on an 8-element input and on a 4000×40004000 \times 4000 input, and explain the difference at each size.
    3. Describe a pair of branches where torch.where (which evaluates both branches) costs more than a graph break.
  2. [code] Shape changes. torch.compile guards on input shapes and recompiles when a guard fails (Section 13.3.1).

    1. Compile torch.tanh(x) * 2 + 1 with recording_backend and call it on vectors of lengths 8,16,32,…,81928, 16, 32, \ldots, 8192. Count the compilations and inspect the reasons with torch._logging.set_logs(recompiles=True).
    2. Repeat with dynamic=False and with torch._dynamo.mark_dynamic(x, 0) before the first call. How many compilations occur in each case, and when is mark_dynamic preferable?
  1. [code] Fusion behind a matrix product. ● Compilation leaves a large matrix product unchanged but fuses the elementwise chain following it. Consider gelu_ish(a @ a) for an n×nn \times n bf16 matrix a on a GPU with peak PP, bandwidth β\beta, and ridge point I∗=P/βI^* = P/\beta. Model the product as compute-bound (2n3/P2n^3/P seconds) and the chain as bandwidth-bound (m=18m = 18 arrays of n2n^2 elements of b=2b = 2 bytes in eager mode versus 2 arrays when fused).

    1. Derive the speedup bound S(n)S(n) of compiled over eager execution in terms of n,m,b,I∗n, m, b, I^*, evaluate it on the RTX 4090 (I∗≈164I^* \approx 164) at n=1024,4096,16384n = 1024, 4096, 16384, and find the nn at which S(n)=1.1S(n) = 1.1.
    2. Measure the eager and compiled times of gelu_ish(a @ a) for n=256,512,…,8192n = 256, 512, \ldots, 8192, plot the measured speedup against S(n)S(n), and explain where they differ.
  2. Fusing a reduction. ● A numerically stable row-wise softmax over an R×dR \times d fp32 matrix can be written as five eager operations: row max, subtraction, exponential, row sum, and division.

    1. Count the DRAM reads and writes (keeping terms proportional to RdRd) for five eager kernels versus a single fused kernel that holds each row in SRAM, and state the bandwidth-bound speedup factor.
    2. When a row exceeds SRAM capacity, find the minimum number of passes for a fused kernel that computes the max and sum in separate passes versus an online single-pass reduction maintaining mj=max⁡(mj−1,xj)m_j = \max(m_{j-1}, x_j) and sj=sj−1emj−1−mj+exj−mjs_j = s_{j-1} e^{m_{j-1} - m_j} + e^{x_j - m_j}. Verify that sd=∑j=1dexj−mds_d = \sum_{j=1}^d e^{x_j - m_d}.
  1. [code] Compiling the optimizer. ● Rewrite the step of Section 13.3.3 using torch.optim.Adam (zero_grad, backward, step).
    1. Inspect the step with torch._dynamo.explain: how many graphs does it capture, and where does it break?
    2. Count the minimum parameter-sized arrays read and written by one SGD update versus one Adam update (Section 9.5), time eager and compiled steps for both optimizers, and explain why compiling the update gains more for one than the other.
  1. [code] Overhead crossover. ● Using the 60-layer stack of Section 13.3.4, investigate where kernel replay ceases to matter:
    1. Time eager and replayed execution for depths L∈[10,200]L \in [10, 200] at width 256, fit t(L)=c+sLt(L) = c + sL, and compare the slopes.
    2. Predict from max⁡(FLOPs/P,bytes/β)=h\max(\textrm{FLOPs}/P, \textrm{bytes}/\beta) = h the width at which one layer's matrix product takes as long to execute as to launch. Then measure eager and replayed times at depth 60 for widths from 64 to 4,096 and compare the crossover width with your prediction.
    3. Profile the eager stack with d2l.kernel_times and d2l.show_profile, and compare its busy device share and per-launch wall time against the compiled profile.

Discussions