← Inference From First Principles

Compilation and Execution Graphs

Capturing a decode step as a graph: what Dynamo's guards promise, what a CUDA graph removes, what an Inductor-compiled kernel fuses, what each costs to build, and why the first claim in this chapter's earlier draft was wrong.

In one recorded RTX 2060 experiment, a fixed-shape GPT-2 decode step took 16.5 ms under eager PyTorch execution and 3.37 ms when its GPU operations were captured and replayed as a CUDA graph: a 4.9× reduction in host-observed step time. The tested continuations agreed with the Chapter 10 reference for 129 generated tokens. The difference, about 13.1 ms per step, demonstrates a large dispatch-and-execution benefit for this workload. It is not, by itself, a measurement showing that exactly four fifths of eager time was CPU computation or GPU idleness; that decomposition would need a CPU/GPU timeline.

An earlier draft declared that TorchInductor could not run because it could not find a C++ compiler. The error message was real but the diagnosis was wrong: Visual Studio 2022 and MSVC were installed, while the shell lacked the environment loaded by vcvars64.bat. Once that environment was imported, the Chapter 18 example compiled and ran an Inductor-generated CPU path. The GPU Inductor path did not run, for a separate reason: this PyTorch 2.6.0 CUDA environment lacked a usable Triton installation. An indexed CPU decode step also hit a linker failure, so the measured compiled CPU workload was a specifically adapted compute core, not the unmodified complete step. This chapter separates Dynamo graph capture, Inductor code generation, and CUDA graph replay; names the path actually tested in each experiment; and includes their costs and limitations.

Where this sits

Chapter 7 characterised the time of small GPU operations in the local PyTorch stack; Chapter 9 related autoregressive decoding to repeated launch and memory costs; and Chapter 11 combined launch, effective bandwidth and arithmetic ceilings into an empirical performance model, not a universal theorem about every kernel. Chapter 10 supplied a preallocated static KV cache. Chapter 17 found a draft-model step-time ratio consistent with launch overhead, without independently isolating that cause. These observations motivate testing whether replaying a stable sequence of GPU work avoids repeated host-side dispatch.

The question here is narrower than whether compilation is generally faster: what part of a particular decode step can be recorded, compiled, or replayed without changing its semantics, and how many repetitions repay the setup cost? That question connects kernel execution to later serving concerns—variable batch sizes, changing cache positions, end-of-sequence decisions, and requests arriving between steps. A correct engine must know both when a graph can be reused and what it must do when the contract fails.

The Lab increment is examples/ch18/graph_lab.py: a DecodeState whose token, position, output and fixed-size cache buffers reside on the selected device; a decode_step that can be replayed from stable GPU addresses; GraphedStep for CUDA capture and replay; a counting backend for Dynamo graphs and recompilations; a CPU-compatible decode_core; and benchmark and environment probes. Dynamo guards and CUDA graph replay are different contracts. The experiments do not integrate graph buckets, admission, cancellation or variable-length speculative verification into Chapters 15–17; those remain engineering tasks.

For the Pi series, this adds a new kind of reproducibility record. Model weights and tokenisation are not enough to describe a compiled execution path: the operator graph, PyTorch and CUDA versions, GPU architecture, selected backend, generated code, input shapes and layouts, memory assumptions, compilation options and cache version all matter. An execution graph is an implementation artefact derived from a model and workload, not a substitute for the model manifest. A byte-identical model can execute differently after a compiler or kernel change, especially near numerical ties.

Three things called compilation

Execution graph: ops and their dependencies

Three mechanisms are commonly grouped under “compilation”, although only one of them actually compiles new kernels in this chapter. Their separation matters: Dynamo’s graphs are a representation, Inductor generates executable implementations, and CUDA graphs replay a recorded sequence of already chosen GPU operations.

Mechanism What is reused Local requirement What can invalidate or prevent it
TorchDynamo An FX graph for a traced region, with runtime guards selecting a valid specialisation A supported PyTorch build; a counting backend need not compile native code Unsupported Python effects, graph breaks, or guard failures that cause retracing/recompilation
TorchInductor Generated CPU code or GPU/Triton kernels for captured tensor computation A working compiler/toolchain for the selected backend Unsupported lowering, linkage failure, backend or package mismatch; different guards/shapes may require variants
CUDA graph replay A captured GPU work sequence with fixed kernel parameters and pointer addresses CUDA capture-safe operations, long-lived device buffers, compatible GPU/runtime Different required operations, storage addresses, incompatible layouts/shapes or host-dependent decisions not represented in the captured work

These distinctions follow the PyTorch 2.6 documentation and the PyTorch 2 systems paper. Dynamo traces bytecode to graph regions; guards express assumptions about values, types, shapes and program state, and a guard miss can trigger recompilation until a configured limit is reached. A graph break returns part of execution to Python and may prevent cross-break optimisation, but does not inherently mean two kernels or an error. Inductor lowers a captured graph into generated CPU or GPU code where its backend supports the operators. CUDA graph capture is independent of Inductor: the GPU work issued in a capture region is recorded for replay with the same virtual addresses and operation structure. GPU work is recorded, not executed normally, while capture is active. A new token can still be supplied by copying its value into the existing captured input buffer. The local experiments demonstrate particular cases of these general rules, not the full space of legal compiler or CUDA-graph updates.

Capture, and what it promises

Compilation: eager vs compiled step

A Dynamo guard is a runtime condition under which an extracted graph remains applicable. A custom backend, CountingBackend, receives each traced graph, counts its FX call nodes, and returns its eager GraphModule forward method without compiling device kernels. The Lab uses that backend to observe recompilation and symbolic-shape behaviour separately from Inductor’s code-generation costs. The FX node count is not a count of CUDA kernel launches; one graph operator may lower to several kernels or be fused with others.

The first probe uses torch._dynamo.explain on four short Python functions. These are graph-capture examples, not timings of production decoding or proof that every comparable operation will break on later PyTorch releases:

Function Graphs Breaks Reason Dynamo reports
A matmul, relu, sum 1 0
if x.sum() > 0: 2 1 generic_jump TensorVariable()
x / x.abs().max().item() 2 1 Tensor.item
a print inside the function 2 1 builtin: print

The three examples break for different reasons. The tensor-valued if needs a Python branch decision; .item() requests a host scalar from a tensor; and print performs an observable Python effect. Dynamo ended the captured region at each example on this version and resumed tracing where possible. A break can increase Python overhead and prevent fusion across the boundary, but its performance impact depends on what surrounds it. The two reported graphs do not necessarily represent two launched GPU kernels, and the number of breaks alone is not a speed benchmark.

Next, the same small function was called with twelve batch sizes, 1, 2, …, 12, to ask how many graph specialisations Dynamo’s counting backend received. No native Inductor compilation or serving throughput was timed in this experiment:

Setting Compilations for 12 batch sizes
Default 2 (the second with symbolic shapes)
dynamic=False 8, then the limit
dynamic=True 2

In this PyTorch 2.6 run the default policy produced two graphs, with the later graph including a symbolic dimension. dynamic=False produced eight graphs and then reached the observed torch._dynamo.config.cache_size_limit=8; dynamic=True still produced two. This is a result of the tested function, shape sequence and installed configuration. It does not establish that a serving engine encountering its ninth batch size universally falls off a performance cliff: limits, configuration, accumulated cache state and fallback behaviour need to be inspected in that engine. The reason for the second dynamic=True specialisation was not traced; one should inspect guard logs before attributing it to a particular symbolic-shape constraint.

Finally, Dynamo traced two versions of a decode step over 20 invocations. The Chapter 10 growing-cache version produced eight compiled graph variants before reaching the configured cache limit; the new fixed-shape step, whose current position is a device tensor rather than a Python shape or integer controlling the operation graph, produced one graph with no reported break. The custom backend counted 716 FX call nodes; torch._dynamo.explain counted 506 operations using its own counting convention. These are different instrumentation metrics, not conflicting counts of GPU launches. Fixed shapes and stable Python-level structure reduced specialisation in this particular trace, but CUDA replay additionally requires stable storage addresses and capture-safe operations.

Making the step graphable

A CUDA graph records a particular sequence of GPU operations, not an arbitrary Python decoding loop. For the test’s replayed region, the operations and tensor metadata need to remain compatible on every invocation. The Chapter 10 path with concatenated cache state, variable-length attention and a Python position changes its execution inputs and allocation pattern as decoding proceeds. The alternative in graph_lab.py keeps a fixed-size attention buffer and moves the values that change between positions into device-resident tensors:

  • Input token: a stable [B, 1] device tensor, updated in place with the selected arg-max rather than rebound to a new allocation.
  • Position: a device-side one-element integer tensor, incremented after each recorded step; the value changes but its address and shape do not.
  • Generated output: a preallocated [B, max_len] tensor; one position is written on each step.
  • KV state: Chapter 10’s preallocated StaticCache, updated using index_copy_ at the current position.
  • Attention visibility: the kernel reads buffers sized for max_len and masks future positions instead of constructing a shorter cache slice.

These choices make this specific greedy step capturable. They do not yet handle per-sequence stopping, ragged contexts, shared paged blocks or varying attention masks, and a fixed tensor address alone does not guarantee semantic correctness.

The essential indexed writes and mask are illustrated below; the full implementation in examples/ch18/graph_lab.py also performs embedding lookup, transformer-layer computation, the output projection and the in-place next-token and position updates:

state.k[layer].index_copy_(2, state.pos, k)          # write at the device-side position
state.v[layer].index_copy_(2, state.pos, v)
scores = (q @ state.k[layer].transpose(-2, -1)) / math.sqrt(dh)   # [B, h, 1, max_len]
scores = scores.masked_fill(state.positions > state.pos, float("-inf"))
...
nxt = logits.argmax(-1)
state.out.index_copy_(1, state.pos, nxt)             # record the token
state.tok.copy_(nxt)                                  # feed it to the next step
state.pos.add_(1)                                     # advance, on the device

The trade-off is deliberate: each attention step computes against a fixed max_len capacity even when the live prefix is short. The mask prevents masked future entries from influencing the result, but does not avoid reading or multiplying across those buffer positions. In the recorded batch-one experiment with max_len=256, the fixed-shape eager step took 16.5 ms against 18.1 ms for the concatenating eager baseline; that does not isolate the cost of padding, because the implementations differ in more than attention length. CPU tests check token equality against Chapter 10 on a tiny model, non-interference from deliberately contaminated future cache slots, and batch-row independence. The GPU experiment compares 129 tokens; neither test set covers long contexts, all GPU backends or every stop condition.

GraphedStep warms the decoder on a side stream, captures the device work once, then replays it. The excerpt omits the crucial state-snapshot and restoration operations; consult the actual class before using this pattern in a server:

stream.wait_stream(torch.cuda.current_stream())        # warm up on a side stream
with torch.cuda.stream(stream):
    for _ in range(3): decode_step(state, weights, config)
torch.cuda.current_stream().wait_stream(stream)
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
    logits = decode_step(state, weights, config)       # recorded, not executed for real
# replay: graph.replay() runs the same kernels on the same buffers

There are two different phases to account for. The three side-stream warm-up calls execute, so they increment the position and modify the KV and output buffers. Inside torch.cuda.graph, subsequent GPU work is captured into the graph rather than executed as an ordinary eager pass; it must not be assumed that capture itself computed a fourth token. The implementation saves the token, position, output and all KV buffers before setup and restores them after capture. Its CUDA test checks that construction leaves the position unchanged and that replayed output agrees with eager output on a tiny model. The important invariant is: the first replay must start with exactly the state intended for the next logical token; copying only the position while leaving warmed-up KV data behind would not be sufficient.

What a CUDA graph removes

The CUDA experiment used the hand-written GPT-2 float32 forward on an RTX 2060 12 GB, a 16-token prompt, fixed max_len=256, and batch sizes 1, 4, 16 and 64. Each timing cell summarises five interleaved rounds of a loop of approximately 128 generated tokens; the measured decode operation is repeated 127 times after the initial prefill-derived token. GPU completion was synchronised at the boundaries of each timed loop, so the milliseconds per step are host-observed elapsed loop time divided by replayed steps, not separate CUDA-event kernel-time or CPU-profiling measurements. The recorded token-equivalence check counted 129 tokens in its own test. The table below preserves the reported step-time medians:

Batch Chapter 10 concat, eager Fixed-shape, eager CUDA graph Graph over fixed-shape eager
1 18.1 ms 16.5 ms 3.37 ms 4.9×
4 19.6 17.1 4.46 3.8×
16 19.5 17.4 5.32 3.3×
64 20.6 17.4 11.22 1.5×

At batch one the fixed-shape eager median was 16.46 ms, versus 3.37 ms for CUDA graph replay: 4.88× faster for this same operation sequence. At batch 64, the graph median rose to 11.22 ms, while fixed-shape eager remained about 17.36 ms, leaving a 1.55× advantage. The observed trend is consistent with per-operation host dispatch being important at small batches and device computation becoming relatively more important at larger ones. It does not quantify how many milliseconds the CPU spent preparing launches or exactly how busy the GPU was; those require separate timeline instrumentation. For scale, 124,439,808 fp32 parameters occupy 497,759,232 nominal bytes (about 474.7 MiB); divided by Chapter 11’s measured 304 GB/s bandwidth reference, this gives a 1.64 ms idealised weight-read floor, not an observed per-step DRAM-traffic measurement. The 3.37 ms graph measurement remains above that simplified floor because a real step includes more than a single ideal pass over weights.

To test whether requesting the token on the host destroys the benefit, the Lab also executed a version that called state.tok.tolist() after each eager step or graph replay. Its medians were 17.4, 18.3, 18.6 and 20.0 ms for eager and 3.33, 4.61, 5.55 and 11.36 ms for the graph at batches 1, 4, 16 and 64. The graph advantage survived in this setup. These timings do not include a realistic per-sequence stopping policy, token streaming over a network or a scheduler; reading a token at each iteration is a proxy for one host-visible dependency, not proof that token transfer is free in general. Synchronisation and data transfer should be measured independently before extending this result to a deployed service.

GPT-2’s 12 small transformer layers produce many relatively small GPU operations in this hand-written implementation. A model with larger matrix multiplications could spend a higher share of its eager time doing device work, but layer count, kernel fusion, quantisation, batch size and attention backend all affect that balance. Chapter 17’s 3B/1B Llama pair is not benchmarked with CUDA graphs here, so predictions about which model would benefit proportionally more remain hypotheses. The supported conclusion is local: for GPT-2, this graphable decoding path and these batch sizes, eliminating repeated per-operation dispatch materially reduced total step time.

What a graph costs

  • Capture/setup time: constructing the batch-one graph, including warm-up and capture, took 0.178 s in the recorded run. With a per-step saving of approximately 16.46 − 3.37 = 13.09 ms, the simple break-even estimate is 14 replayed steps. This arithmetic excludes graph maintenance, model/prompt prefill, first-run library initialisation and any additional setup outside the measured interval. It assumes the same graph will remain usable across those steps.
  • Allocator footprint: at batch eight, PyTorch recorded about 144.02 MiB of additional allocated tensor memory for the state/cache and about 9.66 MiB more after capture. These are local PyTorch allocation deltas, not a measurement of total VRAM residency, CUDA graph pool fragmentation or all per-shape graph instances.
  • Specialisation: this captured graph is tied to one batch size and configured buffer length. A real scheduler would need a set of graph buckets, padding with potentially wasted computation, recapture, or a separately validated update mechanism. The chapter does not measure that scheduling or memory trade-off.

What breaks it silently

Two failure modes were exercised. Neither is a substitute for systematic capture-lifetime, aliasing, bounds and concurrent-stream tests. The goal is to show why a graph’s lack of Python-side work on replay must be treated as a contract rather than a universal runtime safety check.

Rebinding a Python tensor does not rebind a captured graph pointer. In the experiment, the model state originally contained a tensor used during capture. After capture, the Python attribute state.tok was assigned a new tensor. Replay still read the original captured storage, and the following five generated tokens matched an untouched control run. This is a concrete stale-input hazard, not an unexplained change in the model. To change the input, copy new token values into the existing captured tensor using a properly ordered device operation; preserve the storage and its lifetime, and separately test any necessary buffer aliasing.

The application must enforce replay bounds. A separate child process replayed the captured step beyond a 24-slot cache and emitted a CUDA device-side bounds assertion rather than completing normally. The child exited abnormally, so the test process was protected from a corrupted CUDA context. The result establishes that the prototype has no protective host-side per-replay position check; it does not establish that eager CUDA indexing errors are always recoverable as ordinary Python exceptions. In a serving loop, validate remaining capacity and stopping conditions before launching a graph that may write past its allocated state, and keep the failure test isolated in a subprocess.

What Inductor fuses

Graph optimisations: fusion and elimination

TorchInductor converts Dynamo-captured computation into backend-specific generated code. PyTorch 2’s systems paper describes its use of C++ on CPUs and Triton-based GPU kernels. The machine recorded here ran PyTorch 2.6.0+cu124 on Windows, with MSVC 14.44 present once vcvars64.bat loaded the developer environment. Its CPU Inductor smoke test succeeded, and the toy MLP compiled in the recorded local trials. Its CUDA Inductor smoke test failed with Cannot find a working triton installation, because triton was not importable. This is a specific toolchain dependency failure, not evidence that CUDA graph replay needs Triton, that GPU code generation is impossible in principle, or that Inductor is categorically unsupported on all Windows configurations. No Inductor-generated GPU-kernel timing is reported.

What it could not compile

The unmodified CPU indexed decode step failed during generated-kernel linkage with unresolved external symbol aoti_torch_check. To localise the failing class of operation, the Lab separately asked Inductor to compile small indexing, masking, reduction, matrix-multiplication and selection functions, using the same PyTorch installation and MSVC environment. That test established where the tested examples succeeded or failed; it did not isolate every required symbol or prove that a particular source-code operation is unsupported in all compiler configurations:

Function Compiles with Inductor on CPU, torch 2.6, Windows
w[idx], an embedding-style gather no
buffer.index_copy_(2, pos, new) no
masked_fill then softmax yes
argmax yes
layer_norm, matmul, tanh yes
torch.where(mask, a, b) yes

In the recorded samples, an embedding-style indexed read (w[idx]) and an indexed in-place write (index_copy_) failed to link, while the listed softmax, arg-max, layer-normalisation/matmul, and torch.where examples succeeded. The linker error named aoti_torch_check, consistent with generated bounds checking requiring a missing linked symbol. The Lab did not inspect a compiler/linker trace sufficient to identify the ultimate packaging or configuration defect. State the observed PyTorch 2.6 + MSVC + Windows failure rather than treating this as a design limit of Inductor, indexing or compilation generally.

The experiment therefore changed the implementation being compiled. decode_step_split keeps embedding lookup, write-mask construction, next-token selection, token output and position updates eager. It sends the twelve-layer compute portion to torch.compile(decode_core), replacing indexed KV-cache writes with torch.where over the entire fixed-size cache, followed by copies. Both the eager and compiled performance arms use this same split design, so their relative timing compares Inductor’s effect on an equal algorithmic workload; it does not compare compiled execution of Chapter 10’s original indexed step. A tiny-model CPU test checks split versus indexed logits below 1e-5 over 15 steps, and Dynamo’s counting backend sees one graph for the core. The GPU Inductor variant was not run.

What it bought

For the CPU experiment, the Lab fixed PyTorch to one CPU thread, measured ten consecutive split-step calls per trial, and interleaved six rounds of eager and compiled execution. The two processes below differ in Inductor disk-cache state; neither timing includes the initial compilation cost, which is accounted for separately. The table reports the recorded medians of those repeated calls:

Eager Inductor Speed-up
First process (empty compile cache) 42.5 ms 35.6 ms 1.19×
Second process (warm disk cache) 46.2 ms 38.4 ms 1.20×

The cold-process comparison was 42.53 ms eager versus 35.61 ms compiled (1.19×); the disk-warm-process comparison was 46.23 ms versus 38.42 ms (1.20×). The individual elapsed times differed between processes, so the defensible finding is the within-process ratio for the same split-step workload, not an absolute cold-versus-warm execution improvement. Over 40 further steps the compiled and eager split paths selected the same tokens; the recorded maximum absolute logit difference was 0.0006714 (rounded to 0.001 in the original text). The equivalence check covers that finite sequence, not all shapes, stopping conditions or generated kernels.

Inductor improved this CPU split-step implementation by approximately 19–20% relative to its eager control. Fusion and reduced Python/runtime overhead are plausible contributors, but the experiment does not include generated-kernel inspection, counters or a breakdown of fused operations, so their separate contributions are unmeasured. Similarly, roughly 0.5 GB of model weights is a nominal parameter-storage amount, not the number of bytes proven to traverse DRAM per step: caches, residency, repeated reads and CPU memory hierarchy complicate the comparison. Without a measured single-thread bandwidth for the CPU, this chapter cannot establish that either path was bandwidth-bound. The direct evidence is the matched-workload timing and the token/logit comparison.

What it costs to start

The first compiled-core call took 25.699 s with an initially empty Inductor disk cache and 8.395 s in a second process using the populated disk cache. Each duration includes compilation/loading and that first invocation, rather than representing a separately isolated compiler-only timer. Using the simple formula

\[ N_{\mathrm{break\ even}}=\left\lceil\frac{T_{\mathrm{setup}}}{t_{\mathrm{eager}}-t_{\mathrm{compiled}}}\right\rceil \]
and the within-process median savings (**6.918 ms** cold, **7.801 ms** disk-warm), the recorded accounting reports **3,715** and **1,077** steady calls. This is an approximate **amortisation estimate**, not a measured service break-even point: first-call time includes one execution, startup paths differ between processes, and a deployment may reuse compiled artefacts across many sequences or invalidate them before repayment.

The warm-cache measurement was made on the same Windows machine, PyTorch installation, compiler and tested shapes. It does not show how portable or stable the generated code is across releases, CPU instruction sets, drivers, configuration flags or model changes. A production cache record should include the source model and weights, input signatures, graph guards, compiler and backend versions, target architecture, compiler flags and a validation result. Cache reuse is not just a performance optimisation: loading the wrong compiled variant can violate numerical or memory assumptions even when an uncompiled model would be valid.

What the numbers do not show

  • One small, hand-written GPT-2 model. Small GPU operations are a favourable case for dispatch-overhead reduction; larger models, other operators, precisions and attention kernels may shift the balance.
  • GPU loop, not full request latency. Batches 1–64 were tested at fixed max_len=256, with greedy decoding and no admission, EOS policy, network streaming or variable-length scheduler.
  • No GPU kernel timeline. The 16.5-to-3.37 ms reduction suggests large launch/dispatch overhead but does not partition CPU preparation, GPU idle gaps, device execution and memory transfer.
  • No GPU Inductor comparison. Triton was unavailable in the recorded PyTorch 2.6 CUDA environment; neither reduce-overhead nor max-autotune was measured.
  • CPU Inductor compiled a modified split step. Both timed arms use full-buffer torch.where cache writes; the original indexed version failed linkage in this installation.
  • First-call and memory accounting are limited. One empty-cache and one disk-warm Inductor process were studied. CUDA-graph extra memory is a PyTorch allocator delta, not total VRAM use.
  • No general dynamic-shape guarantee. Observed Dynamo specialisations and the cache limit belong to the tested code and configuration; CUDA graph bucket selection, updates and recapture were not implemented.
  • Safety and numerical coverage remain narrow. Token equality was tested on bounded sequences; one stale-input hazard and one out-of-range child-process failure do not establish production safety.
  • No integration with paged scheduling, prefix caching or speculation. Those mechanisms can change addresses, shapes, cache lifetimes and output counts, invalidating naïve replay assumptions.
  • Version specificity. The observations refer to PyTorch 2.6.0, MSVC 14.44 and this GPU/OS combination, not modern compiler behaviour in general.

Inference Lab increment

The Chapter 18 Lab exposes the following pieces as separate testable mechanisms, so readers can distinguish trace capture, replay correctness and generated-kernel compilation:

  • DecodeState, prefill and decode_step: device-held token, position, output and fixed-size KV state for a graphable greedy continuation.
  • decode_core and decode_step_split: the CPU-compiler-compatible alternative with indexed operations left eager and whole-buffer where cache writes in both arms.
  • GraphedStep: side-stream eager warm-up, CUDA capture, complete state restoration and replay into stable buffers.
  • CountingBackend with capture and capture_step: FX graph node counts, observed breaks and shape-dependent recompilations without Inductor compilation.
  • load_msvc_environment: discovers vcvars64.bat and imports the MSVC environment; env reports the actual compiler and Triton status.
  • inductor_ops and inductor: operation-level linkage probes and CPU split-step compilation, including first-call and steady-state timings.
  • break_even_calls and amortised_seconds: simple setup-cost accounting utilities.
  • graphs: local eager/graph GPU timing, PyTorch-allocator memory deltas, token comparisons, stale-input rebinding and an isolated out-of-range child process.

These are Lab routines, not a finished graph-serving engine. In particular, GraphedStep does not implement a general guard system, prompt lifecycle or replay-safe stop-condition policy.

The chapter’s rule is: a reusable execution path needs an explicit, tested validity contract, not just a successful capture or compile. Dynamo checks graph guards and may specialise again; CUDA graph replay instead reuses the recorded operations and pointers, so the application must maintain stable storage, valid bounds, input updates and ordering. A graph can be fast while silently ignoring a rebound tensor. A compiler can work for a toy operator while failing to link a realistic indexed step. Performance claims therefore name the precise path, the setup included in the clock, the evidence for equivalence, and the condition under which that path can be reused.

What you should now be able to do

  • Separate Dynamo graph extraction, Inductor kernel code generation and CUDA graph capture/replay; identify the toolchain and runtime required for each.
  • Use a counting backend and guard/recompile logs to examine shape changes without interpreting FX nodes as device launches.
  • Explain why moving a decode position and the current token into stable device buffers makes the tested step capturable, and why scanning the full cache can cost additional work.
  • Run a tiny-model token-equivalence check for eager, fixed-shape and graph-replayed steps, including careful initial-state restoration.
  • State the captured-pointer, compatible-shape, static-operation and bounds assumptions that the serving loop must enforce before replay.
  • Compute a qualified setup-cost break-even from observed step savings, and list the costs omitted by that estimate.
  • Interpret CPU Inductor results as a modified split-step comparison and recognise the difference between a missing compiler environment, a linker failure and a missing GPU backend.
  • Specify what additional profiler evidence would be required to turn a speed-up ratio into a CPU-versus-GPU time attribution.

Key terms

  • Dynamo graph: an FX representation of an extracted region of PyTorch computation, selected for inputs satisfying its guards.
  • Guard: a runtime assumption under which a particular compiled graph remains valid; CUDA graph replay itself does not run Dynamo’s guards.
  • Graph break: a boundary at which Dynamo stops tracing and Python executes before capture may resume.
  • Recompilation/specialisation: producing another graph or generated executable because prior assumptions no longer match.
  • Symbolic shape: a dimension represented by a symbolic value with associated constraints instead of one fixed integer.
  • TorchInductor: PyTorch’s code-generating backend for captured computation, using C++ and other backends according to device.
  • CUDA graph: recorded GPU operations and parameters replayed through a small number of host API calls, typically one graph launch.
  • Stable input storage: device buffers whose addresses remain fixed while their contents may be updated between replays.
  • Capture warm-up: eager executions before capture to prepare kernels, runtime state and allocations; these executions can mutate model state.
  • Graph bucket: a graph selected for a supported batch-size or shape class, often trading padding work against number of variants.
  • Cold start / disk-warm start: first-call timing with generated-code caches initially absent / already populated; neither equals pure compiler duration unless isolated.
  • Break-even replay count: number of repetitions at which an assumed per-call saving offsets setup costs; sensitive to reuse and omitted costs.

Reader exercises

  1. With CountingBackend, trace 12 changing batch sizes and record TORCH_LOGS="recompiles,guards". Which guards actually caused the second dynamic=True specialisation? Distinguish observation from hypothesis.
  2. Capture sizes 1, 2, 4 and 8; separately record PyTorch allocated bytes, reserved bytes and peak VRAM where available. Then pad other batch sizes to those buckets and measure wasted work and end-to-end dispatch overhead.
  3. Hold batch fixed and vary max_len over 256, 512 and 1024. Compare the masked full-buffer step with a validated variable-length eager reference, keeping weights and attention backend equal.
  4. Use a CUDA profiler timeline to report GPU kernel time, host launch gaps and synchronisations for the same step before and after graph capture. Does that support the “four fifths is dispatch” interpretation?
  5. On an environment with a verified working Triton/Inductor CUDA backend, compile the GPU decode core and then test the indexed whole step. Record the precise PyTorch, compiler and CUDA versions rather than assuming every Windows installation behaves like this one.
  6. Vary the CPU decode-core depth (for example 2, 6, 12 layers) and measure cold compilation, disk-warm first call, steady execution and code-cache footprint, with multiple repetitions.
  7. Apply CUDA graphs to a small draft model from Chapter 17 and report the measured draft/target cost ratio, graph setup, memory and near-tie numerical behaviour.
  8. Rebind an input tensor after capture and show that the graph continues reading the old storage. Fix it by copying values into the captured buffer; verify content, address and stream ordering.
  9. Deliberately exceed the capture buffer’s bound only in a disposable child process. Implement a host-side replay gate and verify that a serving loop refuses the unsafe invocation.
  10. Combine shape buckets with Chapter 15’s variable-size batch schedule. Report graph hit rate, recaptures, padding, memory use, TTFT and inter-token gaps—not only isolated model-call time.

References

Primary research

  1. PyTorch 2: Faster Machine Learning Through Dynamic Python Bytecode Transformation and Graph Compilation — Ansel et al., ASPLOS 2024. Describes TorchDynamo’s bytecode-based graph extraction, TorchInductor’s generated backends and dynamic-shape compilation. Its multi-model benchmarks are not reproduced in this chapter.
  2. Nimble: Lightweight and Parallel GPU Task Scheduling for Deep Learning — Kwon, Yu, Jeong and Chun, NeurIPS 2020. Studies ahead-of-time scheduling and reduced runtime GPU task-submission overhead. It supports the motivation for pre-recorded execution, not a claim that this Lab implements Nimble or achieves its speed-ups.
  3. Triton: An Intermediate Language and Compiler for Tiled Neural Network Computations — Tillet, Kung and Cox, MAPL/PLDI 2019. Introduces tile-based GPU kernel programming and compilation, relevant to Inductor’s GPU backend, which was not available for measurement here.

Authoritative implementation documentation and local evidence

  • PyTorch 2.6 CUDA semantics and CUDA Graphs — capture semantics, fixed virtual addresses, static storage and graph replay; relevant to the warm-up/capture distinction.
  • PyTorch dynamic shapes — guard-driven shape specialisation and dynamic recompilation. Behaviour varies by release; the recorded experiment used 2.6.0.
  • PyTorch compiler programming model and PyTorch torch.compile troubleshooting — current conceptual reference for graph breaks and recompilation; version-specific results remain those from the recorded run.
  • examples/ch18/graph_lab.py, tests/test_ch18_graph_lab.py, research/ch18/results.json and research/ch18/sources.md — the Lab implementation, regression tests and measurements. Published research performance figures are external reports, whereas the tables in this chapter describe only these local experiments.

Evidence in this chapter

Claim Evidence classification and boundary
Dynamo graphs, guards, breaks and Inductor’s backends; CUDA capture constraints Established implementation background (Ansel et al., PyTorch and CUDA documentation); version-dependent details
Four toy Dynamo functions: one unbroken and three with one graph break Book result from torch._dynamo.explain, not a kernel launch measurement
Twelve batch sizes: two specialisations by default and with dynamic=True, eight then cache limit with dynamic=False Book result on tested function and PyTorch 2.6, not a general ninth-shape latency prediction
Chapter 10 growing step: eight Dynamo graphs in 20 calls; fixed-shape step: one Book result from counting backend; FX nodes are not CUDA kernels
Fixed-shape and graph-replayed greedy continuations matched the Chapter 10 reference over 129 compared tokens Local equivalence result on one configured GPU decode test; additional small-model CPU/CUDA tests
Fixed-shape eager 16.46 ms vs graph replay 3.37 ms at batch 1; advantage falls to 1.55× at batch 64 Book result from five interleaved loop timings; no CPU/GPU profiler timeline
“Four fifths of eager time is CPU/non-compute” Inference not established; measured time difference supports launch-overhead hypothesis but not exact attribution
Approximate idealised 1.64 ms weight-read floor Derived using nominal fp32 parameter bytes and Chapter 11 bandwidth; not measured HBM traffic
Graph setup 0.178 s, estimate of 14-step repayment, and batch-eight extra allocated memory 9.66 MiB Book setup timer, arithmetic and PyTorch allocator deltas; excludes other lifecycle and VRAM costs
Rebinding a Python input attribute leaves replay reading original captured storage Book result from controlled GPU hazard test
Replaying beyond cache bounds produced a device assert in child process Book result; does not establish eager GPU exceptions are safely recoverable
MSVC toolchain existed but needed vcvars64.bat; CUDA Inductor failed because Triton could not be imported Book result from environment probes; not an inherent compiler/platform limitation
Some indexed CPU Inductor samples failed linking aoti_torch_check while simpler operations compiled Book result for one Windows/PyTorch installation; root linker cause not isolated
Adapted CPU split step: 42.53 to 35.61 ms (1.19×), 46.23 to 38.42 ms (1.20×) Book result, one CPU thread, matched split-step workloads; attribution to fusion not directly profiled
Inductor first compiled calls: 25.7 s cold and 8.4 s disk-warm; approximate 3,715 and 1,077-call repayment First-call observation plus amortisation model, not measured whole-service crossover
Larger models, graph buckets, flexible shapes, CUDA Inductor, compile modes, production scheduling Not run or not measured