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 \(h\) 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.

In JAX, jax.jit traces the function using abstract tracer objects into a typed intermediate representation (jaxpr, inspectable via jax.make_jaxpr) (Frostig et al. 2018), which the XLA compiler lowers into fused GPU kernels cached by input shape and dtype.

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,)
def f(x):
    x = x * 2
    if x.sum() > 0:        # Python needs the value of this comparison
        return x + 1
    return x - 1

try:
    jax.jit(f)(jnp.ones(8))
except jax.errors.TracerBoolConversionError as e:
    print(type(e).__name__)

def f_select(x):  # Both alternatives in the graph; select keeps one
    x = x * 2
    return jax.lax.select(x.sum() > 0, x + 1, x - 1)

print(jax.make_jaxpr(f_select)(jnp.ones(8)))
TracerBoolConversionError
{ lambda ; a:f32[8]. let
    b:f32[8] = mul a 2.0:f32[]
    c:f32[] = reduce_sum[axes=(0,) out_sharding=None] b
    d:bool[] = gt c 0.0:f32[]
    e:f32[8] = add b 1.0:f32[]
    f:f32[8] = sub b 1.0:f32[]
    g:f32[8] = select_n d f e
  in (g,) }

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.

jax.jit refuses by raising TracerBoolConversionError. Replacing the Python if with jax.lax.select (or jax.lax.cond when only one branch should be evaluated) yields a single jaxpr.

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,)
@jax.jit
def g(x):
    print(f'tracing g for shape {x.shape}')  # Python runs only while tracing
    return jnp.sin(x) + 1

for n in (8, 8, 16, 32):
    g(jnp.ones(n))
tracing g for shape (8,)
tracing g for shape (16,)
tracing g for shape (32,)

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

jax.jit specializes strictly to static shapes: the Python print executes during tracing for lengths 8, 16, and 32 (three traces for four calls), while the second call at length 8 hits the cache.

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 = 18\) arrays of size \(nb\) 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

\[ \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 \approx 1.5 \ll 82\) FLOP/byte), both versions are bandwidth-bound and fusion should speed up gelu_ish by roughly \(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
x = jax.random.normal(d2l.get_key(), (4000, 4000))
compiled = jax.jit(d2l.gelu_ish)
assert jnp.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.84 ms/call, 627 GB/s
compiled: 0.17 ms/call, 768 GB/s

Both versions stream through memory at 0.6–0.9 TB/s, and the compiled version runs \(8\times\) to \(11\times\) faster—right around the \(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 = 2048\) and FFN hidden width \(4d = 8192\) in bf16, an unfused 8-op activation on \(M\) tokens moves \(18 \cdot 4dM \cdot 2 = 144\,dM\) bytes, while the two surrounding FFN matrix products perform \(2 \cdot 2 \cdot M \cdot d \cdot 4d = 16\,d^2M\) FLOPs. Their time ratio is independent of the token count \(M\):

\[ \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^* = 164\) FLOP/byte and \(d = 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 \(i\) 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 \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
def init_mlp(key, width=1024, depth=4):
    """Weights and biases drawn uniformly from +-1/sqrt(width)."""
    bound = 1 / width**0.5
    keys = jax.random.split(key, (depth, 2))
    return [(jax.random.uniform(kW, (width, width), minval=-bound,
                                maxval=bound),
             jax.random.uniform(kb, (width,), minval=-bound, maxval=bound))
            for kW, kb in keys]

def mlp(params, X):  # Linear layers with the gelu_ish chain between them
    for W, b in params[:-1]:
        X = d2l.gelu_ish(X @ W + b)
    W, b = params[-1]
    return X @ W + b

def train_step(params, X, Y, lr=0.1):  # Forward, backward, SGD update
    loss_fn = lambda p: ((mlp(p, X) - Y) ** 2).mean()
    loss, grads = jax.value_and_grad(loss_fn)(params)
    return loss, jax.tree.map(lambda p, g: p - lr * g, params, grads)

Let us predict the step time. The four forward products and seven backward products (the first layer needs no input gradient) perform ~\(11 \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 \ge 10\) µs each (> 1 ms of host launch overhead), making the eager step overhead-bound.

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

\[ 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
params = init_mlp(d2l.get_key())
X, Y = (jax.random.normal(d2l.get_key(), (512, 1024)) for _ in range(2))
compiled_step = jax.jit(train_step)
t_first = d2l.Benchmark(lambda: compiled_step(params, X, Y),
                        warmup=0, repeats=1).time  # Includes compilation
t_eager = d2l.Benchmark(lambda: train_step(params, X, Y)).time
t_compiled = d2l.Benchmark(lambda: compiled_step(params, 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'))
first call: 5.8 s
eager: 30.87 ms, compiled: 0.26 ms
break-even: about 200 steps

Default torch.compile speeds up the step by less than \(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.

jax.jit compiles the forward pass, backward pass, and update into a single XLA program launched in one call, running in ~0.25 ms—matching our paper estimate and running ~\(100\times\) faster than un-jitted JAX.

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\) activations on a batch of 64 examples (120 operations per call). Each layer performs only \(8.4 \times 10^6\) FLOPs and moves 384 KiB (< 0.5 µs on the roofline, and ~1–3 µs of actual device execution above the hardware kernel-start floor), whereas eager execution pays \(h\) per operation (\(120\,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
def init_deep(key, depth=60, width=256):  # 120 operations per call
    return list(jax.random.uniform(key, (depth, width, width),
                                   minval=-width**-0.5, maxval=width**-0.5))

def deep(params, x):
    for W in params:
        x = jnp.tanh(x @ W)
    return x

params = init_deep(d2l.get_key())
x = jax.random.normal(d2l.get_key(), (64, 256))
jitted = jax.jit(deep)
jitted(params, x)  # First call compiles
times = {}
for desc, f in (('eager', deep), ('jit', jitted)):
    t = times[desc] = d2l.Benchmark(lambda: f(params, x), repeats=100).time
    print(f'{desc}: {1000 * t:.2f} ms/call, '
          f'{1e6 * t / 120:.1f} µs per operation')
# The kernels of the jitted stack, against the time of a call
d2l.show_profile(d2l.kernel_times(lambda: jitted(params, x)),
                 1000 * times['jit'], rows=3)
eager: 7.79 ms/call, 64.9 µs per operation
jit: 0.25 ms/call, 2.1 µs per operation
wall clock 0.25 ms per step, device busy 0.24 ms (95%), matrix products 74%
  0.17 ms  73%  gemm_fusion_dot_1
  0.06 ms  25%  loop_reduce_fusion_1
  0.00 ms   1%  gemm_fusion_dot

Default torch.compile (fused) is barely faster than eager execution: because Inductor delegates the matrix products to cuBLAS, it cannot fuse the \(\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\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.

jax.jit fuses each \(\tanh\) directly into the following matrix product and replays the compiled sequence as an XLA command buffer (CUDA graph), running ~\(30\times\) faster than eager dispatch and keeping the GPU busy for nearly the entire ~0.25 ms call.

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^*\) 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 \(h\) 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 \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, \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?
  3. [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 \times n\) bf16 matrix a on a GPU with peak \(P\), bandwidth \(\beta\), and ridge point \(I^* = P/\beta\). Model the product as compute-bound (\(2n^3/P\) seconds) and the chain as bandwidth-bound (\(m = 18\) arrays of \(n^2\) elements of \(b = 2\) bytes in eager mode versus 2 arrays when fused).
    1. Derive the speedup bound \(S(n)\) of compiled over eager execution in terms of \(n, m, b, I^*\), evaluate it on the RTX 4090 (\(I^* \approx 164\)) at \(n = 1024, 4096, 16384\), and find the \(n\) at which \(S(n) = 1.1\).
    2. Measure the eager and compiled times of gelu_ish(a @ a) for \(n = 256, 512, \ldots, 8192\), plot the measured speedup against \(S(n)\), and explain where they differ.
  4. Fusing a reduction. ● A numerically stable row-wise softmax over an \(R \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 \(Rd\)) 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 \(m_j = \max(m_{j-1}, x_j)\) and \(s_j = s_{j-1} e^{m_{j-1} - m_j} + e^{x_j - m_j}\). Verify that \(s_d = \sum_{j=1}^d e^{x_j - m_d}\).
  5. [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.
  6. [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 \in [10, 200]\) at width 256, fit \(t(L) = c + sL\), and compare the slopes.
    2. Predict from \(\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.
  1. [code] Value-dependent branches. Tracing replaces argument values with symbolic placeholders (Section 13.3.1).
    1. Rewrite the branch of f with jnp.where and with jax.lax.cond, and inspect both jaxprs with jax.make_jaxpr. Which operations does each execute at run time?
    2. Apply jax.vmap to the jax.lax.cond version over a batch of vectors and inspect its jaxpr. What became of the conditional, and why?
    3. Jit a function that branches on x.shape[0] > 4 and call it on vectors of lengths 3, 5, and 6. Why does it succeed, and how many times does it trace?
  2. [code] Shape changes. A jitted function specializes to its argument shapes (Section 13.3.1).
    1. Jit a function returning jnp.tanh(x).mean() that increments a Python counter during tracing. Call it on vectors of lengths 100, 200, and 300 (three times each), and compare the first-call and cached-call times.
    2. Pad every input to length 512 and pass a mask or length so that a single trace computes the exact unpadded mean for all three lengths.
    3. Compare passing the length as a traced array versus marking it with static_argnums.
  3. [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 \times n\) bf16 matrix a on a GPU with peak \(P\), bandwidth \(\beta\), and ridge point \(I^* = P/\beta\). Model the product as compute-bound (\(2n^3/P\) seconds) and the chain as bandwidth-bound (\(m = 18\) arrays of \(n^2\) elements of \(b = 2\) bytes in eager mode versus 2 arrays when fused).
    1. Derive the speedup bound \(S(n)\) of compiled over eager execution in terms of \(n, m, b, I^*\), evaluate it on the RTX 4090 (\(I^* \approx 164\)) at \(n = 1024, 4096, 16384\), and find the \(n\) at which \(S(n) = 1.1\).
    2. Measure the eager and compiled times of gelu_ish(a @ a) for \(n = 256, 512, \ldots, 8192\), plot the measured speedup against \(S(n)\), and explain where they differ.
  4. Fusing a reduction. ● A numerically stable row-wise softmax over an \(R \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 \(Rd\)) 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 \(m_j = \max(m_{j-1}, x_j)\) and \(s_j = s_{j-1} e^{m_{j-1} - m_j} + e^{x_j - m_j}\). Verify that \(s_d = \sum_{j=1}^d e^{x_j - m_d}\).
  5. [code] Trace-time constants. The Python body of a jitted function runs only during tracing (Section 13.3.1).
    1. Jit a function that returns x + np.random.randn(), call it twice, inspect its jaxpr, and explain the two outputs.
    2. Suppose a jitted dropout function reads a PRNG key from a Python global variable. Explain what happens across steps when the global variable is reassigned, and rewrite the function so every call draws a fresh mask.
  6. [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 \in [10, 200]\) at width 256, fit \(t(L) = c + sL\), and compare the slopes.
    2. Predict from \(\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