Topic 20 of 62 · How a model learns
Effective batch and accumulation
EasyHow does gradient accumulation emulate a larger batch size, and when does the equivalence break?
1 · Start with the intuition
Because the gradient of an average loss is the average of the per-example gradients, you do not need to fit the entire optimization batch in GPU memory at once. Gradient accumulation splits a large target batch into a sequence of smaller microbatches: for each microbatch, you run forward and backward while keeping the weights θ fixed, let the gradients add up in .grad, and call optimizer.step() and zero_grad() only after all microbatches have been processed.
2 · How the mechanism works
Mechanism step 1 of 3 · no question to answer
Run one microbatch at a time
Forward and backward one microbatch of size b_micro so activation memory stays bounded by b_micro.
Next, we will look at: Scale & accumulate into .grad. Move on when this operation makes sense.
Visualizing the behavior
One optimizer step per 4 microbatches (DDP)
IllustrativeMicrobatch A: 10 tokens, mean loss 2.0 · B: 90 tokens, mean loss 1.0
Derived3 · The governing equation
B_effective = b_micro × a_accum × D_data_parallel Equal-token microbatches: L_total = (1/a) Σₖ Lₖ ⇒ ∇θ L_total = (1/a) Σₖ ∇θ Lₖ DDP (averages gradients over W ranks): each rank backpropagates loss_sum_rank × W / N_global where N_global = valid tokens over all ranks and all accumulated microbatches
Notation: b_micro is sequences per GPU per micro-step, a_accum is the number of accumulated micro-steps per optimizer update, and D_data_parallel is the number of data-parallel replicas (excluding tensor or pipeline parallel shards).
Gradient accumulation is mathematically identical to a single large batch only when each microbatch’s gradient depends solely on its own examples and reductions are weighted properly. Two cases commonly break exact equivalence: (1) variable-length sequences, where averaging microbatch means equally gives tokens in short microbatches too much weight unless you normalize by total valid tokens across the whole effective batch; and (2) objectives that couple examples across the batch, such as contrastive learning with in-batch negatives or BatchNorm. The first case also applies across GPUs: DDP averages gradients equally over ranks, so dividing by each rank’s own token count over-weights tokens on ranks with few of them. The fix is to divide each rank’s summed loss by the global token count and multiply by the world size W, which DDP’s averaging then cancels. Forgetting no_sync() on intermediate microbatches is a different kind of mistake: the gradient is unchanged, but all-reduce runs on every micro-step instead of once on the accumulation boundary, wasting communication.
4 · Put concrete numbers on it
Worked numbers (from stated assumptions)5 · Common misconception to avoid
Thinking gradient accumulation reduces model-state memory, or that it increases the number of in-batch negatives in contrastive learning. Weights, gradients, and optimizer states stay the exact same size; only peak activation memory drops. And in contrastive learning, each microbatch builds its own B_micro × B_micro similarity matrix unless you explicitly cache or gather embeddings.
In practice · implementation & engineering rule of thumb
Normalize by the valid (non-pad) target tokens across all microbatches AND all ranks (all-reduce the count), multiply by world size because DDP averages gradients over ranks, and use model.no_sync() on intermediate microbatches to avoid redundant all-reduces.
local_tokens = sum((mb["labels"] != -100).sum() for mb in microbatches)
global_tokens = local_tokens.clone()
dist.all_reduce(global_tokens) # valid tokens over all ranks and microbatches
scale = dist.get_world_size() / global_tokens # DDP averages over ranks; W cancels that
for i, mb in enumerate(microbatches):
sync_ctx = contextlib.nullcontext() if i == len(microbatches) - 1 else model.no_sync()
with sync_ctx:
logits = model(mb["input_ids"])
loss_sum = F.cross_entropy(logits.view(-1, V), mb["labels"].view(-1), ignore_index=-100, reduction="sum")
(loss_sum * scale).backward()
optimizer.step(); optimizer.zero_grad(set_to_none=True)Go one level deeper
Follow-ups that often come after a correct first answer.
- Batch size changes the optimization
- Accumulation raises the effective batch, so a learning rate and warmup tuned for one batch size may not transfer. The gradient-noise-scale analysis suggests a critical batch size beyond which larger batches give diminishing returns per example.
- BatchNorm breaks exact equivalence
- BatchNorm computes statistics per microbatch, so 4 × 8 accumulated is not identical to a batch of 32. LayerNorm and RMSNorm work per token and have no such issue. Dropout masks and RNG streams also differ, which matters only for bitwise reproducibility.
6 · Self-check & interview synthesis
Explain it in your own words first
Before revealing the reference answer, try answering the opening question aloud in four beats: what it is → how the math works → what trade-off it makes → a concrete number or failure mode.
Follow-up question interviewers often ask next
MediumIn DistributedDataParallel (DDP), what happens if you run 8 accumulation steps without wrapping the first 7 in model.no_sync()?
Show follow-up reasoning
The final gradient at step 8 is still mathematically correct, but DDP triggers an all-reduce collective on every backward() call—so you pay for 8 network synchronizations per optimizer step instead of 1, losing most of the throughput advantage of accumulation.