Unit 11 of 12 · about 3 hours · explain, measure

`torch.compile` on a training step: graph boundaries, recompiles and breaks

Compilation moves work across the eager boundary: a break silently keeps the slow path while the config claims the fast one. Knowing where the graph ends says which optimizations actually apply.

You'll be able to

  • Explain what torch.compile captures, what forces a graph break, and what invalidates a compiled graph.
  • Locate every graph break in one training step with torch._dynamo.explain and explain each in one sentence.
  • Measure compiled versus eager step time honestly, with compilation time kept out of the steady-step mean.

Covers

torch.compile graph boundaries, recompilation and graph breaks
1

Read

In this order, only the parts listed

0 of 2 done

  1. Graph breaks and recompilationsAI Systems Performance Engineering - Chapters 13 and 14

    Chapter 13, PyTorch Compiler (torch.compile) with Using the PyTorch Compiler and Compilation Modes and Trade-Offs in Speed, Memory, and Compile Time; Chapter 14, Explaining and Minimizing Graph Breaks with Graph Breaks and TorchDynamo explain(), Minimize Graph Recompilations, and Debugging Compiler Phases, Graph Breaks, and Performance

  2. CS336 Assignment 2: compile on the reference modelCS336 Assignment 2 (Spring 2026) - Sections 2 and 3

    Section 3.1.1 Operator Fusion for torch.compile fusion and Section 4 torch_compile (2pt): compile the attention benchmarking script and then the whole Transformer, compare eager and compiled timing tables, and report where fusion helps and where it does not

2

Focus on

  • Dynamo captures bytecode into graphs guarded on shapes, devices, grad mode and hook state. A CPU check of a compiled Linear reports Graph Count 1 with Break Count 0; any data-dependent branch or untraceable call splits the graph and runs the fragment eager.
  • Guards explain recompiles: a new shape, a toggled grad mode, a changed hook table or a new argument structure re-triggers compilation. Stable training loops keep shapes and modes fixed for exactly this reason.
  • Breaks preserve numerics but drop optimization scope. A step with many breaks is eager with extra overhead, so count breaks before quoting speedups.
  • Compilation time is a first-step cost like allocator prep. Warm it up, then time steady steps; folding compile minutes into the step mean punishes the compiled run for one-off work.
Common mistakes · 3
  • Quoting first-step compiled time as the compiled step time. Compilation happens once; steady steps are the comparison.
  • Assuming fewer breaks always means faster. A single graph with tiny dynamic shapes can recompile every step, which is worse than two stable graphs.
  • Calling .item() or printing a tensor inside the compiled step. Each forces a graph break and a device sync, so the step runs as fragments with a host round trip in the middle.
3

Try it yourself

Closed-book, before checking anything

Closed-book, compile a tiny Linear training step, print the explain graph and break counts, add one branch on a .item() value and show the break count rise (a branch on a tensor predicate alone may not break). Then time eager versus compiled steady steps with warmup separated from measurement.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.Explain reports Graph Count 1 and Break Count 0 for a Linear. What does that promise?Answer

    The whole call captured as one graph under its guards. It promises nothing about speed; it only says no fragment fell back to eager.

  2. 2.A loop over varying sequence lengths recompiles every step. Which guard fires?Answer

    The shape guard. Each new shape invalidates the compiled graph; padding or bucketing to fixed shapes stops the storm.

  3. 3.A compiled step matches eager loss but runs slower. Name two suspects before blaming the compiler.Answer

    Graph breaks leaving most work eager with added overhead, and timing that includes compilation or allocator warmup in the compiled mean.

5

Practice

  • CS336 Assignment 2: torch_compile

    Section 4 torch_compile on a size your hardware fits: eager versus compiled comparison with the break and guard evidence for where fusion applies

    A writeup problem; checking is your explain output plus honest steady-step tables with compilation kept separate. Needs one GPU for device-relevant breaks; CPU shows the counting method.

You're done when

You can point at every break in your own step, name the guard or construct behind it, and defend the compiled speedup with warmup excluded.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 11 more in the section
  • CS336 Assignment 2 (Spring 2026) - Sections 2 and 3Stanford University · required

    Complete benchmarking_script, nsys_profile, mixed_precision_accumulation, benchmarking_mixed_precision, memory_profiling and gradient_checkpointing on model sizes your hardware fits, with your own solutions. Keep timing tables, memory predictions and failure notes; the FlashAttention kernel (Section 4) and the leaderboard (Section 9) are outside this stage.

  • AI Systems Performance Engineering - Chapters 13 and 14Chris Fregly (O'Reilly) · support

    Read Chapter 13 on NVTX markers, the PyTorch profiler, memory and allocator tuning, activation checkpointing and the data input pipeline, and the Chapter 14 sections on graph breaks and recompilation. Use them to explain one profiled step of your own trainer; treat bundled expectations as the author's hardware results.

Also in this section

  • Machine Learning Systems Volume I - ML Frameworks, Model Training and BenchmarkingML Systems Textbook · primary

    Read Model Training (Iron Law of Training Performance, Pipeline Architecture, Identifying Bottlenecks, Pipeline Optimizations), then ML Frameworks (Execution Problem, Differentiation Problem, Anatomy of a Training Step) at https://mlsysbook.ai/vol1/frameworks/frameworks.html and Benchmarking (Training Benchmarks, Benchmarking Best Practices) at https://mlsysbook.ai/vol1/benchmarking/benchmarking.html. Turn the reading into a state-ownership table and a deterministic train-resume trace before the CS336 exercises.

  • Ultra-Scale Playbook - First Steps: Training on One GPUHugging Face · required

    Read Memory usage in transformers, Activation recomputation and Gradient accumulation, then Appendix A1 on profiling. Derive weight, gradient, optimizer and activation bytes for your tiny model before measuring; the interactive calculator does not show its sequence length or recomputation setting, so compare it with the formulas only after setting both.

  • Distributed Training Guide - Chapter 1 and Related TopicsLambda Labs · required

    Trace 01-single-gpu/train_llm.py end to end with its README (argument parsing, model initialization, checkpoint save of model, optimizer and scheduler, timers and memory statistics), then the related-topics folders on determinism, gradient accumulation, effective batch size and optimized data loading. Produce a state-ownership table and prove identical data order and optimizer trajectory after a controlled interruption.

  • Machine Learning Engineering Open Book - Training and PyTorch DebuggingStas Bekman · required

    Read training/README.md, training/dtype.md, training/reproducibility/README.md and the tiny-model, memory and profiling sections of debug/pytorch.md. Use its commands as a field checklist while diagnosing your own loop.

  • Transformer Math 101EleutherAI · support

    Use the compute, parameter, optimizer, gradient and activation memory equations as a second derivation of your memory ledger. Check each per-dtype byte count against your own trainer's state.

  • Mixed Precision TrainingMicikevicius et al. (ICLR 2018) · support

    Read the sections on FP32 master weights, loss scaling and FP32 accumulation. Connect each to a failure your trainer can show: lost small updates, underflowed gradients or overflowed products.

  • PyTorch Profiler RecipesPyTorch · support

    Use the profiler, memory snapshot and benchmark recipes only when the CS336 handout calls for them. Annotate one complete step and explain every visible gap or synchronization event.

  • TensorTonic - Training Arithmetic ProblemsTensorTonic · support

    Solve Training FLOP Estimator, Mixed-Precision Training Memory Accountant and Gradient Accumulation Equivalence (free problems in the Language Modeling from Scratch plan) before the CS336 measurements.

  • Distributed Training SubsystemRoadmap-Final · support

    Start Milestone A with the deterministic sampler, state manifest, event trace and single-process oracle. Keep extending this repository through DT-9.

  • PyTorch data loading API - DataLoader, Sampler and multi-process loadingPyTorch · reference

    Read Data Loading Order and Sampler, Single- and Multi-process Data Loading with its Randomness subsection, and the DistributedSampler entry for set_epoch, drop_last padding and worker seeding. Use it to define sampler position and worker sharding for the lineage and resume units.

  • PyTorch Autograd mechanics notePyTorch · reference

    Read How autograd encodes the history with Saved tensors, Hooks for saved tensors, and Backward Hooks execution (whether each hook fires and in which order). Use it for the autograd graph, saved-tensor and hook-ordering claims.