Topic 3 of 6 · 5 min read
Gradient accumulation and activation checkpointing
Goal: Configure accumulation and checkpointing to reach a target effective batch size within a stated memory limit.
Gradient accumulation and activation checkpointing both spend extra time to save memory: one lets you simulate a big batch, the other shrinks the activation bill.
Check yourself · 1 of 3
You train on 2 GPUs with a micro-batch of 4 and 8 accumulation steps. What is the effective batch size?
Why it matters
Many recipes call for an effective batch of 64 or 128 sequences, and a single GPU may hold only 4 at a time. These two techniques close that gap without a bigger card.
Gradient accumulation
Run several small micro-batches, add up their gradients, and take one optimizer step. The effective batch is:
effective batch = micro-batch x accumulation steps x number of GPUs
With a micro-batch of 4, 8 accumulation steps and 2 GPUs, the effective batch is 64. Memory depends on the micro-batch only. The cost is time per update, not memory. Divide the loss by the number of accumulation steps, or the gradients come out too large.
accum = 8
for i, batch in enumerate(loader):
loss = model(**batch).loss / accum
loss.backward()
if (i + 1) % accum == 0:
optimizer.step()
optimizer.zero_grad()
Activation checkpointing
Normally the forward pass stores every layer's activations for the backward pass. With checkpointing, only some layers keep their activations, and the rest are recomputed when needed. This often cuts activation memory sharply for about a third more compute, since one extra forward pass is added. In Hugging Face Transformers it is one call: model.gradient_checkpointing_enable().
How to choose
- Pick the effective batch from your recipe.
- Raise the micro-batch until you hit the memory limit.
- If even a micro-batch of 1 or 2 fails, turn on checkpointing, then raise the micro-batch again.
- Set accumulation to reach the target. Log the effective batch so it is on record.
Before and after
Weak: "Out of memory at batch 32, so I will use batch 2 and keep the learning rate." The effective batch is now 2 and the run behaves differently. Fixed: micro-batch 2 with 16 accumulation steps keeps the effective batch at 32.
What goes wrong
- Forgetting to scale the loss, which inflates gradients by the number of steps.
- Counting steps wrongly. The scheduler and logging should count optimizer steps, not micro-batches.
- Checkpointing with the wrong cache setting. Some model code needs
use_cache=Falseduring training, or it warns and ignores checkpointing.
Examples
Reaching an effective batch of 64
A 7B LoRA run on one 24 GB GPU fits a micro-batch of 2 with checkpointing on. Target effective batch is 64, so accumulation steps are 64 / (2 x 1) = 32. One optimizer update now takes 32 forward and backward passes, and the log should say effective_batch=64.
The scheduler bug
A config sets 1,000 warmup steps, but the scheduler is called every micro-batch with 8 accumulation steps. Warmup finishes after 125 optimizer updates and the learning rate peaks too early. Call the scheduler only after optimizer.step().
Key points
- Effective batch size equals micro-batch times accumulation steps times the number of GPUs.
- Accumulation saves no time. It lets a small micro-batch behave like a large batch at the cost of more passes per update.
- Activation checkpointing recomputes activations in the backward pass, trading roughly one extra forward pass for lower memory.
- Divide the loss by the accumulation steps so gradient size matches the large-batch run.
- Step the learning rate scheduler per optimizer step, not per micro-batch.
Common mistakes
- Reducing the batch to fit memory without compensating with accumulation, which changes the training recipe.
- Leaving the loss unscaled during accumulation, so gradients are several times too large.
- Enabling checkpointing everywhere when the memory problem is only the optimizer state, which wastes time.
- Mixing up micro-batch and effective batch in logs and comparing runs unfairly.
Check yourself · 2 of 3
What does activation checkpointing trade away to save memory?
Check yourself · 3 of 3
Why divide the loss by the number of accumulation steps?
Practice items, not counted towards your mastery.
Start here
- The Ultra-Scale Playbook: Training LLMs on GPU Clusters (opens in a new tab)BookFree
An interactive guide to data, tensor, pipeline and ZeRO parallelism with measured trade-offs.
- Getting Started with Fully Sharded Data Parallel (FSDP) (opens in a new tab)DocsFree
A runnable FSDP setup that shows how parameters, gradients and optimizer state are sharded.
- ZeRO: Memory Optimizations Toward Training Trillion Parameter Models (opens in a new tab)PaperFree
Breaks down the bytes per parameter for weights, gradients and Adam states, and how sharding removes the copies.
More for this topic
- torch.utils.checkpoint (opens in a new tab)DocsFree
The API for activation checkpointing, with its trade-offs and caveats.
- Training Deep Nets with Sublinear Memory Cost (opens in a new tab)PaperFree
The paper behind recomputing activations to trade extra compute for lower memory.