AI State of the Art
SOTA/Training: Modern Training Techniques/28 min
Section 94

Activation Recomputation (Gradient Checkpointing)

Listen as a podcast β†’

One name misleads, the other explains

The technique is usually called gradient checkpointing. The name is doubly unhelpful: it does not checkpoint gradients, and it does not checkpoint anything in the ordinary sense. Its second name, activation recomputation, says exactly what happens, and it is the one worth keeping.

The mechanism fits in those two words. Instead of holding on to activations, you throw them away and recompute them when the backward pass needs them. Nothing more.

The problem: why the backward pass needs the forward pass

An activation is an intermediate result of the forward pass: the output of one layer, which becomes the input of the next. Unlike a weight, it is not a learned value, it is a value computed on the text at hand. The distinction is developed in Backpropagation.

Why must they be kept? Take the simplest layer, y=Wxy = Wx, where WW is the learned weight matrix and xx the input activation. The backward pass has to work out how much to correct each weight, that is:

βˆ‚Lβˆ‚W=βˆ‚Lβˆ‚yβ‹…x⊀\frac{\partial L}{\partial W} = \frac{\partial L}{\partial y} \cdot x^{\top}

Read the formula. LL is the loss, the single number measuring the model's error. βˆ‚L/βˆ‚y\partial L / \partial y is the gradient coming down from the next layer: it says how the loss responds to a change in the output yy. x⊀x^{\top} is the input activation, transposed, simply flipped so the dimensions line up (see matrix operations). The result βˆ‚L/βˆ‚W\partial L / \partial W says how to correct each weight.

The thing to notice is the presence of xx on the right-hand side. A weight's gradient does not depend only on what comes from above: it also depends on what the layer had received as input. Without xx, you cannot correct WW. And since xx was computed in the forward pass, it has to be kept until the backward pass reaches that layer, which for the first layer means all the way out and all the way back.

How much it weighs

Activations are the fourth item in training memory, and the only one that depends on batch size and sequence length. The other three (weights, gradients, optimizer state) are established in ZeRO: for a 7-billion-parameter model, 84 GB, of which 56 is AdamW's bookkeeping alone. That accounting is not redone here. Let us do the one that is missing.

Take that same 7-billion model: 32 layers, a hidden dimension of 4,096, a sequence of 4,096 tokens, a batch of 1. NVIDIA's paper on the subject establishes the per-layer count: with a modern attention implementation you must retain the equivalent of 34 bytes per token per hidden dimension, for every layer. That is the sum of a transformer block's intermediate results, projection inputs, normalisation outputs, the non-linearity's output, and the rest.

34⏟bytesΓ—4,096⏟tokensΓ—4,096⏟dimensionΓ—32⏟layersβ‰ˆ18Β GB\underbrace{34}_{\text{bytes}} \times \underbrace{4{,}096}_{\text{tokens}} \times \underbrace{4{,}096}_{\text{dimension}} \times \underbrace{32}_{\text{layers}} \approx 18 \text{ GB}

Eighteen gigabytes of activations, next to 14 GB of weights. Activations weigh more than the model itself, and that lands squarely in the 10-to-30 GB band quoted in ZeRO.

More importantly, this figure moves when you change a setting. A batch of 8 instead of 1: 144 GB. It is the only one of the four items that behaves that way, and that is why it gets its own technique.

The term Flash Attention removed

The same count, applied to the old naive attention implementation, gave roughly 194 bytes instead of 34, nearly six times more, or about a hundred gigabytes for the same configuration. The extra came from a single term: the large sequence-by-sequence attention matrix, which had to be stored. That term grows with the square of sequence length, which is what made long contexts impractical. Flash Attention never materialises that matrix, and so the term disappears.

The trick: throw away, then redo

Instead of keeping every activation, you keep only a few, at the checkpoints. Between two checkpoints, everything is discarded. When the backward pass reaches that segment, you start again from the nearest upstream checkpoint, redo the forward pass for that segment only to regenerate the missing activations, use them, then discard them again.

The analogy: rather than keeping every scratch sheet from a long hand calculation, you keep one intermediate result every ten steps. If you have to recheck step 37, you start from the step-30 result and redo seven steps. Far less paper, slightly more pencil.

Training Deep Nets with Sublinear Memory Cost (Chen et al., 2016)
What this technique does not do

Unlike the parallelism schemes, activation recomputation splits nothing across machines and communicates nothing. It is a purely local transformation: a single card, with or without a network, benefits in exactly the same way. It swaps one resource for another (memory for compute time) without moving anything.

That is also why it composes with everything else without interference, and why it is FSDP's obligatory companion: FSDP partitions the three fixed memory items, recomputation attacks the fourth.

Where the overhead comes from, and why to read it as an order of magnitude

The figure everyone quotes is "about 30% extra compute". Here is its real origin, in two parts.

The reasoning. A full forward pass costs one unit of work. The backward pass costs two, because it computes two things instead of one: the gradient to hand back to the previous layer, and the gradient of each weight. A training step therefore costs 1+2=31 + 2 = 3 units. Fully recomputing the activations adds one forward pass, that is one unit:

1+1+21+2=43β‰ˆ1.33\frac{1 + 1 + 2}{1 + 2} = \frac{4}{3} \approx 1.33

A third more compute. That is where both the "33%" and the "30%" come from.

The measurement. Chen and co-authors report, for a 1,000-layer residual network on ImageNet, memory brought down from 48 GB to 7 GB for 30% additional running time.

Treat this figure as an order of magnitude

The two numbers agree, but neither is a universal constant. The reasoning assumes all the cost is matrix arithmetic, which is false: normalisations and activation functions do not follow the 1-to-2 ratio. The 30% measurement is on an architecture that is not a transformer, on images, in 2016.

On a modern transformer, the overhead actually observed depends on sequence length, on the hardware, and on how much of the time the card was already spending waiting on something else. Remember "on the order of 30%", and measure on your own configuration. The rest of this page shows how to push it much lower.

Where to put the checkpoints

Placement is a balancing act: more checkpoints means more memory but less recomputation.

Chen and co-authors show that placing a checkpoint every N\sqrt{N} segments of an NN-layer network brings activation memory from proportional to NN down to proportional to N\sqrt{N}, at the cost of one extra forward pass per batch, the third computed above. For a 32-layer model that is about 6 checkpoints and activation memory divided by 32β‰ˆ5.7\sqrt{32} \approx 5.7. For an 80-layer model, a factor of 9.

The paper also shows you can go further still (down to memory proportional to log⁑N\log N) but at a compute overhead that grows with the size of the network, which stops being worthwhile in practice.

Chart titled Activation Memory Scaling vs Model Depth. On the x-axis, the layer count L from 4 to 64. On the y-axis, relative activation memory from 0 to over 60. Three curves: no checkpointing, O(L), rises in a straight line to 64; optimal spacing with k equal to root L, rises very slowly to about 10; full per-layer checkpointing with k equal to 1, rises to about 17.
The same trade-off, seen as a curve. The top line is memory without recomputation: it grows in proportion to the layer count. The two lower curves are two ways of placing checkpoints; the root-N one is the flattest, and its gap with the top line widens as the model gets deeper.Source : Michael Brenndoerfer's blog, Activation Checkpointing

In practice: one checkpoint per transformer block

The N\sqrt{N} theory is rarely applied literally. In practice you take the architecture's natural seam: one checkpoint at the entry of each transformer block. For each block you keep only the input tensor, of size batch Γ— sequence Γ— dimension, and discard everything the block computes inside. The backward pass redoes the block.

The choice is a good one because a block holds around twenty intermediate tensors for a single input: you keep one object and throw away twenty, redoing a modest and perfectly parallelisable amount of arithmetic.

Selective recomputation: don't redo everything

Recomputing a whole block is crude. Some operations occupy a lot of memory and cost almost nothing to redo; others are the reverse. The right criterion is the ratio of memory saved to compute added, and it varies enormously from one operation to the next.

Attention's softmax and its sequence-by-sequence matrix are the extreme good case: enormous in memory, negligible in compute next to the block's matrix multiplications. You recompute those. The outputs of the large matrix multiplications are the opposite case: you keep those.

Diagram of a self-attention block. On the left the input X, then a linear layer XW, then the three projections Q, K and V. Q and K go through a product, a Softmax and a Dropout, then a second product with V yields the output Y. A red dashed frame encloses Q, K, V, the product, the Softmax, the Dropout and the second product: that is the region selective recomputation is applied to.
Selective recomputation in practice: the red frame delimits the only part of the attention block that is discarded and recomputed, the part producing the sequence-by-sequence matrix and the softmax. Everything outside the frame stays stored, because it is either small or expensive to redo.Source : Reducing Activation Recomputation in Large Transformer Models paper (Korthikanti et al., NVIDIA, figure 3), via r/MachineLearning
Reducing Activation Recomputation in Large Transformer Models (Korthikanti et al., 2022)
What the paper measures

The authors combine selective recomputation with sequence parallelism and report activation memory divided by 5, while cutting the time overhead by more than 90% relative to full recomputation. On a 530-billion-parameter model trained on 2,240 A100 cards, Model FLOPs Utilization goes from 42.1% (full recomputation) to 54.2%, a 29% faster run.

That is the result worth remembering rather than the "30%": aimed well, recomputation stops being a painful trade.

What Flash Attention changes

Flash Attention already does, inside attention, exactly what this page describes: it never stores the large matrix and recomputes it tile by tile during the backward pass. So the heaviest memory item is handled before you even switch recomputation on. The two techniques stack (Flash Attention for the inside of attention, block recomputation for the rest) and it is that combination that makes very long sequences reachable.

In PyTorch

def forward(self, x):
    for block in self.transformer_blocks:
        x = torch.utils.checkpoint.checkpoint(block, x)
    return x

checkpoint(block, x) runs the block without recording its internal activations, keeps only the input x, and re-runs the block automatically when the backward pass reaches that point. The rest of the training code does not change.

When to switch it on, and when not to

Recomputation is not free and therefore not always desirable:

  • Model and batch already fit in memory: leave it off. You would pay the compute overhead for memory you have no use for.
  • Memory is the binding constraint: switch it on. That happens as soon as you want a longer sequence or a bigger batch.
  • You want a bigger batch: this is the main use case. A bigger batch can win back in throughput what recomputation cost, because the card works on larger chunks of data at a time.
Measure, do not guess

It is a setting like any other. Run one training step with and without, note peak memory and time per step, and decide. Memory management and gradient accumulation are the two other dials to weigh at the same time.

Chart of GPU memory in MiB against batch size, for an 8-billion-parameter model, with and without gradient checkpointing. Without checkpointing, the purple and orange curves stop around a batch of 16, already reaching 65,000 to 72,000 MiB. With checkpointing, the red and green curves continue to a batch of about 110 while staying below 80,000 MiB.
A real measurement on an 8-billion-parameter model. Without recomputation (upper-left curves), memory saturates at a batch of 16. With recomputation, the same card absorbs a batch nearly seven times larger. That is exactly the case where recomputation earns its keep.Source : Giles Thomas, Messing around with fine-tuning LLMs, part 9

The combinations

  • With FSDP or ZeRO: the standard, near-obligatory pairing. Those methods partition the three fixed items, recomputation attacks the fourth. Either one alone leaves a bottleneck untouched.
  • With tensor parallelism: see Megatron-LM, which is where the selective recomputation above comes from.
  • With sequence parallelism: that one splits activations across cards, recomputation reduces their total quantity. The two gains multiply, and it is exactly the combination NVIDIA's paper measures.

Reversible layers: the limiting case

Some architectures, such as RevNet and Reformer, are designed so that a layer's input can be reconstructed exactly from its output, by an inverse operation. There is then nothing to store at all: the backward pass climbs the network rebuilding activations as it goes, starting from the final output alone.

The price is a constraint on the architecture, which must be designed for invertibility from the start. It is a very different trade: instead of choosing how much to store, you give up some freedom in designing the model.

Summary

Activation recomputation handles the fourth item of training memory, the one neither FSDP nor ZeRO partitions. The backward pass needs the forward pass's activations, because a weight's gradient depends on what its layer had received as input. Rather than keep them, you discard them and redo them on demand from a checkpoint typically placed at each transformer block's entry. This moves no data between machines: it is a purely local exchange of memory for compute. The overhead reasons out to roughly a third, the backward pass costing twice the forward, but read that as an order of magnitude, and note that selective recomputation cuts it by more than 90% by redoing only attention's softmax.

Check your understanding0 / 5

1. Why does the backward pass need the activations computed during the forward pass?

2. Where does the 4/3 factor (roughly a third more compute) for full activation recomputation come from?

3. The famous figure of roughly 30 percent extra compute that gets quoted everywhere: what is its actual status?

4. During multi-card training, what does activation recomputation send over the network?

5. The model, the batch and the activations already fit comfortably in the card's memory. Should you turn on activation recomputation?