Search

Search papers and lessons

Gradient Accumulation

Level 2 · 11 min read

Gradient accumulation adds up the gradients of several small batches before one weight update, so a large effective batch can be trained in the memory of a small one.

On this page

  • Colour = topic mix
  • Calculus
  • Discrete math
  • Probability
  • Linear algebra
  • Neural network basics
  • Optimizers
  • ReadReady to readNot yet

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 ww, a learning rate of 0.1, and four examples whose gradients for ww are 1, 3, 2 and 6. Micro-batches hold two examples, so each update takes N=2N = 2 passes.

  1. Start with an empty buffer. Set w=0w = 0 and the gradient buffer to 0. Check: the buffer holds nothing yet.
  2. Run the first micro-batch. Its examples have gradients 1 and 3, so their average is 2. Divide that average by N=2N = 2, 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.
  3. 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 1+2=31 + 2 = 3. Check: 3 is the average of all four examples, since (1+3+2+6)/4=3(1 + 3 + 2 + 6)/4 = 3.
  4. Update once. The weight moves by the learning rate times the buffer: w=0−0.1×3=−0.3w = 0 - 0.1 \times 3 = -0.3. Check: there is one update, and it came after both passes.
  5. Empty the buffer. Set it back to 0 so the next cycle starts clean. Check: the four examples must not be counted again.
  6. Compare with one big batch. Put all four examples in one batch. The average gradient is 3, so the update is w=0−0.1×3=−0.3w = 0 - 0.1 \times 3 = -0.3. 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

Definition: Gradient accumulation

Split an effective batch of B=NbB = Nb examples into NN micro-batches B1,…,BN\mathcal{B}_1, \ldots, \mathcal{B}_N, each with bb examples. Gradient accumulation builds the average gradient over the whole effective batch one micro-batch at a time, then applies one update with it:

G=1N∑i=1Ngi,θ←θ−η G,G = \frac{1}{N}\sum_{i=1}^{N} g_i, \qquad \theta \leftarrow \theta - \eta\, G,

where gig_i is the average gradient over micro-batch ii, θ\theta holds the parameters and η\eta is the learning rate.

Step 1 in symbols: a micro-batch gradient

Let ℓi\ell_i be the average loss over micro-batch ii, and L(x;θ)L(x; \theta) the loss on a single example xx:

ℓi=1b∑x∈BiL(x;θ),gi=∇θ ℓi.\ell_i = \frac{1}{b}\sum_{x \in \mathcal{B}_i} L(x; \theta), \qquad g_i = \nabla_\theta\, \ell_i.

The symbol ∇θ\nabla_\theta is the gradient with respect to the parameters. A forward and backward pass on micro-batch ii produces gig_i.

Step 2 in symbols: scale, then add

Before its backward pass, each micro-batch loss is divided by NN. Because the gradient of a scaled function is the scaled gradient,

∇θ(1N ℓi)=1N gi.\nabla_\theta\left(\frac{1}{N}\,\ell_i\right) = \frac{1}{N}\, g_i.

The buffer adds these terms. After NN passes it holds ∑i=1N1Ngi=G\sum_{i=1}^{N} \frac{1}{N} g_i = G.

Step 3 in symbols: one update

After the NNth pass the parameters move by θ←θ−ηG\theta \leftarrow \theta - \eta G, and the buffer is reset to zero. In the walkthrough, g1=2g_1 = 2 and g2=4g_2 = 4, so G=12(2+4)=3G = \frac{1}{2}(2 + 4) = 3 and θ=0−0.1×3=−0.3\theta = 0 - 0.1 \times 3 = -0.3.

Step 4 in symbols: why it matches the big batch

If the micro-batches split the effective batch, every example appears exactly once:

G=1N∑i=1N1b∑x∈Bi∇θL(x;θ)=1Nb∑x∈B∇θL(x;θ).G = \frac{1}{N}\sum_{i=1}^{N}\frac{1}{b}\sum_{x \in \mathcal{B}_i}\nabla_\theta L(x; \theta) = \frac{1}{Nb}\sum_{x \in \mathcal{B}} \nabla_\theta L(x; \theta).

The right-hand side is the average gradient of the full batch B\mathcal{B} of B=NbB = Nb 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

Example
1. Tiny: two passes of one example each

One weight, learning rate 0.5, and two micro-batches of one example each. The example gradients are 4 and 2, so N=2N = 2.

  1. Divide each gradient by NN: 4/2=24/2 = 2 and 2/2=12/2 = 1.
  2. Add them into the buffer: 2+1=32 + 1 = 3.
  3. Update the weight: w=0−0.5×3=−1.5w = 0 - 0.5 \times 3 = -1.5.
  4. Check against one batch of both examples: the average gradient is (4+2)/2=3(4 + 2)/2 = 3, so the update is also −1.5-1.5.
  5. Interpretation: with one example per pass, accumulation gives exactly the update of a batch of two, and the update uses both examples.
Example
2. Standard: a 256-example target on a 64-example budget

A training set has 25,600 examples. The target batch is 256, but memory fits only 64 examples per pass.

  1. Passes per update: N=256/64=4N = 256 / 64 = 4.
  2. Updates per epoch: 25600/256=10025600 / 256 = 100.
  3. Passes per epoch: 100×4=400100 \times 4 = 400. This matches 25600/64=40025600 / 64 = 400, since every example is still processed once per epoch.
  4. Each loss is divided by 4 before its backward pass, so after 4 passes the buffer holds the average gradient over 256 examples.
  5. 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.
Example
3. Realistic: fine-tuning on one 24 GB GPU

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.

  1. Passes per update: N=64/4=16N = 64 / 4 = 16.
  2. Each pass divides its loss by 16, and the buffer collects 16 passes.
  3. The learning rate tuned for batch 64 stays the same, because the effective batch is unchanged.
  4. Each update therefore costs 16 forward and backward passes of 4 sequences each, plus one optimiser step.
  5. 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: N=64/8=8N = 64 / 8 = 8 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 NN, because each is already an average over its micro-batch. Without the division, the buffer holds NN times the average gradient, so the update is NN times too large, the same as multiplying the learning rate by NN.

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.

OptionWhat it savesWhat it costs
Gradient accumulationMemory for the batchMore passes per update, no compute saving
Activation CheckpointingMemory for stored activationsExtra forward computation during the backward pass
Smaller model or lower-precision numbersMemory for weights and activationsPossible loss of quality
Sharding state across devicesMemory on each deviceCommunication 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 NN, and adds the gradients into a buffer.
  • One update follows every NN 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.

Check yourself

QuestionRecall: what does gradient accumulation change, and what does it leave the same?Show answer
It changes how the average gradient is computed: the gradient is built up over several micro-batches and applied in one update. The update rule and the result for models without batch-dependent layers match one full batch. The forward and backward work per example stays the same.
QuestionComputation: a team wants an effective batch of 96 examples, with micro-batches of 12 examples. How many passes per update, and what factor should each loss be divided by?Show answer
There are 96/12=896 / 12 = 8 passes per update. Each micro-batch loss is divided by 8 before its backward pass, so after the eighth pass the buffer holds the average gradient over all 96 examples.
QuestionWhy: why does the division by N matter, and what happens if it is left out?Show answer
Each pass's gradient is an average over its micro-batch. Adding NN such averages without dividing gives NN times the average gradient, so the update is NN times too large, as if the learning rate had been multiplied by NN. Dividing by NN makes the sum equal the average over the whole effective batch.
QuestionApplied: a team uses batch normalisation and accumulates 8 micro-batches of 16, for an effective batch of 128. Their loss curve looks like a run with batch 16 rather than one with batch 128. Why, and what can they do?Show answer
Batch normalisation computes its statistics over each micro-batch, so every pass normalises over 16 examples, not 128. The normalisation layers therefore behave like a batch-16 model, even though the update is built from 128 examples. They can switch to a normalisation that works per example, such as layer normalisation, or keep batch normalisation and tune around the difference.

Sources