7 routes42 sections324 units

Unit 8.6 · about 4 h

226 / 324

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.

  • implement
  • measure

You can now

  • 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

Study, in this order

2 steps

  1. `torch.utils.checkpoint` API
    PyTorch - 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 checkpoint
    PyTorch - reliability and performance recipes

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

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.

Reproduce closed-book

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.

Traps

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

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.

Self-test

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

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

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

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

Completion criterion

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

Mark passed, then open 8.7 Only mark this when you can do it without notes.

Leads to

Comes after

Resources for this unit

  • PyTorch - reliability and performance recipes
    PyTorchprimarycourse
    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 semantics
    PyTorchrequiredreference
    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 troubleshooting
    PyTorchrequiredreference
    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 Debugger
    Roadmap-Finalreferenceassessment
    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 FLOPs
    TensorTonicsupportpractice
    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 walkthrough
    Daniel Bourkeoptionalimplementation
    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 resume
    TrenTorchsupportpractice
    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 Foundationreferencereference
    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 PyTorch
    Aurelien Geron (O'Reilly, 2025)supporttheory
    Read Appendix B, Reduced Precision Models and Mixed-Precision Training, for why float16 training underflows and what fp32 primary weights and loss scaling fix.

Quick find

Search Michi

Type to search every route, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels