Activation Checkpointing: Memory Savings During Training
Abstract
Activation Checkpointing (gradient checkpointing) is a technique where intermediate activations are not saved in memory but recomputed during the backward pass, reducing VRAM consumption at the cost of additional computations.
Memory Problem
During training, the forward pass saves the outputs of each layer for use in backpropagation. For deep models and long sequences, this is the dominant source of memory consumption.
Mechanism
The forward pass is divided into segments. Only the inputs to the segments (checkpoints) are saved. During the backward pass, activations within a segment are recomputed.
# PyTorch
from torch.utils.checkpoint import checkpoint
def forward_segment(x):
return layer2(layer1(x))
# instead of direct call
y = checkpoint(forward_segment, x)
Diagram
flowchart LR
A[Input] --> C1[Checkpoint 1]
C1 --> C2[Checkpoint 2]
C2 --> C3[Checkpoint 3]
C3 --> L[Loss]
L -.->|backward pass| C3
C3 -.->|recompute| C2
C2 -.->|recompute| C1
Trade-offs
| Parameter | Without checkpointing | With checkpointing |
|---|---|---|
| Activation memory | O(n layers) | O(√n) |
| Computations | 1× | ~1.3× |
| Speed | Higher | Lower |
| Max batch size | Smaller | Larger |
Practice
- Used in conjunction with mixed precision and gradient accumulation.
- Allows increasing batch size with fixed VRAM.
- Implemented in PyTorch through
torch.utils.checkpoint. - Incompatible with some operations requiring saved state (e.g., dropout with fixed seed).
When to Use
When the model does not fit in memory with a given batch size. If VRAM is sufficient, checkpointing only slows down training. Related topics: distributed training, LoRA.