Foundations to Frontier
Tests
C. Programming, Tools and HPC › C6 Distributed Training

Gradient Checkpointing (Activation Recomputation)

Backpropagation needs the activations of every layer, so activation memory grows with depth, batch size and sequence length, and for long contexts it dwarfs the model's own memory. Gradient (activation) checkpointing stores only some activations during the forward pass and recomputes the others during the backward pass, trading extra computation for memory. This topic covers the store-everything, checkpointed and recompute-everything extremes, the √n schedule (memory O(√n) for one extra forward pass), optimal schedules, selective recomputation for transformers (recompute only the attention scores, whose memory grows with the square of the sequence length), and how to use torch.utils.checkpoint and framework options. In the exercises you implement all three strategies on a deep chain and verify identical gradients while counting memory and recomputation; then you find the optimal segment length and quantify full and selective recomputation for a 32-layer transformer at sequence lengths from 2k to 32k.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Bookmarks instead of photocopies

Suppose you must later walk back through every step of a long calculation. You could photocopy every page as you go (lots of paper), or you could keep only a bookmark every few pages and, when you need a page, redo the calculation from the nearest bookmark. Gradient checkpointing does exactly this during training: it keeps a few “bookmark” activations and recomputes the rest when the backward pass needs them, saving memory at the cost of some extra work.

Trading compute for memory: activation checkpointing
0123456789101112131415161718192021222324blue: stored checkpoints (layer outputs kept from the forward pass) · orange: recomputed for the current segment
activations in memory now 6
peak 10 (store-all: 25)
extra forward layers 19 (+26% compute)
Slide k: memory ⌈n/k⌉ + k is smallest near k = √n, while compute only grows from 0 to one extra forward pass (about +33% when backward costs twice the forward). In transformers, recomputing just the attention scores and softmax ("selective" checkpointing) removes the activation term that grows with the square of the sequence length for only a few percent of compute.
Why engineers care

Activation memory is what limits batch size, image resolution and context length: high-resolution satellite tiles, long telemetry sequences and 3D volumes all run out of GPU memory first because of activations, not weights. Checkpointing is often the single switch that makes such training fit.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Gradient checkpointing saves memory by…
  2. 2. What does it cost?
  3. 3. In the demo, which checkpoint spacing gives the smallest peak memory for many layers?

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

In PyTorch

from torch.utils.checkpoint import checkpoint, checkpoint_sequential

class Block(nn.Module):
    def forward(self, x):
        return checkpoint(self._forward, x, use_reentrant=False)   # don't store activations inside this block
    def _forward(self, x):
        return x + self.mlp(self.norm2(x + self.attn(self.norm1(x))))

y = checkpoint_sequential(model.layers, segments=8, input=x)       # n layers in 8 checkpointed segments

Hugging Face models expose model.gradient_checkpointing_enable(); Megatron-LM and DeepSpeed have --recompute-activations / selective recomputation options; JAX has jax.checkpoint (alias jax.remat). Recomputation must reproduce the same values: random operations like dropout restore their RNG state, which the frameworks handle.

📝 Quick check (Level 1)
0/3 answered
  1. 1. torch.utils.checkpoint.checkpoint(f, x) during forward…
  2. 2. JAX's equivalent is…
  3. 3. Why must dropout's random state be restored during recomputation?

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.

Three strategies

For a chain of n layers with forward cost t_f and backward cost t_b ≈ 2t_f:

  • Store all: n activations, no recomputation.
  • Recompute all: keep only the input; for each layer’s backward, recompute from the start: O(1) memory, O(n²) forward work.
  • Checkpoint every k: keep ⌈n/k⌉ checkpoints; in backward, recompute each segment’s k − 1 interior activations from its checkpoint. Peak memory ⌈n/k⌉ + k, minimized at k ≈ √n (memory ≈ 2√n); extra work n − ⌈n/k⌉ layer forwards, at most one extra forward pass (+33% when t_b = 2t_f).

Better schedules exist: Chen et al.’s recursive scheme reaches O(log n) memory for O(n log n) compute, and Griewank’s binomial checkpointing (Revolve) is optimal for a fixed number of checkpoint slots.

🐍 Exercise 1: three ways to backpropagate
For a chain of n tanh layers with hand-written backward, implement store-everything backpropagation, checkpointing every k layers (recompute each segment's interior from its checkpoint) and recompute-from-the-input; count forward evaluations and the peak number of stored activations; check that all three give identical gradients, confirmed by finite differences.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Peak memory (activations) for n = 64 layers with checkpoints every 8?
  2. 2. Extra compute of checkpointing every k layers is at most…
  3. 3. Recomputing everything from the input costs…

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.

Transformers: selective recomputation

Per transformer layer (fp16, micro-batch b, sequence s, hidden h, heads a, no tensor parallelism) the stored activations are about s·b·h·(34 + 5·a·s/h) bytes (Korthikanti et al.). The 5·a·s²·b term, from the attention score matrices, softmax and dropout masks, grows with the square of the sequence length but accounts for only a small share of the FLOPs. Selective recomputation recomputes just those, keeping the cheap-to-store, expensive-to-recompute matmul inputs; full recomputation keeps only each layer’s input (2·s·b·h). FlashAttention-style kernels already avoid materializing the s × s matrices, which is the same idea built into the kernel.

Combining with other memory savers

Checkpointing reduces activations; ZeRO/FSDP (C6.3) reduces model states; sequence and context parallelism (C6.2) split activations along the sequence; activation offloading moves them to CPU memory; smaller micro-batches with gradient accumulation (C6.5) cut activations at the cost of throughput.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Which activation term grows quadratically with sequence length?
  2. 2. Selective recomputation trades…
  3. 3. FlashAttention reduces activation memory because…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Recomputation, measured

Exercise 1. For 16 tanh layers: storing everything keeps 17 activations with 16 layer forwards; checkpointing every 4 keeps at most 8 (4 checkpoints plus the final output, plus 3 recomputed interior activations) with 28 forwards; recomputing from the input keeps 3 with 152 forwards. All three give gradients identical to each other and to finite differences.

Exercise 2: the √n rule and transformers.

For a 64-layer chain (backward = 2 × forward):

segment k 1 2 4 8 16 32 64
peak stored activations 65 34 20 16 20 34 65
time relative to no checkpointing 1.00 1.17 1.25 1.29 1.31 1.32 1.33

A 32-layer transformer (h = 4096, 32 heads, micro-batch 1, fp16), activation memory for the whole model and extra compute:

sequence none selective recomputation full recomputation
2 048 30.6 GB 9.1 GB (+2.6%) 0.5 GB (+33%)
8 192 380 GB 36.5 GB (+8.3%) 2.1 GB (+33%)
32 768 5 644 GB 146 GB (+19%) 8.6 GB (+33%)

At 2k tokens selective recomputation cuts activation memory 3.4× for 2.6% more compute; at 32k tokens storing everything would need 5.6 TB, selective recomputation 146 GB (still too much for one GPU without sequence parallelism), full recomputation 8.6 GB. The cost of selective recomputation grows with the sequence because the attention share of the FLOPs (4s²h against 24sh²) grows.

🐍 Exercise 2 (research): segment length and selective recomputation
Compute peak memory and relative time of checkpointing a 64-layer chain for segment lengths 1 to 64 and find the optimum; using the per-layer transformer activation formula, compare no recomputation, selective recomputation of the attention core and full recomputation for a 32-layer, 4096-wide model at sequence lengths 2k, 8k and 32k, in memory and extra compute.

Recomputation in AI, robotics and aerospace

  • Long-context models for telemetry, documents or genomes, where attention activations dominate.
  • High-resolution vision (large satellite tiles, 3D medical or terrain volumes) where per-sample activations are huge.
  • Physics-informed and differentiable simulators, which checkpoint time steps of long rollouts (the same idea as adjoint checkpointing in optimal control and data assimilation).
  • Fine-tuning large models on single GPUs together with LoRA and quantization.

References

  1. T. Chen, B. Xu, C. Zhang, C. Guestrin (2016). “Training deep nets with sublinear memory cost.” arXiv:1604.06174.
  2. A. Griewank, A. Walther (2000). “Algorithm 799: Revolve: an implementation of checkpointing for the reverse or adjoint mode of computational differentiation.” ACM TOMS, 26(1).
  3. V. Korthikanti et al. (2023). “Reducing activation recomputation in large transformer models.” MLSys.
  4. T. Dao et al. (2022). “FlashAttention: fast and memory-efficient exact attention with IO-awareness.” NeurIPS.
  5. PyTorch documentation (pytorch.org/docs): torch.utils.checkpoint.