Gradient Accumulation › A Worked Example
Language AI HandbookAll chapters Gradient Accumulation › A Worked ExampleOne section · Sections in this chapter8 / 14 ↓
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
To make the mechanics concrete, consider a simple linear regression scenario that illustrates the mathematical equivalence between full-batch training and gradient accumulation.
Suppose you have a dataset of 8 samples and a model parameterized by a single weight , with mean squared error loss:
where:
- : the scalar model parameter
- : the batch of samples
- : the -th input-output pair
- : the batch size
The full-batch gradient over all 8 samples is:
Now split the 8 samples into micro-batches of size 2 each. For micro-batch (samples and ), the mean loss is:
The scaled gradient contribution from micro-batch (after dividing by ) is:
Summing across all 4 micro-batches to obtain the accumulated gradient:
The accumulated gradient equals the full-batch gradient exactly. This confirms that the scaling is necessary and sufficient to achieve mathematical equivalence.
The same derivation applies to any differentiable loss and any model architecture. The linearity of gradient computation means that you can always decompose a full-batch gradient into a sum of micro-batch gradients. The only requirement is that the micro-batches partition the full batch without overlap, and that each micro-batch uses the same model parameters.
What Changes When Micro-batches Are Unequal?
In some settings, the last micro-batch of an epoch may be smaller than the others, because the dataset size is not perfectly divisible by the full logical batch size. For example, if you have 1000 samples, a logical batch of 64, and micro-batch size 16, then 15 logical batches will have all four micro-batches of size 16, but the final logical batch may have only 1000 mod 64 = 40 samples, requiring some micro-batches of size 10 or fewer.
In this case, the correct approach is to weight each micro-batch by its actual size rather than using uniform scaling. The properly weighted contribution of micro-batch with samples is:
where is the total number of samples in the logical batch. This produces an unbiased estimate of the full-batch gradient even when micro-batches have different sizes.
Most training frameworks simplify this by dropping the last incomplete batch entirely, which avoids the unequal weighting problem. Whether to drop or include it is a hyperparameter choice: dropping it is simpler and slightly wastes data, while including it with proper weighting is more data-efficient but requires additional bookkeeping.