Deep LearningDeep Learning Comparison Series
Activation Checkpointing vs Gradient Accumulation
Question 315 of 316 · Updated
On this page
- 1. The core difference
- 2. Side-by-side comparison
- 3. Numerical example
- 4. Gradient accumulation: scale the loss correctly
- 5. Activation checkpointing: recompute selected regions
- 6. Memory and compute trade-offs
- 7. Are the results identical to one large batch?
- 8. Can both techniques be combined?
- 9. Which technique should you choose?
- 10. Common implementation mistakes
- Key takeaway
- Research and technical references
Activation checkpointing reduces memory by discarding selected forward activations and recomputing them during backpropagation. Gradient accumulation reduces memory pressure from a large batch by processing smaller microbatches and adding their gradients before one optimizer update. Both help fit training into limited GPU memory, but solve different bottlenecks.
1. The core difference#
Activation checkpointing saves selected activation boundaries and recomputes missing intermediate tensors during backward. Its primary target is saved activation memory within a model's forward/backward graph. It trades extra forward computation for lower activation storage. It does not inherently change physical batch size or optimizer-update frequency.
Gradient accumulation splits a large batch into smaller microbatches. It computes each microbatch's gradients, adds them to existing gradient buffers, and updates weights only after the accumulation window. Its primary target is per-step memory pressure caused by processing too many examples at once. It increases effective batch size without holding all examples' activations simultaneously.
2. Side-by-side comparison#
| Aspect | Activation checkpointing | Gradient accumulation |
|---|---|---|
| Main idea | Save fewer activations; recompute missing ones | Process smaller microbatches; sum gradients |
| Memory target | Intermediate activation storage | Activations for a large physical batch |
| What changes | Forward intermediates retained for backward | Examples processed per microbatch |
| Backward pass | Recomputes selected forward regions | Runs backward for each microbatch |
| Optimizer updates | Normally unchanged | Delayed until accumulation completes |
| Extra cost | Repeated forward computation | Microbatch-loop overhead and possibly lower utilization |
| Effective batch size | No direct change | Microbatch size × accumulation steps |
| Parameters and optimizer states | Not directly reduced | Not directly reduced |
3. Numerical example#
Suppose a model is trained with a target batch of 64 examples, but the GPU runs out of memory.
Gradient accumulation: Use a physical microbatch of 16 and four accumulation steps. The effective batch is 16 × 4 = 64. Process four microbatches, run backward on each, accumulate gradients, then perform one optimizer update. This reduces the number of examples whose activations are live for any one microbatch's forward/backward pass.
Activation checkpointing: Keep the physical batch at 64 if it otherwise fits. Partition selected model blocks into checkpointed regions, retain boundary tensors, discard some internal activations, and recompute those intermediates during backward. This reduces activation storage inside the model graph. It does not split the batch or create four optimizer accumulation steps.
Neither method guarantees that batch 64 will fit. Parameters, optimizer states, temporary workspaces, attention kernels, sequence length and allocator overhead also contribute to peak GPU memory.
4. Gradient accumulation: scale the loss correctly#
For a target batch divided into K equal microbatches, a common mean-loss implementation scales each microbatch loss by 1/K:
PYTHONoptimizer.zero_grad(set_to_none=True) for x_micro, y_micro in microbatches: loss = criterion(model(x_micro), y_micro) (loss / accumulation_steps).backward() optimizer.step()
For unequal microbatch sizes, weight each mean loss by its share of examples, or accumulate summed losses and normalize by the total example count. Do not blindly divide by the number of microbatches when their sizes differ. Do not call zero_grad after every microbatch: that erases accumulated gradients.
5. Activation checkpointing: recompute selected regions#
The initial forward retains selected boundaries. During backward, the framework re-executes parts of the forward function to regenerate tensors needed for gradient computation.
PYTHONimport torch from torch.utils.checkpoint import checkpoint class BlockStack(torch.nn.Module): def __init__(self, blocks): super().__init__() self.blocks = torch.nn.ModuleList(blocks) def forward(self, x): for block in self.blocks: x = checkpoint(block, x, use_reentrant=False) return x
This is an illustrative pattern for compatible modules. In real systems, checkpoint memory-heavy regions, preserve consistent random behavior for stochastic operations, and compare results with ordinary backpropagation. Current PyTorch guidance recommends explicitly using use_reentrant=False.
6. Memory and compute trade-offs#
Checkpointing reduces forward activation data retained for backward and recomputes selected operations. It can increase step time; overhead depends on checkpoint placement, operator cost and recomputation strategy. It does not directly shrink parameter, gradient or optimizer-state storage.
Gradient accumulation limits the per-microbatch activation footprint by processing fewer examples at once. It keeps gradient buffers alive across microbatches until the update and requires multiple sequential forward/backward passes per optimizer update. It does not reduce parameter or optimizer-state memory, and accumulated gradients still occupy memory.
Gradient accumulation can lower the activation peak associated with a large physical batch, but it does not reduce the activations required by one individual microbatch. Checkpointing can reduce that within-microbatch activation requirement.
7. Are the results identical to one large batch?#
Gradient accumulation can approximate the gradient from a single large batch when the same examples contribute to the update, loss reduction and microbatch weighting are correct, parameters are not updated between microbatches, and batch-dependent operations do not change the result materially.
It is not always exactly equivalent. Batch Normalization uses microbatch statistics unless handled specially; dropout can produce different random draws; and contrastive or other cross-example objectives may require examples from the full batch at once. Gradient clipping should generally be applied to the accumulated gradient at the intended update boundary, not independently to each microbatch unless that is deliberate.
Activation checkpointing is intended to preserve the same mathematical computation and gradients, subject to floating-point effects and correct handling of randomness and stateful operations during recomputation.
8. Can both techniques be combined?#
Yes. They address different parts of the memory problem. For example, use an effective batch of 64, a microbatch size of 8, and eight accumulation steps. Enable activation checkpointing for memory-heavy Transformer blocks. The model processes eight examples at a time, recomputes selected activations during each microbatch's backward pass, accumulates gradients across eight microbatches, and performs one optimizer update at the end.
This can make a previously infeasible configuration fit, but may increase wall-clock time. Benchmark the combined setup rather than assuming memory savings or throughput improvements multiply.
9. Which technique should you choose?#
Choose gradient accumulation when the model fits in memory for a small microbatch, but the desired effective batch is larger than the physical batch that fits.
Choose activation checkpointing when intermediate activations dominate peak memory, such as in deep networks, long sequences or large feature maps, and you can afford extra recomputation.
Use both when the activation footprint is still too high at the largest practical microbatch, or when you need a large effective batch and must also reduce per-microbatch activation memory.
Profile allocated and reserved GPU memory, identify whether activations or optimizer state dominate, and measure step time and throughput.
10. Common implementation mistakes#
- Clearing gradients between accumulation microbatches destroys the accumulated gradient.
- Incorrect loss scaling changes the effective gradient magnitude, especially with a short final microbatch.
- Calling optimizer.step after every microbatch defeats accumulation.
- Clipping each microbatch separately is generally not equivalent to clipping the final accumulated gradient.
- BatchNorm microbatch statistics can differ from statistics computed over one large batch.
- Checkpointing primarily targets saved activations, not parameters or optimizer states.
- Ignoring recomputation cost can turn memory savings into unacceptable throughput loss.
- Dropout and other random operations need consistent replay behavior for checkpointed computation.
- The techniques are not mutually exclusive and should be tuned independently.
Key takeaway#
Gradient accumulation changes how examples are grouped before an optimizer update; activation checkpointing changes which intermediate activations are stored versus recomputed during backpropagation. Use accumulation to reach a larger effective batch with smaller microbatches, checkpointing to reduce within-microbatch activation memory, and both when the workload needs both benefits.
Research and technical references#
- Chen et al. (2016), Training Deep Nets with Sublinear Memory Cost
- PyTorch, torch.utils.checkpoint documentation
- PyTorch, Zeroing out gradients in PyTorch
- Hugging Face, Gradient accumulation
- Sohoni et al. (2019), Low-Memory Neural Network Training: A Technical Report
Related MachinoAI lessons: What is activation checkpointing?, What is gradient accumulation?, and When should gradient accumulation be used?.
References
- 1.
- 2.PyTorch torch.utils.checkpoint documentationdocs.pytorch.org
- 3.PyTorch Zeroing out gradients in PyTorchdocs.pytorch.org
- 4.Hugging Face Gradient accumulationhuggingface.co
- 5.
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningLarge Language Models