Search

Search papers and lessons

Activation Checkpointing

Level 3 · 12 min read

Activation checkpointing cuts training memory by storing only some intermediate values and recomputing the rest in the backward pass, at the cost of extra arithmetic.

On this page

  • Colour = topic mix
  • Discrete math
  • Calculus
  • Systems
  • Linear algebra
  • Neural network basics
  • Probability
  • ReadReady to readNot yet

TL;DR

Activation checkpointing is a way to train a deep network with less memory. Backpropagation needs the values each layer produced on the forward pass, and keeping all of them can fill a GPU. Checkpointing keeps only a few of them and recomputes the missing ones when the backward pass needs them. The cost is roughly one extra forward pass per training step, and the saving can be large enough to fit a model or batch that would otherwise not fit at all.

Builds on: Backpropagation, GPU Memory Hierarchy · Leads to: Megatron-LM, ZeRO

Where it's used

Training large language models. A Transformer with dozens of layers stores a large intermediate tensor per layer for every token in every sequence in the batch. The large-model training papers Megatron-LM: Training Multi-Billion Parameter Language Models and ZeRO: Memory optimizations Toward Training Trillion Parameter Models both treat checkpointing as one of the standard tools for fitting a model into GPU memory.

Fine-tuning on one GPU. Libraries such as PyTorch provide a checkpointing wrapper (torch.utils.checkpoint). A person fine-tuning a medium-sized model on a single card can often turn it on, keep the same batch size, and avoid running out of memory. The step takes longer, but the run finishes.

Larger batches on the same hardware. Memory for stored activations grows with the batch size. Checkpointing lets a team raise the batch size on a fixed GPU, which can improve how well the hardware is used, even though each individual step is slower.

How it works

Take a chain of four layers, each of which doubles its input. Each layer has a weight w=2w = 2. The input is a0=1a_0 = 1, and the loss is the final output, so L=a4L = a_4.

  1. Forward pass. Compute the layers in order: a1=2×1=2a_1 = 2 \times 1 = 2, a2=2×2=4a_2 = 2 \times 2 = 4, a3=2×4=8a_3 = 2 \times 4 = 8, a4=2×8=16a_4 = 2 \times 8 = 16. The loss is L=16L = 16. Check: each value is twice the one before it.

  2. Normal backward pass. Backpropagation walks back from the loss. Each layer needs the value that went into it on the forward pass, its activation, to compute its weight gradient. Store everything, so the activations a0,a1,a2,a3a_0, a_1, a_2, a_3 (four numbers) are kept in memory. Check: memory now holds four activations. With nn layers it would hold nn.

  3. Checkpointed forward pass. Run the same forward computation but keep only a0a_0 and a2a_2. The values a1a_1 and a3a_3 are thrown away, so the forward pass stores two numbers instead of four. Check: the stored values are at positions 0 and 2, every second layer.

  4. Recompute for the last layer. Backward starts at layer 4, which needs a3a_3. It is missing, so run layer 3 again from the stored a2a_2: a3=2×4=8a_3 = 2 \times 4 = 8. Layer 4's weight gradient is a3×∂L∂a4=8×1=8a_3 \times \frac{\partial L}{\partial a_4} = 8 \times 1 = 8. Check: the recomputed 8 matches the value from step 1.

  5. Continue backward. Layer 3 needs a2a_2, which is stored. Its weight gradient is a2×∂L∂a3=4×2=8a_2 \times \frac{\partial L}{\partial a_3} = 4 \times 2 = 8. Layer 2 needs a1a_1, which is missing, so run layer 1 again from the stored a0=1a_0 = 1 to get a1=2a_1 = 2. Layer 2's weight gradient is a1×∂L∂a2=2×4=8a_1 \times \frac{\partial L}{\partial a_2} = 2 \times 4 = 8. Check: again every value matches what the full storage version would give.

  6. Finish. Layer 1 needs a0a_0, which is stored: a0×∂L∂a1=1×8=8a_0 \times \frac{\partial L}{\partial a_1} = 1 \times 8 = 8. All four weight gradients are 8, the same as with full storage.

The picture shows which values are kept and which are rebuilt.

flowchart LR
  A0[a0 stored] --> L1[layer 1] --> A1[a1 recomputed]
  A1 --> L2[layer 2] --> A2[a2 stored] --> L3[layer 3] --> A3[a3 recomputed]
  A3 --> L4[layer 4] --> LOSS[loss]

The activations here are the layer outputs stored for the backward pass. They are not the same thing as an Activation Function, although the word is shared.

246810121416051015checkpoint every k layers (k)values held in memory
  • stored values, n = 16
With 16 layers, checkpointing every k layers keeps about 16/k checkpoints plus up to k recomputed values in memory at once. The lowest point is at k = 4, where 8 values are held.

The math

Setting

A network computes ak=fk(ak−1;wk)a_{k} = f_k(a_{k-1}; w_k) for k=1,…,nk = 1, \dots, n, starting from input a0a_0. Its loss is L=g(an)L = g(a_n). Backpropagation computes each weight gradient, a Partial Derivative, by the Chain Rule:

∂L∂wk=∂L∂ak⋅∂ak∂wk.\frac{\partial L}{\partial w_k} = \frac{\partial L}{\partial a_k} \cdot \frac{\partial a_k}{\partial w_k}.

For a layer of the form ak=wk ak−1a_k = w_k\, a_{k-1}, the second factor is ak−1a_{k-1}, so the weight gradient needs the stored input ak−1a_{k-1}. This is why the activations must be kept. The gradient with respect to the input, ∂L/∂ak−1=wk⋅∂L/∂ak\partial L / \partial a_{k-1} = w_k \cdot \partial L / \partial a_k, is passed back without needing storage.

Step 2 in symbols: storing everything

Storing every activation a0,…,an−1a_0, \dots, a_{n-1} takes memory proportional to nn. With nn layers the peak is nn stored values.

Step 3 in symbols: checkpoints

Choose a set of checkpoint positions. Keep only the activations at those positions. Let the layers form segments of kk layers each. Keep one checkpoint at the start of each segment, which gives n/kn/k stored values.

Step 4 in symbols: recomputing one segment

During the backward pass, when a missing activation is needed, recompute the segment that contains it from its checkpoint. Within a segment of length kk, the recomputation can hold up to kk activations at once, as the backward pass walks through that segment. Only one segment is recomputed at a time, so the peak is

M(k)=nk+k.M(k) = \frac{n}{k} + k.

The first term counts checkpoints. The second counts the activations of the one segment being recomputed.

Choosing the segment length

Minimise M(k)M(k). Setting the derivative to zero, −n/k2+1=0-n/k^2 + 1 = 0, so k=nk = \sqrt{n}. The peak becomes

M(n)=2n.M(\sqrt{n}) = 2\sqrt{n}.

For n=16n = 16 this is 2×4=82 \times 4 = 8, which matches the plot. Storing everything needs 16 values, so checkpointing halves the peak here, and for large nn the gap grows as n\sqrt{n} compared with nn. This is the sublinear memory result in the 2016 paper of Chen and colleagues cited in the sources.

The cost of recomputation

Let a forward pass over all layers cost FF, and a backward pass cost about 2F2F, since each layer's backward work involves roughly two multiplications of the same size as its forward work. A checkpointed step does one forward pass, a recomputed forward pass, and a backward pass:

cost≈F+F+2F=4F,compared with 3F.\text{cost} \approx F + F + 2F = 4F, \qquad \text{compared with } 3F.

Each segment is recomputed once, so the extra forward work is at most one full forward pass. The step is about one third slower in this simple accounting. Real systems vary, because the backward pass does not always cost exactly twice the forward pass.

Worked examples

Example
1. Two layers, two values

A network has two layers with weight 2 each and input a0=3a_0 = 3. Store only a0a_0 and recompute a1a_1 when needed.

  1. The forward pass gives a1=2×3=6a_1 = 2 \times 3 = 6 and a2=2×6=12a_2 = 2 \times 6 = 12.
  2. Full storage would keep a0a_0 and a1a_1, which is 2 values.
  3. Checkpointing keeps only a0=3a_0 = 3.
  4. In the backward pass, layer 2 needs a1a_1. Recompute it from a0a_0: a1=2×3=6a_1 = 2 \times 3 = 6.
  5. The stored memory is 1 value instead of 2, at the cost of one extra layer call.

The saving is small here, but the mechanism is the same at any size.

Example
2. Standard case: sixteen layers

A network has n=16n = 16 layers. Compare the peak memory of full storage and of checkpointing with segments of 4 layers.

  1. Full storage: n=16n = 16 activations are held at the peak.
  2. Checkpointing with k=4k = 4: there are n/k=16/4=4n/k = 16/4 = 4 checkpoints.
  3. One segment of 4 activations is recomputed at a time: k=4k = 4.
  4. Peak: 4+4=84 + 4 = 8 values.
  5. Check with the formula 2n=2×4=82\sqrt{n} = 2 \times 4 = 8. The two agree, and the segment length k=16=4k = \sqrt{16} = 4 is the best choice.
  6. The extra arithmetic is at most one forward pass, so the step costs about one third more.
Example
3. A realistic model: a 48-layer network

A transformer has 48 layers. At the chosen batch size, each layer's stored activations take 1.5 gigabytes. Compare the memory of full storage with checkpointing in segments of 8 layers.

  1. Full storage: 48×1.5=7248 \times 1.5 = 72 gigabytes of activations, which is more than many single GPUs hold for this kind of work.
  2. Checkpoints: the segments start at layers 0, 8, 16, 24, 32 and 40, so there are 6 checkpoints. Storing them takes 6×1.5=96 \times 1.5 = 9 gigabytes.
  3. Recomputation: during the backward pass one segment of 8 layers is rebuilt at a time, which takes 8×1.5=128 \times 1.5 = 12 gigabytes.
  4. Total: 9+12=219 + 12 = 21 gigabytes.
  5. The memory fell from 72 to 21 gigabytes, about 29 percent of the original. The step takes roughly a third longer, as in Step 6.

Try it: a network has 64 layers, each with 1 gigabyte of activations, and segments of 8 layers. Give the peak memory with checkpointing, and say what full storage would need. Answer: there are 8 checkpoints, so 8 gigabytes, plus one recomputed segment of 8 gigabytes, for 16 gigabytes in total. Full storage needs 64 gigabytes.

Common mistakes and tradeoffs

It is tempting to think that checkpointing makes training faster because it saves memory. In fact it makes each step slower, because some work is done twice. The benefit is that a model or batch that would not fit can run at all, or that a larger batch can be used, which may give more total throughput.

It is tempting to think that checkpointing changes the result. In fact, when the recomputation is done with the same inputs and the same random state, the gradients equal those of full storage. The only difference is time and memory. Randomness inside a layer, such as Dropout, is the main care point: the recomputed values must reproduce the original random choices, and libraries handle this by saving the random state.

It is tempting to think that more checkpoints are always better. In fact more checkpoints store more values, and fewer checkpoints recompute longer segments. The best choice balances the two, which is the n\sqrt{n} rule in the Math section. A common practical choice is to checkpoint at each block of a Transformer, which matches how the model is built.

When to use it: when activation memory is the limit, which is common for deep networks and long sequences, and when some slowdown is acceptable.

When not to use it: when memory is plentiful and speed matters most, or when the model is shallow enough that its activations fit easily.

Alternatives: smaller batches, lower-precision numbers (see Mixed-Precision Training), and splitting the model or optimizer state across devices (Model Parallelism, Data Parallelism, and ZeRO). These can be combined with checkpointing.

History

The reverse-mode differentiation that backpropagation uses was popularised for neural networks by Rumelhart, Hinton and Williams in 1986, and at that time memory was not the main concern. Numerical analysts working on automatic differentiation of simulations had already studied the trade between storing intermediate values and recomputing them, because their programs were long time-stepping loops with large states.

As networks deepened and GPUs became the standard hardware, memory became the limit. In 2016 Chen, Xu, Zhang and Guestrin showed that checkpointing the layers at intervals of about n\sqrt{n} reduces activation memory from order nn (linear) to order n\sqrt{n}, at the cost of one extra forward pass. The idea caught on because it required no change to the model, only to how the backward pass is scheduled. Later large-model systems built it into their standard memory toolkits.

Recap

  • Backpropagation needs the values each layer produced on the forward pass.
  • Storing all of them costs memory proportional to the number of layers.
  • Checkpointing stores only some values and recomputes the missing ones from the nearest checkpoint during the backward pass.
  • With segments of about n\sqrt{n} layers, the peak memory is about 2n2\sqrt{n} values, instead of nn.
  • The price is roughly one extra forward pass per step, and the gradients are unchanged.
  • Large-model training systems such as Megatron-LM and ZeRO use this trade as one of their memory tools.

What to read next: Megatron-LM: Training Multi-Billion Parameter Language Models shows checkpointing inside a large transformer training setup, and ZeRO: Memory optimizations Toward Training Trillion Parameter Models shows how the other memory costs are split across devices.

Check yourself

QuestionA network stores 9 activations with no checkpointing. Using the rule of the form n/k + k with n = 9, what segment length k minimises the peak, and what is the peak?Show answer

The best kk is 9=3\sqrt{9} = 3. The peak is 9/3+3=3+3=69/3 + 3 = 3 + 3 = 6 values, down from 9.

QuestionCalculate: a network has 36 layers and segments of 6 layers. How many checkpoints are stored, and what is the peak number of activations when the backward pass recomputes one segment?Show answer

There are 36/6=636 / 6 = 6 checkpoints, and one segment of 6 activations is recomputed at a time. The peak is 6+6=126 + 6 = 12 values.

QuestionWhy does checkpointing need the forward values to be reproduced exactly during recomputation, and what goes wrong if a layer contains [[dropout]] and the random choices are not saved?Show answer

Backpropagation uses the activations to compute gradients for the same forward computation that produced the loss. If recomputation gives different values, the gradients no longer belong to the computed loss and training is corrupted. A Dropout layer draws random choices on each call, so the recomputed dropout mask may differ from the original. Libraries avoid this by saving the random state for each recomputed segment, so the replay makes the same choices.

QuestionA team is training a model that fits in memory with batch size 4 but not with batch size 8. Should they turn on checkpointing to train with batch size 8? Give one reason for and one against.Show answer

For: checkpointing reduces the activation memory that grows with batch size, so batch size 8 may fit, and a larger batch can use the hardware better. Against: each step does about one extra forward pass, so each step is slower, and the total time per sample must be compared with the alternatives before deciding.

Sources