Unit 8 of 14 · about 4 hours · measure
Allocator fragmentation, activation peaks, OOMs and recompilation storms
Out-of-memory and sudden slowdowns after a code edit are usually allocator state or compiler guards, not model size. This unit reads the evidence instead of shrinking the batch blindly.
You'll be able to
- Diagnose an OOM as fragmentation, activation peak or leak using allocator and snapshot evidence.
- Fix fragmentation with staged settings and activation peaks with checkpointing or offload, preserving equivalence.
- Detect graph breaks and recompilation storms from logs and explain which change triggered them.
Covers
Read
In this order, only the parts listed
0 of 3 done
- CUDA allocator, checkpointing and offloadAI Systems Performance Engineering - Chapters 1 to 5, 13 and 14
Chapter 13, Profiling and Tuning Memory in PyTorch, with Tuning the CUDA Memory Allocator, Activation Checkpointing for Memory Savings, and Offloading Parameters to CPU and NVMe
- Graph breaks and recompilationsAI Systems Performance Engineering - Chapters 1 to 5, 13 and 14
Chapter 14, Explaining and Minimizing Graph Breaks, with Graph Breaks and TorchDynamo explain(), Minimize Graph Recompilations, and Debugging Compiler Phases, Graph Breaks, and Performance
- OOM triage and fragmentation fixesMachine Learning Engineering Open Book - Network, Debug, Training Performance and Orchestration
Debugging CUDA OOM in forward and backward, Overcoming CUDA OOM due to memory fragmentation with expandable segments, and the memory profiler plus allocation tracing sections
Focus on
- Free memory with no large-enough block is fragmentation; a spike at a known layer is an activation peak; growth across steps is a leak.
torch.cuda.memory_statsplus the snapshot timeline separates the three. - Fix in order: confirm the cause from the snapshot, then try allocator settings such as expandable segments, then activation checkpointing or offload. Each change keeps an equivalence check so memory savings do not silently change numerics.
torch._dynamo.explainplusTORCH_LOGSwith graph breaks and recompiles names the break. Dynamic shapes and data-dependent branches add guards; each new guard shape recompiles.
Common mistakes · 3
- Shrinking the batch for a fragmentation OOM. Smaller tensors can fragment worse; expandable segments or staged allocation often fixes the real cause.
- Enabling checkpointing without accounting for the extra forward FLOPs. Step time grows by the recompute, so MFU falls while HFU counts the extra work.
- Allowing
allow_in_graphas a quick fix for every break. It bypasses safety checks and can silently produce wrong results.
Try it yourself
Closed-book, before checking anything
torch._dynamo.explain on a toy function with a data-dependent branch and name the break.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Memory shows 10 GB free but a 2 GB allocation fails. What is the likely cause?Answer
Fragmentation: no single free block fits 2 GB. Check the block-size histogram and expandable-segments behavior before changing the model.
2.Peak memory lands on activations at long sequence. Which fixes preserve the update?Answer
Activation checkpointing with recomputation, or offload with correct restore. Both keep the mathematical update while trading compute or transfer for memory.
3.Step time jumps after adding a print of a tensor value. What happened?Answer
A graph break: Dynamo cannot trace the builtin
printwith a tensor argument, so it splits the graph there and the step pays a device sync to read the value. Confirm withtorch._dynamo.explainorTORCH_LOGS=graph_breaks.
Practice
- CS336 Assignment 2:
memory_profilingSection 2.1.6
memory_profilingin the Spring 2026 handout; attribute the peak at short versus long sequence and the mixed-precision difference on the memory timelineUse the CPU and portable snapshot path on your machine. GPU peaks need CUDA; report allocator settings beside every number.
You're done when
You can classify one OOM from snapshot evidence and silence one recompilation storm by removing or scoping the break that caused it.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 9 more in the section
- AI Systems Performance Engineering - Chapters 1 to 5, 13 and 14Chris Fregly (O'Reilly) · required
Use Chapter 1 for goodput and reproducibility, Chapters 2 to 5 for topology, orchestration, communication, storage and the data pipeline, Chapter 13 for PyTorch profiling and scaling, and the Chapter 14 sections on graph breaks and recompilation. Run only the companion labs for the bottleneck you observe, preserve workload correctness and record hardware assumptions.
- Machine Learning Engineering Open Book - Network, Debug, Training Performance and OrchestrationStas Bekman · required
Use
network/debug/README.md, the hang, crash and OOM sections ofdebug/pytorch.md,training/performance/README.md,storage/README.mdandorchestration/slurm/users.mdas an incident-driven reference. Build one symptom-to-evidence-to-cause runbook rather than reading every page.
Also in this section
- Machine Learning Systems Volume II - Fleet Orchestration and Performance EngineeringML Systems Textbook · primary
Read Scheduling Problem, Orchestration Paradigms, Topology-Aware Scheduling, Elastic Scheduling, Cost Optimization, Multi-Tenancy and Quotas and Debugging Cluster Utilization, then Memory Wall and Roofline Diagnosis, Graph Compilation, Communication-Computation Overlap, System Profiling and Measurement at Scale at https://mlsysbook.ai/vol2/performance_engineering/performance_engineering.html. Use the framework to choose one bottleneck-specific lab and one rollback metric.
- PyTorch Flight Recorder TutorialsPyTorch · support
Read the environment-variable Flight Recorder tutorial (trace buffer, dump on timeout,
fr_traceanalysis), then the newer tutorial at https://docs.pytorch.org/tutorials/intermediate/debug_hangs_with_flight_recorder.html, which needstorchcommsand can run on CPU with Gloo. Diagnose one injected hang from per-rank dumps. - MegaScale: Scaling Large Language Model Training to More Than 10,000 GPUsJiang et al. (NSDI 2024) · support
Read the efficiency optimizations, the fault-tolerance loop (heartbeats, diagnostics, fast restart) and the straggler and diagnosis tooling. Its MFU and scale numbers are its own cluster's results.
- Revisiting Reliability in Large-Scale Machine Learning Research ClustersKokolis et al. (2024) · support
Read the failure taxonomy, mean time to failure versus job size and the scheduler-side metrics. Use them to model goodput with failures for one job size.
- How to Scale Your Model - Chapters 1, 5, 9 and 12Google DeepMind · required
Use rooflines, training cost models, profiling workflow and GPU topology to predict the dominant limit of one run. Compare the prediction with a trace and quantify the residual before proposing a change.
- CS336 Assignment 2 (Spring 2026) - Profiling and Parallelism AnalysisStanford University · required
Revisit Section 2 profiling and Section 8 communication analysis. Produce warmup-controlled timing, Nsight or PyTorch traces, memory evidence and analytic DP, FSDP, TP and 2D comparisons on configurations you can execute honestly.
- Ultra-Scale Playbook - Benchmarking ConfigurationsHugging Face · support
Study the configuration-search experiments and Lessons learned on benchmarking as method. Its heatmaps are its own H100 cluster's results; reproduce the method on a tiny legal search space, separating analytic predictions, simulations and measurements.
- TorchTitanPyTorch · depth
Read
docs/debugging.md(memory snapshots, fake-backend modes, Flight Recorder dumps) and the CPU unit tests undertests/unit_tests/cpu/, then the configuration, metrics, profiling, checkpoint and parallelization seams at a pinned commit. Select one bounded issue or measurable improvement and follow the contribution standards; do not attempt a wholesale rewrite. - Distributed Training Systems LaboratoryRoadmap-Final · support
Complete the capstone with a fixed workload, correctness oracle, analytic plan, fault campaign, aligned traces and one real-code extension. Label CPU simulation, single-GPU evidence and multi-GPU evidence separately.