AI Logic

Distributed Training and Memory Saving

Gradient Checkpointing

Updated:

How gradient checkpointing works. Left: ordinary training, which saves the activations of all 9 layers. Middle: gradient checkpointing, which splits the network into 3 segments, saves only the activations at each segment's input, and discards the rest. Right: the backward procedure, which, starting from the top segment, recomputes the forward pass from the segment input and then back-propagates, along with the formula showing the memory becomes O(√n)

Background and overview

Gradient checkpointing is a method that reduces the memory used for training by saving only some of the activations (the outputs of each layer) computed in the forward pass and recomputing the rest during the backward pass. In exchange for a little extra computation, it allows deeper models and larger batch sizes to be trained within the same GPU memory.

In backpropagation, computing each layer's gradient uses that layer's inputs and outputs from the forward pass. Therefore, ordinary training keeps all intermediate results of the forward pass in memory until the backward pass is finished. For an nn-layer network, this memory grows in proportion to nn, and in deep models it becomes far larger than the weights.

In their 2016 paper "Training Deep Nets with Sublinear Memory Cost," Chen et al. showed a method that splits the network into segments and saves only the activations at the segment inputs. It reduces the activation memory of an nn-layer network to O(n)O(\sqrt{n}), at the cost of roughly one extra forward pass of computation per mini-batch. The underlying idea is a technique known as checkpointing in the field of automatic differentiation, which the paper brought to general neural network training.

As an analogy, instead of writing down every intermediate step of a long calculation, you note only the answers at a few breakpoints and recompute from a breakpoint when needed. You need less scratch paper (memory), at the cost of a bit more recomputation.

Theory

The procedure of the paper's Algorithm 1 (for a network whose layers form a single chain) is as follows (middle and right of the figure above).

  1. Split an nn-layer network into kk segments.
  2. In the forward pass, save only the activation at each segment's input, and discard the outputs of the layers inside a segment once they have been used.
  3. Compute the loss from the output of the last layer and start the backward pass.
  4. Starting from the top segment, do the following for each segment in turn.
    • Recompute the forward pass of that segment alone from its saved input, holding the segment's activations temporarily.
    • Use those activations to back-propagate through the segment, then discard them.
  5. When segment 1 is finished, the gradients of all layers are available.

The memory in this case is the sum of what is needed to back-propagate through one segment and what is needed to store the segment inputs. If the segments are of equal length, as in Eq. (1) of the paper,

Memory=max⁡i=1,…,k(memory for back-propagating segment i)+O(k)=O ⁣(nk)+O(k)\text{Memory} = \max_{i=1,\dots,k} \bigl(\text{memory for back-propagating segment } i\bigr) + O(k) = O\!\left(\frac{n}{k}\right) + O(k)

More segments increase the number of inputs kk, while fewer segments make each segment longer, so choosing the balance point k=nk = \sqrt{n} makes the memory O(2n)=O(n)O(2\sqrt{n}) = O(\sqrt{n}). For example, with 100 layers split every 10 layers, the saved activations drop from 100 to about 20: the 10 segment inputs plus the 10 activations of one segment.

The gradients obtained with gradient checkpointing are exactly the same as in ordinary training. Discarded activations are simply rebuilt with the same computation, so the training result does not change; only memory and time change.

How memory is traded for computation

Gradient checkpointing is a method of trading memory for computation. How much to trade can be chosen by how the network is segmented.

  • Recompute each segment only once (O(n)O(\sqrt{n})): each discarded activation is rebuilt exactly once during the backward pass, so the added computation is roughly one forward pass. The paper explains that since the backward pass takes about twice as long as the forward pass, the overall slowdown is small.
  • Discard only the results of cheap operations: in a CNN with convolution → batch normalization → activation function, keep the outputs of the expensive convolutions and discard only the outputs of the cheap batch normalization and activation functions. Memory is reduced with almost no added computation (Section 4.2 of the paper).
  • Further subdivide each segment (O(log⁡n)O(\log n)): applying the same method to the recomputation inside each segment reduces memory to O(log⁡n)O(\log n). In exchange, the forward computation grows to O(nlog⁡n)O(n \log n), and the paper itself says this would usually not be used.

For real networks whose per-layer memory varies, the paper also presents a method (Algorithm 3) that sets a memory budget BB and greedily chooses the segment boundaries. Varying BB, it searches for the segmentation that minimizes the sum of the memory for the segment inputs and the memory inside a segment.

Gradient checkpointing reduces only activation memory. It does not reduce the weights, gradients, or optimizer states. Activations grow in proportion to the batch size, input length, and number of layers, so the benefit is larger for deep models and long sequences.

Experimental results

The paper implemented the method in MXNet and measured activation memory as well as actual memory and speed on a single Titan X.

ExperimentWhat was comparedResult
ResNet, 1,000 layers, ImageNet (batch 32, 224×224)Activation memory48GB → 7GB
ResNet, varying the number of layers from 128 to 1,024How memory growsLinear in the number of layers → close to the square root of the number of layers
4-layer LSTM, long sequences (64–2,048 time steps)Activation memoryMore than 4× further reduction on top of other optimizations
ResNet and LSTMTime per batchAbout 30% longer
  • Computation-graph optimizations alone are not enough: the paper notes that optimizations such as reusing freed memory and in-place operations cut memory by a factor of 2–3, but memory still grows linearly with the number of layers, and even the largest GPU at hand could train a ResNet of only up to 200 layers.
  • Adding gradient checkpointing made it possible to train a 1,000-layer ResNet within less than 7GB of GPU memory.

There are also estimates for large language models. The ZeRO paper estimates that the activations of a 1.5B-parameter GPT-2 (sequence length 1K, batch 32) take about 60GB, which gradient checkpointing reduces to about 8GB at the cost of 33% more computation.

The roughly 30% increase in computation comes from running the forward pass once more. Compared with being able to train models that previously could not be trained for lack of memory, this is a small price.

Practical considerations

Watch out for operations that do not give the same result as the original forward pass when recomputed. Layers that use randomness, such as Dropout, may produce a different mask when recomputed. PyTorch's torch.utils.checkpoint saves the random number state by default (preserve_rng_state=True) and reproduces the same mask. Operations whose forward behavior depends on things like global variables can give different results when recomputed, making the gradients incorrect.

  • Choose the segment size. Finer segments mean more saved inputs, while coarser segments mean more memory when recomputing one segment. For example, the Megatron-LM paper places a checkpoint at every Transformer layer.
  • In PyTorch, specify use_reentrant=False. The PyTorch documentation recommends passing this argument explicitly and using use_reentrant=False. With the old approach (True), the weights inside a segment get no gradients unless at least one of the segment's inputs requires gradients.
  • Time increases. Use it when the problem is running out of memory rather than speed. If memory is sufficient, training is faster without it.

Comparison with other methods

Gradient checkpointing reduces something different from other methods for reducing training memory. Many large-model training setups combine them.

MethodWhat it reducesWhat it costsGPUs needed
Gradient checkpointingActivations saved for the backward passAbout one forward pass of computation1 or more
Mixed precision trainingBit width of weights, activations, and gradientsThe effort of loss scaling1 or more
ZeRO / FSDPWeights, gradients, and optimizer states duplicated on each GPUCommunication between GPUsMultiple
Pipeline parallelism (GPipe)Number of layers held by one GPUGPU idle timeMultiple
  • When activations dominate memory (deep models, long sequences, large batches), gradient checkpointing is the most effective. It works even with a single GPU.
  • When weights or optimizer states are large, gradient checkpointing does not help, so use ZeRO/FSDP or mixed precision training.
  • GPipe uses the same idea as gradient checkpointing (save only the segment inputs and recompute during the backward pass) within pipeline parallelism to reduce activation memory.

PyTorch example

Show code
python
import torch
import torch.nn as nn
from torch.utils.checkpoint import checkpoint, checkpoint_sequential

"""
Example of gradient checkpointing
Split a 9-layer fully connected network into 3 segments and save only the segment inputs
"""

torch.manual_seed(0)
n_layers = 9   # number of layers n
segments = 3   # number of segments k (√n)
dim = 512

layers = [nn.Sequential(nn.Linear(dim, dim), nn.ReLU(), nn.Dropout(0.1)) for _ in range(n_layers)]
model = nn.Sequential(*layers)
head = nn.Linear(dim, 10)
x = torch.randn(64, dim)
y = torch.randint(0, 10, (64,))
criterion = nn.CrossEntropyLoss()

# 1. checkpoint_sequential: split nn.Sequential into `segments` segments
#    Except for the last segment, activations inside a segment are not saved
model.train()
h = checkpoint_sequential(model, segments, x, use_reentrant=False)
loss = criterion(head(h), y)
loss.backward()  # during backward, recompute the forward pass segment by segment

# 2. checkpoint: choose the segments yourself (e.g., per Transformer block)
class Block(nn.Module):
  def __init__(self):
    super().__init__()
    self.ff = nn.Sequential(nn.Linear(dim, dim), nn.ReLU(), nn.Dropout(0.1), nn.Linear(dim, dim))
    self.norm = nn.LayerNorm(dim)

  def forward(self, h):
    return h + self.ff(self.norm(h))

class Net(nn.Module):
  def __init__(self, use_checkpoint=True):
    super().__init__()
    self.blocks = nn.ModuleList([Block() for _ in range(6)])
    self.head = nn.Linear(dim, 10)
    self.use_checkpoint = use_checkpoint

  def forward(self, h):
    for block in self.blocks:
      if self.use_checkpoint and self.training:
        # pass use_reentrant=False explicitly (recommended by PyTorch)
        # with preserve_rng_state=True (the default), the Dropout mask stays the same on recomputation
        h = checkpoint(block, h, use_reentrant=False)
      else:
        h = block(h)
    return self.head(h)

net = Net()
net.train()
loss = criterion(net(x), y)
loss.backward()

# no backward pass at inference, so checkpointing is not needed
net.eval()
with torch.no_grad():
  preds = net(x).argmax(dim=1)

FAQ

Q. Does gradient checkpointing change the training result?
A.

No. The discarded activations are simply rebuilt with the same computation, so the gradients are the same as in ordinary training. However, layers that use randomness, such as Dropout, need the random number state to be saved so that the same mask is reproduced. PyTorch's torch.utils.checkpoint does this by default.

Q. How much slower does training become?
A.

With the method that recomputes each segment once, the added computation is roughly one forward pass. In the original paper, the time per batch rose by about 30% for ResNet and LSTM. Further subdividing segments to cut memory to O(log⁡n)O(\log n) increases the computation even more.

Q. Which layers should be checkpointed?
A.

Start by making each uniform block, such as a Transformer block or a ResNet stage, one segment. When splitting nn layers into equal lengths, memory is smallest with about n\sqrt{n} segments. Keeping the outputs of compute-heavy layers such as convolutions and discarding those of cheap layers such as batch normalization and activation functions keeps the slowdown small.

References

  1. Chen, T., Xu, B., Zhang, C., & Guestrin, C. (2016). Training Deep Nets with Sublinear Memory Cost. arXiv:1604.06174.
  2. PyTorch Documentation, "torch.utils.checkpoint."