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 and made its own round trip through GPU memory. Optimizing the program requires graph capture—obtaining the computation graph before the operations execute.
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.
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:
- Freeze the branch taken by a concrete example input—fast, and silently wrong when future inputs should take the other branch.
- 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.
- 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 (), reuses that graph on the second
call (), and upon seeing recompiles with a symbolic dimension
(SymInt s77), which then handles 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 arrays of size 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
Because even the fused kernel performs only ~12 FLOPs per 8 bytes in fp32
( FLOP/byte), both versions are bandwidth-bound and
fusion should speed up gelu_ish by roughly .
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 to faster—right around the 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 and FFN hidden width in bf16, an unfused 8-op activation on tokens moves bytes, while the two surrounding FFN matrix products perform FLOPs. Their time ratio is independent of the token count :
for FLOP/byte and . 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 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 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 lossLet us predict the step time. The four forward products and seven backward products (the first layer needs no input gradient) perform ~ 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 µs each (> 1 ms of host launch overhead), making the eager step overhead-bound.
Because compilation costs on the first call and saves per step, it breaks even after
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 , 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 activations on a batch of 64 examples (120 operations per call). Each layer performs only 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 per operation ( 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.
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
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 ~ 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 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 withwhere/selectorcond. - 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
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#
-
[code] Value-dependent branches. The function
fof Section 13.3.1 breaks the graph at itsif.- Compile
fwithfullgraph=Trueand read the error. Rewrite the branch withtorch.cond, verify withtorch._dynamo.explainthat it captures one graph, and comparetorch.condwithtorch.where. - Time the compiled original and the compiled
torch.whereversion withd2l.Benchmarkon an 8-element input and on a input, and explain the difference at each size. - Describe a pair of branches where
torch.where(which evaluates both branches) costs more than a graph break.
- Compile
-
[code] Shape changes.
torch.compileguards on input shapes and recompiles when a guard fails (Section 13.3.1).- Compile
torch.tanh(x) * 2 + 1withrecording_backendand call it on vectors of lengths . Count the compilations and inspect the reasons withtorch._logging.set_logs(recompiles=True). - Repeat with
dynamic=Falseand withtorch._dynamo.mark_dynamic(x, 0)before the first call. How many compilations occur in each case, and when ismark_dynamicpreferable?
- Compile
-
[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 bf16 matrixaon a GPU with peak , bandwidth , and ridge point . Model the product as compute-bound ( seconds) and the chain as bandwidth-bound ( arrays of elements of bytes in eager mode versus 2 arrays when fused).- Derive the speedup bound of compiled over eager execution in terms of , evaluate it on the RTX 4090 () at , and find the at which .
- Measure the eager and compiled times of
gelu_ish(a @ a)for , plot the measured speedup against , and explain where they differ.
-
Fusing a reduction. ● A numerically stable row-wise softmax over an fp32 matrix can be written as five eager operations: row max, subtraction, exponential, row sum, and division.
- Count the DRAM reads and writes (keeping terms proportional to ) for five eager kernels versus a single fused kernel that holds each row in SRAM, and state the bandwidth-bound speedup factor.
- 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 and . Verify that .
- [code] Compiling the optimizer. ● Rewrite the step of
Section 13.3.3 using
torch.optim.Adam(zero_grad,backward,step).- Inspect the step with
torch._dynamo.explain: how many graphs does it capture, and where does it break? - 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.
- Inspect the step with
- [code] Overhead crossover. ● Using the 60-layer stack of
Section 13.3.4, investigate where kernel replay ceases to
matter:
- Time eager and replayed execution for depths at width 256, fit , and compare the slopes.
- Predict from 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.
- Profile the eager stack with
d2l.kernel_timesandd2l.show_profile, and compare its busy device share and per-launch wall time against the compiled profile.