TL;DR
Gradient accumulation trains with a batch larger than memory allows. The model runs forward and backward passes on several small micro-batches, adds their gradients into a buffer, and makes one weight update once enough have been added. For models without batch-dependent layers, the update equals the one a single large batch would give. It saves memory, not computation.
Builds on: Stochastic Gradient Descent, Backpropagation · Leads to: Linear Scaling Rule, Critical Batch Size
Where it's used
Fine-tuning a language model on one GPU. A 24 GB graphics card can hold the weights and the stored activations of only a few long sequences at a time. A typical setup runs 2 sequences per pass, accumulates 16 passes, and updates the weights as if the batch held 32 sequences. The numbers are illustrative, chosen to show the arithmetic.
Reproducing a large-batch recipe on a small machine. Suppose a recipe trains an image model with batch 1,024 across 8 GPUs of 128 examples each. A lab with one GPU that fits 128 examples at a time can match the batch by accumulating 8 passes. Each update then takes about eight times as long as on the 8-GPU setup, but the training run follows the same path.
Multi-machine training with less network traffic. When several machines share gradients, each synchronisation sends a full set of gradient numbers over the network. Accumulating locally over several micro-batches before synchronising sends the gradients once per effective batch instead of once per micro-batch. Some data-parallel frameworks offer a context that skips synchronisation during the local passes.
How it works
Ordinary training does one thing per update: take a batch, run a forward and backward pass, and change the weights. Gradient accumulation splits that work. Here is one tiny instance traced from start to finish.
Setup: a single weight , a learning rate of 0.1, and four examples whose gradients for are 1, 3, 2 and 6. Micro-batches hold two examples, so each update takes passes.
- Start with an empty buffer. Set and the gradient buffer to 0. Check: the buffer holds nothing yet.
- Run the first micro-batch. Its examples have gradients 1 and 3, so their average is 2. Divide that average by , which gives 1, and add it to the buffer: the buffer is now 1. Check: the buffer holds half the micro-batch average, not the whole of it.
- Run the second micro-batch. Its examples have gradients 2 and 6, average 4. Divide by 2 to get 2 and add: the buffer is . Check: 3 is the average of all four examples, since .
- Update once. The weight moves by the learning rate times the buffer: . Check: there is one update, and it came after both passes.
- Empty the buffer. Set it back to 0 so the next cycle starts clean. Check: the four examples must not be counted again.
- Compare with one big batch. Put all four examples in one batch. The average gradient is 3, so the update is . Check: both routes end at the same weight.
This trick has a name: gradient accumulation. The loop is shown below.
flowchart LR A[Clear the buffer] --> B[Forward and backward pass on one micro-batch] B --> C[Add its gradient divided by N to the buffer] C -->|fewer than N passes so far| B C -->|N passes done| D[One weight update] D --> A
The math
Split an effective batch of examples into micro-batches , each with examples. Gradient accumulation builds the average gradient over the whole effective batch one micro-batch at a time, then applies one update with it:
where is the average gradient over micro-batch , holds the parameters and is the learning rate.
Step 1 in symbols: a micro-batch gradient
Let be the average loss over micro-batch , and the loss on a single example :
The symbol is the gradient with respect to the parameters. A forward and backward pass on micro-batch produces .
Step 2 in symbols: scale, then add
Before its backward pass, each micro-batch loss is divided by . Because the gradient of a scaled function is the scaled gradient,
The buffer adds these terms. After passes it holds .
Step 3 in symbols: one update
After the th pass the parameters move by , and the buffer is reset to zero. In the walkthrough, and , so and .
Step 4 in symbols: why it matches the big batch
If the micro-batches split the effective batch, every example appears exactly once:
The right-hand side is the average gradient of the full batch of examples. The equality needs each example's gradient to be independent of the other examples in the batch. The common mistakes section shows where that fails.
Worked examples
One weight, learning rate 0.5, and two micro-batches of one example each. The example gradients are 4 and 2, so .
- Divide each gradient by : and .
- Add them into the buffer: .
- Update the weight: .
- Check against one batch of both examples: the average gradient is , so the update is also .
- Interpretation: with one example per pass, accumulation gives exactly the update of a batch of two, and the update uses both examples.
A training set has 25,600 examples. The target batch is 256, but memory fits only 64 examples per pass.
- Passes per update: .
- Updates per epoch: .
- Passes per epoch: . This matches , since every example is still processed once per epoch.
- Each loss is divided by 4 before its backward pass, so after 4 passes the buffer holds the average gradient over 256 examples.
- Interpretation: the number of updates matches the 256-example run, so the training trajectory is the same in principle. The work per epoch is also the same, but it is spread over four times as many passes, each smaller.
A team fine-tunes a language model with a target of 64 sequences per update. The GPU fits 4 sequences per pass. The numbers are invented for illustration.
- Passes per update: .
- Each pass divides its loss by 16, and the buffer collects 16 passes.
- The learning rate tuned for batch 64 stays the same, because the effective batch is unchanged.
- Each update therefore costs 16 forward and backward passes of 4 sequences each, plus one optimiser step.
- Interpretation: the optimiser sees the same update as the 64-sequence run, but the memory needed is that of 4 sequences. The price is 16 passes for every update.
Try it: the team switches to 8 sequences per pass, still with an effective batch of 64. How many passes per update, and does the learning rate change? Answer: passes per update. The effective batch is still 64, so the learning rate stays the same.
Common mistakes and tradeoffs
It is tempting to think the micro-batch losses can simply be added. In fact each one must be divided by , because each is already an average over its micro-batch. Without the division, the buffer holds times the average gradient, so the update is times too large, the same as multiplying the learning rate by .
It is tempting to think the buffer clears itself. In fact frameworks such as PyTorch add each new gradient to the existing one, so the buffer must be cleared after every update. If it is not, each update includes all earlier micro-batches, and the update keeps growing.
It is tempting to think accumulation gives exactly a large batch in every case. In fact batch normalisation computes its statistics over the micro-batch, so its layers behave as if the batch were small, even though the update is built from the full effective batch. The same holds for any loss that compares examples within one batch, such as a contrastive loss that uses the other examples as negatives. Layers that normalise each example separately, such as layer normalisation, do not have this issue.
It is tempting to think accumulation speeds up training. In fact it saves memory, not computation. Every example still needs one forward and one backward pass, and small micro-batches can leave the GPU underused, so an epoch can take longer than it would with a batch that fits.
When to use it. Use it when the batch you want does not fit in memory and the model has no batch-dependent layers, or when you want to synchronise across machines less often.
When not to use it. If the full batch fits, train with it: there are fewer passes and no bookkeeping. Avoid it when a batch-dependent layer would change behaviour in a way you care about.
Alternatives. The options below each attack memory from a different side.
| Option | What it saves | What it costs |
|---|---|---|
| Gradient accumulation | Memory for the batch | More passes per update, no compute saving |
| Activation Checkpointing | Memory for stored activations | Extra forward computation during the backward pass |
| Smaller model or lower-precision numbers | Memory for weights and activations | Possible loss of quality |
| Sharding state across devices | Memory on each device | Communication between devices |
History
The idea follows from a simple fact: the gradient of a sum over examples is the sum of the per-example gradients, so the same sum can be built up over time instead of all at once. No single person introduced the technique, and it has no date of first use that can be pinned down, so this section stays general.
What made it common was scale. As models grew past what one device's memory could hold, and as deep learning frameworks made adding gradients into a buffer the default behaviour, accumulation became a standard tool. In 2017 Goyal and colleagues showed that very large batches could be trained stably with a learning-rate scaling rule and a warm-up (Goyal and colleagues' paper). That work made the batch size a setting to choose deliberately, and accumulation is one way to reach a chosen batch size on limited hardware.
Recap
- The gradient of a batch is the average of its per-example gradients, and that average can be built up from smaller pieces.
- Gradient accumulation runs forward and backward passes on micro-batches, divides each loss by , and adds the gradients into a buffer.
- One update follows every passes, then the buffer is cleared. For models without batch-dependent layers, the update matches the full batch.
- It saves memory, not computation: the trade is more passes per update for a larger effective batch.
- Read next: Linear Scaling Rule when the effective batch changes the learning rate, Critical Batch Size for how large a batch is worth using, and Activation Checkpointing for another memory saving.