Grimoire
Sheet
pathtraining/memory
difficultyintermediate
timeO(√L)
memoryO(√L)
described2016
revised3w ago

Gradient Checkpointing

Store activations at segment boundaries only, and recompute the interior during the backward pass. With √L segments both memory and recompute land at O(√L).

Theory

Backpropagation through LL layers ordinarily keeps every intermediate activation alive until its gradient is consumed, giving O(L)O(L) memory. Checkpointing keeps only every ss-th activation and re-runs the forward pass within a segment when the backward pass reaches it.

M(s)=Ls+ss=L,    M(s)=2LM(s) = \frac{L}{s} + s \quad\Longrightarrow\quad s^{*} = \sqrt{L}, \;\; M(s^{*}) = 2\sqrt{L}
eq. 1 — boundaries stored plus peak interior

The cost is one extra forward pass over the checkpointed region: about a third more compute for a transformer, since a forward pass is roughly half the cost of forward-plus-backward.

Implementation
python · torch ≥ 2.1
import torch
from torch.utils.checkpoint import checkpoint
from torch import Tensor, nn


class CheckpointedStack(nn.Module):
    def __init__(self, layers: list[nn.Module], every: int = 4):
        super().__init__()
        self.layers = nn.ModuleList(layers)
        self.every = every

    def forward(self, x: Tensor) -> Tensor:
        for i, layer in enumerate(self.layers):
            if self.training and i % self.every == 0:
                # use_reentrant=False replays RNG state correctly
                x = checkpoint(layer, x, use_reentrant=False)
            else:
                x = layer(x)
        return x

Leave use_reentrant at False. The reentrant implementation does not compose with anything that inspects the graph, silently drops gradients for inputs that do not require grad, and mishandles RNG in exactly the way described above.

Activation mem
−72%
Step time
+31%
Max batch
3.4×
7B model, 4096 context, A100 80GB, every=1
Related
References
[1]Chen et al. — Training Deep Nets with Sublinear Memory Cost (2016)arXiv:1604.06174
[2]Korthikanti et al. — Reducing Activation Recomputation in Large Transformers (2022)arXiv:2205.05198