Foundations to Frontier
Tests
C. Programming, Tools and HPC › C6 Distributed Training

Gradient Accumulation

Gradient accumulation computes the gradient of a large batch as the sum of several smaller micro-batches' gradients before taking one optimizer step, so the effective batch size no longer depends on GPU memory. It is exact for losses that are means over equal-size micro-batches, but easy to get subtly wrong: forgetting to divide by the number of micro-batches, counting scheduler steps in micro-batches, synchronizing gradients across GPUs on every micro-batch, BatchNorm statistics, and, most insidiously, averaging token-level losses per micro-batch when sequences have different lengths. In the exercises you implement accumulation, show it reproduces large-batch training exactly, and expose the variable-length normalization bug and its fix; then you measure how far the bug moves the trained model for different length distributions and for length-bucketed versus random micro-batches.

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.

Gradient accumulation with variable-length sequences
1mb2: loss 2mb3: loss 1width = share of all tokens in the accumulation windowmb1 weight per token13.67× the fair weightmb2 weight per token1.37× the fair weightmb3 weight per token0.46× the fair weight
orange: mean of micro-batch means · blue: token-level mean (every token equal)
loss as mean of means 2.000
loss over all tokens 1.293
With equal token counts the two agree. When micro-batches differ in length (and length correlates with the data, as when samplers bucket sequences by length), the averaged-means objective over-weights short micro-batches and training converges to a different model. Sum the token losses and divide by the window's (or the global, all-reduced) token count instead.
Why engineers care

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.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Gradient accumulation is used when…
  2. 2. How often does the optimizer step with 8 accumulation steps?
  3. 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 window

Effective (global) batch = micro-batch × accumulation steps × number of GPUs. Lightning: Trainer(accumulate_grad_batches=8); Hugging Face: gradient_accumulation_steps=8.

📝 Quick check (Level 1)
0/3 answered
  1. 1. Global batch for micro-batch 8, accumulation 16, 4 GPUs?
  2. 2. Why divide the loss by accum?
  3. 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).
🐍 Exercise 1: accumulation, exactly and wrongly
Accumulate gradients over micro-batches with and without the 1/k scaling and compare with the full-batch gradient and with large-batch training; for variable-length sequences compute the exact token-level gradient, the per-micro-batch mean-of-means gradient and the token-count-normalized gradient; count optimizer steps.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Micro-batches with 12 and 350 tokens, mean of means: how many times more does a token of the short one count?
  2. 2. Accumulation reproduces large-batch training exactly if…
  3. 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.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Why does length bucketing amplify the mean-of-means bias?
  2. 2. For exact token weighting across 64 GPUs you need…
  3. 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.

🐍 Exercise 2 (research): how much the normalization bug changes the model
Generate variable-length sequences whose long half follows different weights; group them into micro-batches randomly or by length and into accumulation windows; compute the token weights implied by exact, per-window token-normalized and mean-of-means losses, solve each weighted least-squares problem, and measure how far each solution moves from the exact one for several length distributions.

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

  1. PyTorch documentation and recipes: torch.nn.parallel.DistributedDataParallel.no_sync; Lightning accumulate_grad_batches.
  2. P. Goyal et al. (2017). “Accurate, large minibatch SGD: training ImageNet in 1 hour.” arXiv:1706.02677 (batch-size equivalences).
  3. Hugging Face (2024). “Fixing gradient accumulation” (blog post on token-level loss normalization in transformers).
  4. M. Ott et al. (2018). “Scaling neural machine translation.” WMT (large effective batches via accumulation).
  5. S. McCandlish et al. (2018). “An empirical model of large-batch training.” arXiv:1812.06162.