Summary
Gradient accumulation holds parameters fixed while backward calls add contributions to one update. Use the denominator of the intended objective: total examples or valid targets, not automatically the configured number of micro-batches.
Task: four equal-sized micro-batches have scalar mean gradients at the same parameter value. Reproduce their full-window mean with one optimizer update and only one micro-batch’s live activation graph. Assume the loss decomposes over targets, with no batch-coupled operation changing the forward computation.
An optimizer-update clock differs from the forward/backward clock; scheduler and momentum state must follow the intended update boundary.
The mechanism
Clear the gradient buffer before the window. Equal-size contributions divided by four are ; the buffer becomes . Consume gradient once, with no parameter changes during the four gradient evaluations.
For unequal micro-batch sizes and mean gradients , the intended mean is
Sizes with gradients give , not the batch-means average . The picture’s equal quarters are therefore a special case.
One accumulation window · K = 4
Weight contributions by the intended denominator and advance parameters only at the update boundary
Reference drawing
One accumulation window · K = 4
Weight contributions by the intended denominator and advance parameters only at the update boundary
Derivation
A complete weighted step
Here each input is a batch-by-one tensor; targets are one-dimensional int64 class IDs zero or one, with no ignored entries. The model returns batch-by-two logits. Summed cross-entropy divided by the whole window count makes every target contribute equally.
import torch
from torch.nn import functional
def accumulated_step(model, optimizer, batches):
batches = tuple(batches)
count = sum(targets.numel() for inputs, targets in batches)
if count == 0:
raise ValueError('window must contain targets')
optimizer.zero_grad(set_to_none=True)
for inputs, targets in batches:
loss = functional.cross_entropy(model(inputs), targets, reduction='sum')
(loss / count).backward()
optimizer.step()
model = torch.nn.Linear(1, 2, bias=False)
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
batches = [(torch.tensor([[1.], [2.]]), torch.tensor([0, 1])), (torch.tensor([[3.]]), torch.tensor([1]))]
accumulated_step(model, optimizer, batches)
Materializing the window retains its input batches, not all their activation graphs. Each call clears before accumulating; the next call must not reuse the previous gradient buffer.
Change the window length
New task: three loader batches arrive with accumulation_steps = 2.
Replace the per-batch driver below; retain the function, model, optimizer, and dataloader.
from itertools import islice
iterator = iter(dataloader)
while True:
window = list(islice(iterator, accumulation_steps))
if not window:
break
accumulated_step(model, optimizer, window)
Check: two batches form the first update; the final batch forms a second, using its own actual count. Its loss is not divided by two merely because the configured window length is two. Use when: the loader length is not divisible by the accumulation setting.
Change which targets count
New task: ignore targets labeled -100.
Inside the function, replace its count and loss statements with these two nonadjacent replacements:
count = sum(int((targets != -100).sum()) for inputs, targets in batches)
loss = functional.cross_entropy(model(inputs), targets, ignore_index=-100, reduction='sum')
Retain empty-count rejection, zeroing, normalization, backward, and the final step. Check: three valid targets in one micro-batch and one in another receive weights and . An all-ignored window raises before stepping. Use when: padding or supervision masks alter loss-bearing counts.
Failure: BatchNorm uses different statistics on separate forwards than on their concatenation. Correct denominators cannot restore that lost equivalence. SyncBatchNorm synchronizes concurrent ranks, not earlier serial micro-batches.
Reconstruct: eight devices each process four micro-batches of sixteen examples. Is the effective batch necessarily ?
Answer
The arithmetic gives , but verify each example contributes once to one synchronized mean and update. Specify rank reductions, tails, and batch-coupled operations before claiming equivalence.
Cost model
Activation residency can stay near one micro-batch when graphs are released after backward. Optimizer state and gradient buffers remain; retaining computation graphs defeats the intended activation saving. Serial micro-batches require multiple forwards/backwards per update and may underutilize the device. Measure throughput rather than assuming accumulation is faster or cheaper than distributed execution.
Combined with other techniques
DDP no_sync() encloses forward and backward on intermediate micro-batches when that API is supported.
One final synchronization does not automatically normalize unequal valid counts across ranks; account for the reduction’s averaging factor.
FSDP synchronization and memory behavior depend on its API and sharding strategy.
Under AMP, hold loss scale constant across the window, then unscale and clip the completed gradient once. Advance optimizer and scheduler at their intended successful-update boundaries. Checkpointing trades recomputation for retained activations independently of accumulation.
Common pitfalls
Stepping per micro-batch changes parameter and optimizer trajectories. A gradient scaled by is not universally equivalent to scaling learning rate by , particularly with Adam or clipping. Dropout masks, batch coupling, precision, and reduction order can also prevent exact full-batch equality.
The original sketches below are intentionally incomplete contrasts, not runnable classifier references.
They assume model(batch) returns a loss; the second also assumes equal counts and drops an unfinished tail.
Both omit an explicit initial buffer clear.
for batch in dataloader:
loss = model(batch)
loss.backward()
optimizer.step()
optimizer.zero_grad()
for step, batch in enumerate(dataloader):
loss = model(batch) / accumulation_steps # average over K micro-batches
loss.backward() # gradients accumulate in .grad
if (step + 1) % accumulation_steps == 0:
optimizer.step()
optimizer.zero_grad()
Related
- Activation checkpointing. Independent memory reduction.
- FSDP and ZeRO. Distributed memory reduction.
- Mixed precision training. Orthogonal memory reduction.