Unit 6 of 9 · about 4 hours · implement, measure

Activation checkpointing and recomputation

Checkpointing converts the activation term of the memory model into extra compute. Done blindly it slows training for no reason; done deliberately it is what lets larger batches fit.

You'll be able to

  • Wrap a segment with torch.utils.checkpoint and state exactly what stays alive and what is recomputed.
  • Choose use_reentrant False with reasons, and pass it explicitly.
  • Measure the memory saving against the recompute cost and the RNG effects.

Covers

Activation checkpointing and recomputation
1

Read

In this order, only the parts listed

0 of 2 done

  1. torch.utils.checkpoint APIPyTorch - checkpointing, numerical accuracy and CUDA semantics

    checkpoint signature and semantics: only args stay alive, region outputs are recomputed in backward; use_reentrant False versus True differences; preserve_rng_state with the multi-device caveat; determinism_check and debug

  2. Which layers to checkpointPyTorch - reliability and performance recipes

    General optimizations, Checkpoint intermediate buffers: large layer outputs with small recompute cost as targets

2

Focus on

  • Only the checkpoint inputs stay alive; everything the region computes is rerun in backward. Memory saved is the activations the region would have kept, and the price is one extra forward of the region during backward.
  • Non-reentrant is the recommended path: it supports grad, keyword args and nested structures, and it stops recomputation early once the needed activations exist.
  • RNG state is stashed and restored by default so dropout masks match. Turning that off changes gradients, not forward outputs.
  • Recompute reruns the region code. Globals read inside the region, device moves, and multi-device RNG all break the equivalence silently or loudly.
Common mistakes · 3
  • Omitting use_reentrant and assuming a default. Current PyTorch warns that it must be passed explicitly; pass False deliberately.
  • Wrapping tiny cheap regions. Recompute then costs more than the memory it saves; target large outputs with small recompute cost.
  • Changing code or globals between forward and backward. The recompute must see the identical function, or gradients are silently wrong.
3

Try it yourself

Closed-book, before checking anything

On CPU, checkpoint a dropout block with use_reentrant=False and show its gradients equal the plain block at the same seed (torch.equal held on CPU with PyTorch 2.14). Rerun with preserve_rng_state=False and show the gradients differ while the forward outputs still match.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.What stays alive across a checkpointed region, and what is recomputed?Answer

    Only the input args stay alive. The region reruns in backward to rebuild every forward tensor it needs.

  2. 2.With preserve_rng_state False, forward outputs still match but gradients differ. Why?Answer

    Forward runs once either way. The flag only controls the RNG state used by the backward recompute, so only dropout-dependent gradients change.

  3. 3.What happens when use_reentrant is omitted, and which value is recommended?Answer

    PyTorch warns that it must be passed explicitly. False is recommended: it supports grad, kwargs and nested structures with early stop.

  4. 4.With use_reentrant=True and no input requiring grad, the region's parameters get no gradients. Why, and which variant avoids it?Answer

    The reentrant variant runs the region under no_grad inside an autograd Function whose output requires grad only if an input does. With none, backward never enters the region and PyTorch warns that gradients will be None. The non-reentrant variant has no such requirement.

5

Practice

  • TrenTorch: Gradient Checkpointing

    Implement forward_full, backward_full, forward_checkpointed and backward_checkpointed for a stack of layers, plus count_stored_activations

    The checkpointed gradients must match the full ones, since recomputation repeats the same operations. The section mini-project then measures the memory saved in PyTorch with equivalence checks.

You're done when

Your checkpointed block matches plain gradients at a fixed seed within a stated tolerance, and you can price any block in memory saved versus recompute added.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 7 more in the section
  • PyTorch - reliability and performance recipesPyTorch · primary

    Use the Profiler, Automatic Mixed Precision, model loading and Benchmark recipes, then the Performance Tuning Guide. Apply each to one compact model from an earlier section and keep a CPU fallback when CUDA is unavailable.

  • PyTorch - checkpointing, numerical accuracy and CUDA semanticsPyTorch · required

    Use the official user-guide entries for torch.utils.checkpoint, numerical accuracy, CUDA semantics, reproducibility and serialization. Predict memory categories before measuring and define resume equivalence before running.

Also in this section

  • PyTorch - compiler troubleshootingPyTorch · required

    Read graph breaks, guards, recompilations and logging. Compile one stable fragment, intentionally trigger a graph break or recompilation, inspect it, and compare eager and compiled outputs and gradients.

  • Deep Learning Training DebuggerRoadmap-Final · reference

    Use the failure-injection, measurement and evidence rules as the deeper standard. The full Tier 2 project is a later route and is not added to this stage milestone.

  • TensorTonic - mixed-precision memory and transformer FLOPsTensorTonic · support

    Solve only Mixed-Precision Training Memory Accountant and Transformer Training FLOP Estimator. Reconcile both with the compact model's profiler and document every included and excluded term.

  • Learn PyTorch - profiler walkthroughDaniel Bourke · optional

    Use notebook 10 only if the official profiler route remains unclear. Transfer the relevant annotations into the compact model instead of keeping the tutorial code.

  • TrenTorch - precision, checkpointing and resumeTrenTorch · support

    Solve Loss Scaling, FP16/BF16 Representable Range, Gradient Checkpointing and Resume-from-checkpoint in NumPy, then reproduce each behavior with the PyTorch API in the compact model.

  • Python os - `os.replace`Python Software Foundation · reference

    Read os.replace for the atomic-rename step of checkpoint writes: save to a temp file in the same directory, flush and fsync, then replace the final name.

  • Hands-On Machine Learning with Scikit-Learn and PyTorchAurelien Geron (O'Reilly, 2025) · support

    Read Appendix B, Reduced Precision Models and Mixed-Precision Training, for why float16 training underflows and what fp32 primary weights and loss scaling fix.