Gradient Checkpointing & Activation Recomputation

Trading compute for memory: the checkpointing algorithm, optimal checkpoint placement, selective recomputation, memory savings analysis, and integration with pipeline/tensor parallelism.

Intermediate

Prerequisites

Table of Contents

  1. Learning Objectives
  2. Notation
  3. Core Intuition
  4. The Activation Memory Problem
  5. Basic Checkpointing
  6. Optimal Checkpoint Placement
  7. Selective Recomputation
  8. Memory Savings Analysis
  9. Integration with Parallelism
  10. Common Pitfalls
  11. Summary
  12. Exercises

Learning Objectives

  1. Compute activation memory for a transformer model.
  2. Derive the memory-compute tradeoff for checkpointing.
  3. Prove that L\sqrt{L} checkpoints minimize memory for a chain of LL layers.
  4. Explain selective recomputation and which operations to recompute.
  5. Analyze checkpointing interaction with pipeline parallelism.

Notation

  • LL — number of layers
  • aa — activation memory per layer
  • CC — number of checkpoints
  • TfT_f — forward time per layer

Core Intuition

Training requires storing intermediate activations from the forward pass to compute gradients in the backward pass. For a 70B model processing 4K tokens: activation memory can reach 100+ GB — often more than the model weights. Checkpointing drops some activations and recomputes them when needed during backward, trading ~33% more compute for dramatically less memory.

Gradient Checkpointing

Forward pass — stored vs recomputed activationsrecomprecomprecomprecomp4 checkpoints storedPeak mem: 34 MB (68% ↓)Compute overhead: +45%
Segments
4
StoredRecomputed
Explore: Gradient checkpointing stores activations at segment boundaries only — recomputing intermediate values during backward. More segments = less memory, more compute.

The Activation Memory Problem

Standard training: Store all LL layers' activations:

Memory=L×a.(1)\text{Memory} = L \times a. \tag{1}

For a transformer with T=4096,d=4096,L=32T=4096, d=4096, L=32:

  • Per-layer activations: T×d×4\sim T \times d \times 4 (attention + FFN intermediate) 256\approx 256 MB.
  • Total: 32×25632 \times 256 MB =8= 8 GB per sequence.
  • With batch size 4: 32 GB just for activations.

Basic Checkpointing

Strategy: Only save activations at CC evenly-spaced checkpoints. During backward, recompute from the nearest checkpoint.

Memory: CC checkpointed activations + 1 segment of recomputed activations:

Memory=C×a+LC×a.(2)\text{Memory} = C \times a + \frac{L}{C} \times a. \tag{2}

(Store CC checkpoints + at most L/CL/C layers between checkpoints during recomputation.)

Compute overhead: Re-run forward pass for each segment: ~33% more total compute (each layer's forward is computed twice: once in the original forward, once during backward recomputation — but the second time only for the segment being processed).


Optimal Checkpoint Placement

Minimize f(C)=C+L/Cf(C) = C + L/C (memory expression without constant aa).

dfdC=1L/C2=0    C=L.(3)\frac{df}{dC} = 1 - L/C^2 = 0 \implies C^* = \sqrt{L}. \tag{3}

Minimum memory: 2L×a2\sqrt{L} \times a.

For L=32L=32: C=5C = 566 checkpoints, memory 11a\approx 11a (vs 32a32a without checkpointing). 3x reduction.


Selective Recomputation

Not all operations are equal. Some activations are cheap to recompute and expensive to store:

Always recompute (cheap compute, large memory):

  • Attention matrices (O(T2)O(T^2) memory but O(T2d)O(T^2d) compute — actually, with FlashAttention, they're never stored anyway).
  • Dropout masks (random, trivially regeneratable from seed).

Always store (expensive compute, small memory):

  • LayerNorm statistics (mean, variance): tiny memory, moderate compute.
  • Linear projection outputs: moderate memory, expensive to recompute.

Selective strategy: Checkpoint between transformer blocks (store input to each block); recompute attention + FFN within blocks. Memory: 1 activation per layer (T×dT \times d) instead of all intermediates.


Memory Savings Analysis

Without checkpointing:

  • Activations per layer: 10Td\sim 10Td (attention QKV, attention output, FFN up, FFN down, residuals).
  • Total: 10LTd10LTd.

With checkpointing per block:

  • Store: LTdLTd (one hidden state per layer).
  • Recompute: intermediates within each block during backward.
  • Savings: 10×\sim 10\times reduction.

With FlashAttention + checkpointing:

  • Don't store T×TT \times T attention matrix (FlashAttention handles this).
  • Don't store intermediate FFN activations (recomputed).
  • Store only: layer inputs + LayerNorm stats.
  • Near-optimal memory usage.

Integration with Parallelism

Pipeline parallelism: Each stage must store activations for PP micro-batches (1F1B schedule). Checkpointing reduces each micro-batch's activation footprint.

Tensor parallelism: Activations are split across TP ranks. Checkpointing saves the split activations and recomputes when needed (each rank recomputes independently).

Combined savings: For L=32,P=4,M=8L=32, P=4, M=8:

  • Without checkpointing: 10LTd×P=10×32×T×d×410LTd \times P = 10 \times 32 \times T \times d \times 4 (per micro-batch × stages in memory).
  • With checkpointing: LTd×P=32×T×d×4LTd \times P = 32 \times T \times d \times 4. 10x less.

Common Pitfalls

Pitfall 1. Checkpointing too frequently. Every checkpoint → no recomputation → wastes memory on the checkpoint storage itself.

Pitfall 2. Not using deterministic dropout. If dropout masks aren't reproducible during recomputation, gradients will be incorrect. Save the RNG state at each checkpoint.

Pitfall 3. Checkpointing with mixed precision incorrectly. FP16 activations saved at checkpoints must be used (not recomputed in FP32) to maintain gradient consistency.


Summary

  • Activation memory grows linearly with layers and sequence length.
  • Checkpointing trades ~33% extra compute for O(L)O(\sqrt{L}) memory.
  • Optimal: L\sqrt{L} checkpoints for O(L)O(\sqrt{L}) memory.
  • Selective recomputation: Recompute cheap operations (attention, dropout); store expensive ones.
  • Essential for training large models — used universally with Flash Attention.

Exercises

Exercise 1. For L=48L=48 layers: compute optimal CC, memory with and without checkpointing.

Exercise 2. Derive the exact compute overhead of checkpointing (show why it's 33% for uniform segments).

Exercise 3. For a 70B model with T=8192T=8192: compute activation memory with and without checkpointing + FlashAttention.

Exercise 4. Design a selective recomputation strategy that minimizes memory while adding < 10% compute overhead.

Exercise 5. Explain why checkpointing is especially important for pipeline parallelism (hint: PP micro-batches in flight).