Unit 8 of 12 · about 4 hours · derive, measure

Activation checkpointing, recomputation cost and selective policies

Activations are the elastic row of the ledger: checkpointing trades a bounded recompute cost for a large memory cut. The policy choice decides whether a bigger batch or a longer sequence fits.

You'll be able to

  • Derive the memory saving and extra forward cost of full versus selective checkpointing for a small stack.
  • Apply torch.utils.checkpoint with use_reentrant=False and validate the peak-memory change by measurement.
  • Choose checkpoint granularity from a memory profile instead of a rule of thumb.

Covers

Activation checkpointing and recomputation trade-offsSelective activation checkpoint policy
1

Read

In this order, only the parts listed

0 of 2 done

  1. Full versus selective recomputationUltra-Scale Playbook - First Steps: Training on One GPU

    Activation recomputation: full checkpointing at layer boundaries costing up to 30 to 40 percent extra compute, selective checkpointing of attention at about 70 percent memory saving for 2.7 percent cost on GPT-3 175B, and the HFU versus MFU accounting that follows

  2. CS336 Assignment 2: checkpointing mechanicsCS336 Assignment 2 (Spring 2026) - Sections 2 and 3

    Section 3.1 autograd residuals with saved_tensors_hooks and Section 3.2.1 gradient_checkpointing: the memory-optimal nested strategy with asymptotics, then the single-level granularity choice on a model size your GPU fits (the handout uses xl) validated by peak-memory profile

2

Focus on

  • Full checkpointing stores only layer-boundary activations and replays each layer forward in backward, adding up to a full extra forward pass. Selective checkpointing stores the cheap-to-keep feedforward activations and recomputes only attention, which is expensive to store but cheap to redo.
  • Recompute cost belongs in the FLOP count honestly: hardware FLOPs include the replayed forward, model FLOPs exclude it. Recompute can raise HFU while MFU falls, because MFU improves only when the same model work finishes sooner.
  • Checkpointing changes which tensors backward saves, not the mathematics. Gradients must match the uncheckpointed run; only the memory timeline and step time change.
  • Pin use_reentrant=False explicitly. Omitting it in PyTorch 2.14.1 warns and falls back to the reentrant mode, which supports only backward, needs an input that requires grad, and always recomputes the whole region.
Common mistakes · 3
  • Passing preserve_rng_state=False to skip the RNG bookkeeping while the region uses dropout. The replay then draws different masks and the gradients silently differ; with the default both modes replay torch RNG exactly, but randomness from other libraries is never replayed.
  • Wrapping the loss or the optimizer step in a checkpointed region. Recompute replays forward ops only; step side effects replay wrongly or not at all.
  • Comparing step times with and without checkpointing as pure overhead. The checkpointed run may fit a larger microbatch, so compare at equal global batch or not at all.
3

Try it yourself

Closed-book, before checking anything

Closed-book, sketch the nested checkpoint plan for a stack of N identical blocks with its memory asymptotics. Then checkpoint one granularity on a tiny model, show gradients match the baseline and the peak-memory profile moves as predicted.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.Why does selective checkpointing target attention activations?Answer

    They grow largest with sequence length yet cost little to recompute per byte saved. Feedforward activations are cheaper to store relative to their recompute cost, so they are kept.

  2. 2.A checkpointed run matches loss but its step is slower. Is the optimization failing?Answer

    Not necessarily. Extra forward work is expected; the win is fitting a larger batch or longer sequence. Judge at equal global batch and memory, not per-step time alone.

  3. 3.Checkpointed and baseline gradients differ with dropout on. What is the first suspect?Answer

    RNG state across the replay. Forward randomness must be preserved and replayed identically; otherwise backward differentiates a different graph.

  4. 4.What distinguishes HFU from MFU when recomputation is on?Answer

    HFU counts the replayed forward in achieved FLOPs; MFU counts only the required forward and backward. Recompute raises hardware work while model work stays fixed.

5

Practice

  • CS336 Assignment 2: gradient_checkpointing

    Section 3.2.1 on a model size your hardware fits: the nested-strategy asymptotics sketch, then the single-level granularity choice validated against the peak-memory profile of the neighboring sizes

    A writeup problem with no public tests; checking is your gradient-equality test plus the before and after memory profiles.

You're done when

Your checkpointed run matches baseline gradients and your profile explains which granularity fits the next larger batch.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 11 more in the section
  • 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.

  • 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.

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.

  • 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.

  • 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.

  • 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.