Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.Tasting the soup in spoonfuls
To judge a big pot of soup you don’t need to drink it in one go: you can taste several spoonfuls, keep a running tally, and decide after the last one. Gradient accumulation works the same way: when a big batch doesn’t fit in GPU memory, process it in small pieces, add up what each piece says about how to change the model, and make one change at the end. The only care needed is to add the pieces up fairly.
Accumulation lets a single workstation GPU train with the batch sizes of a cluster recipe, and lets cluster jobs keep their global batch when they move to fewer or smaller GPUs. Getting its normalization wrong silently changes the objective: models of variable-length data (text, telemetry, trajectories) are the usual victims.
- 1. Gradient accumulation is used when…
- 2. How often does the optimizer step with 8 accumulation steps?
- 3. In the demo, when do the two averaging methods agree?
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.The loop
accum = 8
opt.zero_grad()
for i, (x, y) in enumerate(loader): # loader yields micro-batches
ctx = model.no_sync() if (i + 1) % accum and ddp else contextlib.nullcontext()
with ctx: # DDP: skip the all-reduce on intermediate micro-batches
loss = loss_fn(model(x), y) / accum # scale so the accumulated gradient is a mean
loss.backward() # gradients ADD into .grad
if (i + 1) % accum == 0:
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) # clip the accumulated gradient, not micro ones
opt.step(); scheduler.step(); opt.zero_grad() # one optimizer (and scheduler) step per windowEffective (global) batch = micro-batch × accumulation steps × number of GPUs. Lightning: Trainer(accumulate_grad_batches=8); Hugging Face: gradient_accumulation_steps=8.
- 1. Global batch for micro-batch 8, accumulation 16, 4 GPUs?
- 2. Why divide the loss by accum?
- 3. When should gradient clipping happen?
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 30 minUndergraduate students and practising engineers.When accumulation is exact, and when it isn’t
With a mean loss over equal-size micro-batches, (1/k)Σ_j ∇L_j = ∇L of the concatenated batch, so k accumulation steps followed by one optimizer step reproduce large-batch training exactly. Differences arise from:
- Missing 1/k: the gradient (and hence the effective learning rate) is k times larger.
- Counting: learning-rate schedules, warmup and logging must count optimizer steps, not micro-batches.
- BatchNorm sees micro-batch statistics, not large-batch ones.
- Variable lengths: if each micro-batch’s loss is the mean over its tokens, averaging those means weights a token in a micro-batch of T tokens by 1/(kT): tokens in short micro-batches count more. The token-level objective needs Σ(token losses) / (total tokens in the window), which requires knowing the window’s token count up front (count it first, or all-reduce it across GPUs).
- 1. Micro-batches with 12 and 350 tokens, mean of means: how many times more does a token of the short one count?
- 2. Accumulation reproduces large-batch training exactly if…
- 3. model.no_sync() in DDP…
Level 3: Advanced
★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.Normalizing token losses correctly
- Within a window: sum token losses per micro-batch and divide by the window’s total token count (counted before the backward passes, e.g. from the attention masks).
- Across GPUs: each GPU sees different token counts; all-reduce the count (or normalize by a fixed number of tokens per step) so every token in the global batch has the same weight.
- Across steps: SGD weights optimizer steps equally, so windows with fewer tokens still give their tokens a bit more weight; normalizing by a constant expected token count per step removes that too.
- Length bucketing (grouping similar lengths to reduce padding) makes the mean-of-means bias much worse, because micro-batches become all-short or all-long.
This exact bug affected widely used fine-tuning libraries until it was fixed in 2024; the symptom was a training loss that depended on the accumulation setting.
- 1. Why does length bucketing amplify the mean-of-means bias?
- 2. For exact token weighting across 64 GPUs you need…
- 3. A loss curve that changes when you change accumulation steps (same global batch) suggests…
Level 4: Expert
★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.Accumulation, measured
Exercise 1. Four micro-batches of 16 give exactly the gradient of one batch of 64, and 200 training steps with accumulation reproduce 200 large-batch steps; without the 1/k scaling the gradient is k times too large, and with 8 accumulation steps training diverges at a learning rate (0.15) that is perfectly stable with the scaling. A window with a 12-token micro-batch and a 350-token micro-batch makes the mean-of-means gradient 19% wrong, while normalizing by the window’s token count is exact; with equal token counts the bug is invisible.
Exercise 2: how far the bug moves the model. 1600 sequences whose longer half follows slightly different true weights (a different “domain”); 4 sequences per micro-batch, 8 micro-batches per optimizer step. The converged weights of each normalization (closed-form weighted least squares, the point SGD converges to) compared with the true token-level solution, as a fraction of the gap between the two domains’ weights:
| Lengths, grouping | mean of means | token-normalized per window |
|---|---|---|
| all equal (40 tokens) | 0% | 0% |
| uniform 1–79, random | 5.5% | 0.7% |
| uniform 1–79, bucketed by length | 23.7% | 2.1% |
| lognormal (median 30), random | 8.7% | 1.2% |
| lognormal, bucketed by length | 31.3% | 4.6% |
With length bucketing, the buggy normalization moves the trained model almost a third of the way towards the short-sequence data. Per-window token normalization removes most of the bias; what remains comes from weighting optimizer steps equally across windows with different token counts, removed by normalizing with a global constant.
Accumulation in AI, robotics and aerospace
- Single-GPU fine-tuning of large models with recipe batch sizes.
- Variable-length data: language, telemetry sequences, trajectories and point clouds, where token- or point-level normalization matters.
- Memory-bound 3D and high-resolution models whose micro-batch is 1 or 2 samples.
- Reproducibility: keeping the global batch constant when a job moves between clusters with different GPU counts.
References
- PyTorch documentation and recipes: torch.nn.parallel.DistributedDataParallel.no_sync; Lightning accumulate_grad_batches.
- P. Goyal et al. (2017). “Accurate, large minibatch SGD: training ImageNet in 1 hour.” arXiv:1706.02677 (batch-size equivalences).
- Hugging Face (2024). “Fixing gradient accumulation” (blog post on token-level loss normalization in transformers).
- M. Ott et al. (2018). “Scaling neural machine translation.” WMT (large effective batches via accumulation).
- S. McCandlish et al. (2018). “An empirical model of large-batch training.” arXiv:1812.06162.