Gradient Accumulation › The Mathematical Foundation
Language AI HandbookAll chapters Gradient Accumulation › The Mathematical FoundationOne section · Sections in this chapter2 / 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
The insight behind gradient accumulation predates deep learning. It is a direct consequence of the linearity of differentiation: the gradient of a sum is the sum of the gradients, and the gradient of a mean is the mean of the gradients. This property means you can split a batch into any number of smaller chunks, compute gradients independently on each chunk, add the results together, and obtain the same answer as if you had processed the entire batch at once.
To see why this works, consider a dataset and a model with parameters . The standard training objective is to minimize the empirical loss over a batch :
where:
- : the per-sample loss for input and label
- : the number of samples in the batch
- : the model parameters
The gradient of this loss is:
Now suppose we partition into non-overlapping micro-batches of equal size . The gradient of the loss on micro-batch is:
If we compute the average of these per-micro-batch gradients:
Since the micro-batches partition and each has size :
The average of the micro-batch gradients equals the full-batch gradient exactly. This identity is not an approximation or a statistical trick. It is an algebraic consequence of the distributive property of addition over summation.
Deep learning frameworks make this easy to exploit. In PyTorch, each call to .backward() adds gradients into the parameter's .grad attribute rather than overwriting it. Gradient accumulation is simply using this additive behavior intentionally: you call .backward() multiple times without calling optimizer.zero_grad() between calls, allowing gradients to accumulate. The only thing you need to get right is the scaling factor, which ensures the accumulated sum equals the mean rather than the sum of the micro-batch gradients.