Unit 9 of 12 · about 3 hours · measure
Compilation, graph breaks and recompilation in a serving path
Graph capture from the previous unit replays only what compilation produced. A forward pass that recompiles per batch shape stalls at the worst moment, so breaks and guards belong in the serving path design.
You'll be able to
- Explain graph breaks, guards and recompiles, and where each appears in a serving forward pass.
- Stabilize a bounded compiled path across the workload shape distribution with dynamic shapes or bucketing, and count the remaining recompiles.
- Place an intentional break around the dynamic attention operator instead of forcing full-graph compilation across it.
Covers
Read
In this order, only the parts listed
0 of 3 done
- Graph breaks, guards and recompilesPyTorch compiler troubleshooting guide (2.14)
Graph break, Guards, Recompilation and Dynamic Shapes, with
TORCH_LOGSset tograph_breaksandrecompiles - Intentional breaks at the attention boundaryUCSD CSE 291A (Spring 2026) - Guest lecture: Engineering vLLM
May 7, 2026 scribe notes: Section 4.5, the attention-boundary split with an intentional graph break before and after attention
- Compile validation across bucketed shapesAI Systems Performance Engineering companion code - Chapter 18
run_compile_validation:torch.compilewithdynamic=True,mode="reduce-overhead"and a counting backend over padded bucket shapesRead the validation logic, not bundled timings as targets. It runs bucketed shapes only; add your own unbucketed series to compare compile counts. The companion
decode_kernels.pyin the same folder compiles withfullgraph=False;fullgraph=Trueraises at the first graph break instead.
Focus on
- A graph break splits one function into several graphs.
torch._dynamo.explainreports the graph count with a reason per break, and each graph carries its own shape guards. - Static size guards trigger a recompilation for each new size under
dynamic=False, until the recompile limit sends the function to eager execution. The default (dynamic=None) recompiles with automatic dynamic shapes after a size mismatch;dynamic=Truerequests symbolic shapes upfront (sizes 0 and 1 still specialize). Neither guarantees one compilation: strides, dtypes, control flow and other guards can still specialize. Bucketing limits shape variation, not every source of recompilation. - Inductor may reassociate reductions, so compiled output can differ from eager by a few ULPs. Compare with a tolerance, never with exact equality.
- Attention is the dynamic operator in a serving layer. vLLM splits the graph at attention by default (
splitting_ops) so the static pieces stay capturable, the lecture's intentional break; the experimentaluse_inductor_graph_partitionmoves that split into Inductor at ops taggedcudagraph_unsafe.
Common mistakes · 3
- Setting
fullgraph=Trueto remove breaks. It raises on the first untraceable op; remove the op or scope compilation around it instead. - Asserting compiled output equals eager output exactly. Reduction reassociation changes rounding within tolerance.
- Compiling once and assuming coverage. A failed guard may trigger recompilation or eager execution after the compilation limit; count both across the serving shape distribution.
Try it yourself
Closed-book, before checking anything
a = torch.relu(x), then calls print("mid", a.shape), then returns (a + 1).sum(-1), with fullgraph=False, and run torch._dynamo.explain on it: predict 2 graphs and 1 break naming builtin print before you run (a constant print before any traced op does not break). Then compile a reduction with dynamic=False, call it at two batch sizes above 1 under TORCH_LOGS=recompiles, and observe the size-mismatch guard recompile. Recompiling with dynamic=True runs both shapes with no recompile log and matches eager under torch.testing.assert_close, not torch.equal.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.What does
explainreport for theprintfunction, and why two graphs?AnswerTwo graphs and one break naming builtin
print. The traced ops before and after the untraceable call compile as separate graphs.2.Why does the second batch size recompile under
dynamic=False?AnswerGuards specialized on the first size. The new size fails the size guard, so Dynamo recompiles for the new shape.
3.Where does an intentional break belong in a serving layer?Answer
Around attention. Static MLP and norm regions stay compilable and capturable while the dynamic operator stays eager.
4.Compiled output differs from eager by a few ULPs. Is the compile wrong?Answer
Not from that alone. Reassociated reductions round differently. Wrong means exceeding the declared tolerance or failing the oracle matrix.
You're done when
You predict the break count of a small function before running explain, remove a shape recompile with bucketing or dynamic shapes, and can point to the intentional-break boundary in the serving path.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 11 more in the section
- AI Systems Performance Engineering companion code - Chapter 18Chris Fregly · required
Start with paged_attn_common.py, the dense versus paged layout pair, CUDA graph bucketing and the vLLM integration pair. Run correctness tests first, then a hardware-compatible benchmark with newly captured artifacts.
- UCSD CSE 291A (Spring 2026) - Guest lecture: Engineering vLLMUC San Diego · support
Read the scribe notes, Sections 4 and 5: CPU overhead, the API server and renderer, synchronous and asynchronous engine-core scheduling, GPU-side input preparation, piecewise CUDA graphs and the hybrid kernel strategy.
- PyTorch compiler troubleshooting guide (2.14)PyTorch · reference
Read Graph break, Guards, Recompilation and Dynamic Shapes; run
TORCH_LOGSset tograph_breaksandrecompileson a small serving-shaped function.
Also in this section
- FlashInfer: Efficient and Customizable Attention Engine for LLM Inference ServingFlashInfer Project · primary
Read the storage heterogeneity, plan and run separation, load-balanced scheduling, customization, CUDA Graph compatibility and end-to-end evaluation. Use it to connect serving-shaped attention kernels to dynamic workloads and dispatch constraints.
- AI Systems Performance Engineering - Chapters 18 and 19, decode kernels and engine optimizationsChris Fregly (O'Reilly) · required
Read "Optimized Decode Kernels" in Chapter 18 (FlashMLA, ThunderMLA, FlexDecoding), then the Chapter 19 sections on kernel autotuning, occupancy-aware kernel selection, hot-swappable kernels and CUDA-graph prewarming. Choose one bounded critical path to verify.
- FlashAttention-2: Faster Attention with Better Parallelism and Work PartitioningTri Dao · required
Derive online-softmax state, memory traffic and work partitioning. Implement only a small oracle-backed version or use the CS336 assignment; production kernel tuning belongs to the GPU track.
- FlashInfer DocumentationFlashInfer Project · required
Use the current attention, PageAttention, sampling, JIT and CUDA Graph interfaces while implementing. Pin the version and supported GPU architecture, and validate dispatch and fallback over the real workload shape distribution.
- CS336 Assignment 2 - FlashAttention and Triton SectionsStanford University · required
Complete the relevant derivation, PyTorch reference and Triton sections using your own code. Follow assignment integrity: use external help for concepts, invariants, tests and profiling, not copied solutions or edited answer code.
- Mini-SGLang - Kernel, Model Runner and Overlap BoundariesSGLang Project · support
Trace how FlashAttention or FlashInfer, KV layouts, tensor parallel communication and overlap scheduling meet the model runner. Identify the fallback and state-reset boundary before attempting a change.
- vLLM CUDA Graphs design (v0.31.0)vLLM Project · support
Use the capture modes, batch-size buckets and piecewise splitting around attention to explain what a graph replay can and cannot include.
- LLM Inference: From scratch, one token at a time - Module 07Tushar Amrit · support
Work the Attention Kernels module for the decode-attention memory traffic and the paged-attention gather before the matching units.
- AI Performance Engineering - Kernel Optimization, Profiling and AttentionWafer · reference
A curated index. Use Sections 2 and 3 only to find a kernel or profiler source the other entries lack.
- TensorRT-LLM Architecture OverviewNVIDIA · support
Use the runtime-optimization section to compare graph replay, overlap scheduling and backend dispatch with your selected engine. Record current version and hardware support before treating a path as available.
- vLLM structured outputs (v0.31.0)vLLM Project · required
Read Offline Inference and the API-field migration warning; trace grammar bitmask application before sampling in the versioned model-runner API.