Unit 6 of 10 · about 4 hours · measure

`torch.compile` capture, fusion, graph breaks and recompilation

Framework compilation decides fusion boundaries for you until it silently gives up. Breaks and guards are where its speedups go missing.

You'll be able to

  • Trace one operation from torch.compile capture through FX graph and generated Triton code to the running kernel.
  • Diagnose graph breaks and recompilations with explain and TORCH_LOGS, and repair the common cases.
  • Predict how dynamic shapes change guards, recompilation and CUDA-graph recording.

Covers

Framework graph capture, fusion and generated-kernel boundariesGraph breaks, guards, recompilation and dynamic-shape behavior
1

Read

In this order, only the parts listed

0 of 3 done

  1. Compiler pipeline: Dynamo, AOT Autograd, InductorAI Systems Performance Engineering - Chapter 14

    Chapter 14, PyTorch Compiler Deep Dive through TorchInductor Backend Code Generation: bytecode capture, joint forward-backward graph, PrimTorch IR with about 250 primitives, and Inductor code generation with autotuning and CUDA graphs

  2. Graph breaks, recompiles and dynamic shapesAI Systems Performance Engineering - Chapter 14

    Chapter 14, Explaining and Minimizing Graph Breaks (torch._dynamo.explain, allow_in_graph, torch.where masking, torch.cond limits), Minimize Graph Recompilations (TORCH_LOGS=graph_breaks,recompiles,guards, mark_dynamic, eager_on_recompile), and Dynamic Shapes and Variable Sequence Lengths (symbolic shapes and guards)

    The book says dynamic=True disables CUDA graphs. In PyTorch 2.14.1 it does not: with mode='reduce-overhead' Inductor records one CUDA graph per distinct size and warns after 8 (torch._inductor.config.triton.cudagraph_dynamic_shape_warn_limit).

  3. Compiler debugging scriptsAI Systems Performance Engineering companion code - Chapters 9, 10, 13 and 14

    code/ch14/inspect_compiled_code.py for dumping the compiled SimpleLLMBlock kernels; code/ch14/baseline_graph_break_control_flow.py against optimized_graph_break_control_flow.py for the Python-branch break; code/ch14/recompilation_demo.py (in the repository since late August 2026) for guard-driven recompiles

2

Focus on

  • Dynamo captures straight-line tensor code and breaks on data-dependent Python control flow, falling back to eager for that region.
  • Every compiled graph carries guards on shapes, dtypes and devices. A failing guard recompiles, so changing values look like slow code.
  • dynamic=True compiles one graph for many shapes, but reduce-overhead mode still records a CUDA graph per distinct size, so graph memory and recording cost grow with the shape count. Prefer mark_dynamic on the dims that truly vary, and bucket sizes when graphs matter.
  • Inductor fuses and autotunes over the captured graph only. Code outside the graph keeps its launch overhead whatever the mode says.
Common mistakes · 3
  • Reading one slow iteration as a slow kernel. The first iterations pay capture and compile; compare warm steady state only.
  • Closing over a changing Python constant such as a seed or timestamp. Every new value fails a guard and recompiles.
  • Setting dynamic=True and expecting one CUDA graph. Each distinct size records its own graph under reduce-overhead; bucket the sizes or mark only the dim that varies.
3

Try it yourself

Closed-book, before checking anything

Run torch._dynamo.explain on a function with a Python if over y.sum() > 0 and on its torch.where rewrite, with PyTorch 2.14. The first reports Graph Count 2 with Break Count 1 (generic jump); the second reports Graph Count 1 with Break Count 0. Quote both reports from your own run.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.What does explain report for a data-dependent Python if on a tensor sum?Answer

    Two graphs with one break: the region before the branch, a generic-jump break reason, and the region after it.

  2. 2.Iterations stay slow long after warmup. Which log separates breaks from recompiles?Answer

    TORCH_LOGS=graph_breaks,recompiles,guards. Breaks cut graphs short; recompiles show which guard keeps failing.

  3. 3.With dynamic=True and mode='reduce-overhead', what happens when 20 distinct batch sizes arrive?Answer

    One compiled graph serves them all, but Inductor records a separate CUDA graph for each size and warns after 8 by default. Bucket the sizes so a few graphs cover the traffic.

  4. 4.When does eager_on_recompile beat fixing the guard?Answer

    When shapes vary irreducibly and each recompile costs more than it saves. It caps recompiles by falling back to eager.

5

Practice

  • AI Systems ch14: graph-break and recompile inspection

    Run code/ch14/inspect_compiled_code.py to dump the SimpleLLMBlock graphs and Triton code, then code/ch14/recompilation_demo.py; compare explain output for baseline_graph_break_control_flow.py against the optimized version

    Run the scripts on your own GPU with small shapes. Report graph counts, break reasons and which guard each recompile names.

You're done when

You can predict the graph count of a small function before running explain, and name the guard behind any recompile you trigger.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 10 more in the section
  • AI Systems Performance Engineering - Chapter 14Chris Fregly · required

    Read Chapter 14 on the PyTorch compiler, OpenAI Triton and XLA backends. Trace one framework operation from graph capture through generated GPU code, and identify graph breaks and specialization guards.

  • AI Systems Performance Engineering companion code - Chapters 9, 10, 13 and 14Chris Fregly · support

    Use code/ch09, code/ch10, code/ch13 and code/ch14 selectively for Triton, warp specialization, persistent kernels and compiler comparisons. Strip local compatibility shims when diagnosing upstream failures and record every guard in the measurement context.

Also in this section

  • Triton Programming Guide and TutorialsTriton Project · primary

    Complete the vector add, fused softmax, matrix multiplication, LayerNorm and fused-attention tutorials that run on your hardware. For each, add adversarial tails, independent references, cold and warm timing, resource inspection and a correct fallback.

  • UCSD CSE 291A/DSC 291 (Spring 2026) PA2 Part 1 - Triton matmul, add and ReLUUC San Diego · required

    Implement the fused kernel and its configuration search, and test with student_local_test.py on your own GPU. The remote grader needs a course token, so replace its speedup score with your own interleaved timing against the PyTorch reference.

  • TensorTonic Language Modeling from Scratch - Triton problemsTensorTonic · support

    Solve Masked Triton GELU Kernel, Tiled Triton Row Sum, Triton Row-Wise Softmax and Fused Tiled Matmul and ReLU, and rerun each with your own adversarial shapes.

  • CUTLASS 3.x Design and CuTe Layout AlgebraNVIDIA · required

    Study the collective and kernel hierarchy, then the CuTe layout algebra guide. Reconstruct one GEMM configuration down to layouts, copy atoms and MMA atoms and compare it with the equivalent Triton blocked program.

  • LeetGPU - CUDA and Triton Parity SetAlphaGPU · required

    Re-solve one primitive, one GEMM and one transformer challenge from GPU-4 through GPU-6 in Triton. Compare CUDA, Triton, compiler and library paths on identical tests and hardware; leaderboard rank does not replace local raw evidence.

  • GPU MODE - Triton, CuTe and Machine CodeGPU MODE · support

    Use Lectures 14, 15, 29, 37, 57, 86, 103, 104 and 114 selectively. Assign one lecture to each actual implementation question rather than watching the collection linearly.

  • PTX ISA and CUDA Binary UtilitiesNVIDIA · reference

    Inspect generated PTX and SASS for the matched CUDA and Triton kernels. Check instruction, memory-space and target assumptions in the versioned ISA and use binary tools to confirm which device code ships.

  • CUDA Tile IR Programming ModelNVIDIA · depth

    Read the programming model and inspect the official repository after CUDA, Triton and CuTe mappings are clear. Implement one tiny parity kernel only if the toolchain supports it and record compiler-version constraints.

  • Modern GPU Programming for MLSys - TIRxMLC · depth

    Use Parts II and III plus the compiler reference as a Blackwell-specific comparison of layouts, dispatch, TMA pipelines and persistent scheduling. Do not make TIRx a required dependency for the portable track.

  • MIT 6.S894 Lecture 10 - Domain Languages and AcceleratorsMIT · support

    Use the Higher-level kernel languages slides comparing Triton, Pallas, cuTile (Tile IR) and the CuTe DSL on mapping, effort and performance for the programming-model comparison. Do not use the TPU lab.