Skip to content
mlmentorship

Gradient accumulation

Hold parameters fixed, weight gradients by examples or valid tokens, flush partial windows, and distinguish accumulation from changing optimizer or batch statistics.

Published · 10 min read ·Role-specific ·Advanced

Visual quick review

Distinguish the state that changes after every micro-batch (the gradient buffer) from the parameters that change only once after K micro-batches.

One accumulation window · K = 4

Gradient and parameter state across four accumulated micro-batches

Gradient and parameter state across four accumulated micro-batches Four numbered micro-batches run from left to right using the same parameter value theta t. Each backward pass adds one quarter of its gradient to the gradient buffer, which progresses from g1 over 4 to the sum of g1 through g4 over 4. A vertical boundary follows the fourth pass. Only then does optimizer step change the parameters from theta t to theta t plus 1, after which zero grad clears the buffer. FORWARD + BACKWARD ON FOUR EQUAL-SIZED MICRO-BATCHES 1 · micro-batch B1loss / 4, then backward 2 · micro-batch B2loss / 4, then backward 3 · micro-batch B3loss / 4, then backward 4 · micro-batch B4loss / 4, then backward .grad after backwardg1 / 4 .grad after backward(g1 + g2) / 4 .grad after backward(g1 + g2 + g3) / 4 window mean gradient(g1 + g2 + g3 + g4) / 4 BOUNDARY optimizer.step()consume average once PARAMETER STATE SEEN BY EACH FORWARD PASS parameters θt parameters θt parameters θt parameters θt parameters θt+1 no optimizer step · parameters stay fixed zero_grad() starts the window zero_grad() clears .grad for the next window effective batch = 4 micro-batches · parameter updates = 1
Read it this way: the gradient buffer changes after each backward call; every forward still uses the same parameters. Only the completed mean crosses the optimizer boundary. Clear the buffer when beginning the next window. Four equal-sized micro-batches justify the displayed quarters; unequal sizes require target-count weighting.
Check: After the third backward pass, what has changed? What still equals the initial parameter state?
Full explanation 10 min read
Reading depth

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

Weight contributions by the intended denominator and advance parameters only at the update boundaryHold parameters fixed while each microbatch contributes its weighted gradient. Equal sizes yield mean five, not sum twenty. Unequal sizes require example or valid-target weights; this window yields 3.5, not five. Flush partial windows using actual counts and clear the buffer. Finish synchronization and unscaling before clipping and stepping once. Advance optimizer and scheduler on their intended update clock. Batch-coupled operations can break large-batch equivalence.Four backward calls; one intendedmean and updateToy equal-sized microbatches; clearthe buffer firstMeangradientAddedBuffer2v00.50.54v011.56v01.538v025Consume mean five once; optimizer andscheduler follow the intended updateclock.v1Unequal counts: three examples atgradient two; one at gradient eightCount-weighted mean 3.5; averagingthe two batch means gives the wrongfive.A partial window uses its actualexample or valid-target count, notthe configured window length.Finish synchronization and unscaleonce before clipping. Step once, thenclear the accumulated buffer.One live activation graph can bereleased per backward call.Batch-coupled forward statistics neednot match a larger batch.
Read it this way: Hold parameters fixed while each microbatch contributes its weighted gradient. Equal sizes yield mean five, not sum twenty. Unequal sizes require example or valid-target weights; this window yields 3.5, not five. Flush partial windows using actual counts and clear the buffer. Finish synchronization and unscaling before clipping and stepping once. Advance optimizer and scheduler on their intended update clock. Batch-coupled operations can break large-batch equivalence. Does every microbatch use v0?
Reference drawing

One accumulation window · K = 4

Weight contributions by the intended denominator and advance parameters only at the update boundary

Weight contributions by the intended denominator and advance parameters only at the update boundaryHold parameters fixed while each microbatch contributes its weighted gradient. Equal sizes yield mean five, not sum twenty. Unequal sizes require example or valid-target weights; this window yields 3.5, not five. Flush partial windows using actual counts and clear the buffer. Finish synchronization and unscaling before clipping and stepping once. Advance optimizer and scheduler on their intended update clock. Batch-coupled operations can break large-batch equivalence.Four backward calls; one intendedmean and updateToy equal-sized microbatches; clearthe buffer firstMeangradientAddedBuffer2v00.50.54v011.56v01.538v025Consume mean five once; optimizer andscheduler follow the intended updateclock.v1Unequal counts: three examples atgradient two; one at gradient eightCount-weighted mean 3.5; averagingthe two batch means gives the wrongfive.A partial window uses its actualexample or valid-target count, notthe configured window length.Finish synchronization and unscaleonce before clipping. Step once, thenclear the accumulated buffer.One live activation graph can bereleased per backward call.Batch-coupled forward statistics neednot match a larger batch.
Derivation
Gradient and parameter state across four accumulated micro-batches Four numbered micro-batches run from left to right using the same parameter value theta t. Each backward pass adds one quarter of its gradient to the gradient buffer, which progresses from g1 over 4 to the sum of g1 through g4 over 4. A vertical boundary follows the fourth pass. Only then does optimizer step change the parameters from theta t to theta t plus 1, after which zero grad clears the buffer. FORWARD + BACKWARD ON FOUR EQUAL-SIZED MICRO-BATCHES 1 · micro-batch B1loss / 4, then backward 2 · micro-batch B2loss / 4, then backward 3 · micro-batch B3loss / 4, then backward 4 · micro-batch B4loss / 4, then backward .grad after backwardg1 / 4 .grad after backward(g1 + g2) / 4 .grad after backward(g1 + g2 + g3) / 4 window mean gradient(g1 + g2 + g3 + g4) / 4 BOUNDARY optimizer.step()consume average once PARAMETER STATE SEEN BY EACH FORWARD PASS parameters θt parameters θt parameters θt parameters θt parameters θt+1 no optimizer step · parameters stay fixed zero_grad() starts the window zero_grad() clears .grad for the next window effective batch = 4 micro-batches · parameter updates = 1
Read it this way: the gradient buffer changes after each backward call; every forward still uses the same parameters. Only the completed mean crosses the optimizer boundary. Clear the buffer when beginning the next window. Four equal-sized micro-batches justify the displayed quarters; unequal sizes require target-count weighting.
Check: After the third backward pass, what has changed? What still equals the initial parameter state?
Read it this way: Hold parameters fixed while each microbatch contributes its weighted gradient. Equal sizes yield mean five, not sum twenty. Unequal sizes require example or valid-target weights; this window yields 3.5, not five. Flush partial windows using actual counts and clear the buffer. Finish synchronization and unscaling before clipping and stepping once. Advance optimizer and scheduler on their intended update clock. Batch-coupled operations can break large-batch equivalence. Does every microbatch use v0?

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()