AI State of the Art
SOTA/Training: Modern Training Techniques/33 min
Section 95

Gradient Accumulation and Effective Batch Size

Listen as a podcast →

The problem: you want a 4-million-token batch, the card digests 16,000

A word of vocabulary first, because the whole lesson rests on this distinction.

A batch is the bundle of examples over which the model computes one correction before changing its weights. Scaling laws show that training a large language model needs batches of several million tokens to be stable. But an accelerator can only hold a handful of sequences in memory at once: four sequences of 4,000 tokens is 16,000 tokens, and memory is already full.

So the arithmetic is simple and unpleasant: you want 4 million, you can load 16,000. Two hundred and fifty times fewer.

Gradient accumulation is the answer. Instead of correcting the weights after each small bundle, you add up the corrections from several small bundles and change the weights only once, at the end. The model receives exactly the correction a large batch would have produced, but the card never had to host more than one small bundle.

It is filling a swimming pool with a bucket: you cannot fill it in one trip, but with enough trips the result is the same, and you only ever need one bucket.

Micro-batch and effective batch: the central distinction

Two terms for two things that get confused constantly:

  • the micro-batch is what the card actually processes in one go. It, and it alone, determines the memory required. It is a hardware constraint: it depends on how big the card is.
  • the effective batch is what the optimiser sees: the total number of examples folded into a single weight update. It, and it alone, determines the learning dynamics. It is a recipe choice: it depends on what you want to train.

The entire point of the technique is to decouple these two numbers. Without accumulation they are equal, and the hardware dictates the recipe. With accumulation you pick the effective batch you want and adjust the number of trips.

effective batch=micro-batch×accumulation steps×cards in data parallelism\text{effective batch} = \text{micro-batch} \times \text{accumulation steps} \times \text{cards in data parallelism}

Each symbol in words: the micro-batch is the number of sequences one card processes in one go; the accumulation steps are how many micro-batches you stack before updating the weights; the number of cards is the count of model replicas each working on its own slice of the data, described in Data parallelism. The formula says, in one sentence: the effective batch is the product of three ways of slicing the same batch, across time, across cards, and inside a card.

A worked example, derived end to end:

  • micro-batch: 2 sequences of 4,000 tokens, so 8,000 tokens;
  • accumulation: 16 steps;
  • data parallelism: 64 cards;
  • effective batch: 2 × 16 × 64 = 2,048 sequences, that is 2,048 × 4,000 ≈ 8 million tokens.

Eight million tokens per weight update, while at any instant a card holds only 8,000. The full account of what occupies a card's memory during training (weights, gradients, optimiser state, activations) is laid out in ZeRO, which is this course's reference for that arithmetic.

What accumulation does not reduce

It pays to be precise about what is saved. Accumulation reduces the memory of the activations, the intermediate results kept during the forward pass so gradients can be computed on the backward pass. That item is proportional to the micro-batch, so it shrinks when the micro-batch shrinks.

It reduces none of the other three items: the weights, the accumulated gradients and the optimiser state take up the same room whatever the micro-batch, because their size follows the model, not the batch. Those need different tools, ZeRO or FSDP, which spread them across cards.

How it works

The algorithm is disarmingly simple:

  1. set the gradients to zero;
  2. for each micro-batch i=1i = 1 to AA, where AA is the number of accumulation steps:
    • forward pass (compute the prediction and the error);
    • backward pass: the gradients add to whatever is already there, instead of replacing it;
  3. divide the accumulated gradients by AA, to get an average rather than a sum;
  4. update the weights;
  5. reset the gradients to zero for the next cycle.

That is all. Step 2 is not even something you code: adding is the default behaviour of the training libraries. What is new is what you don't do, reset to zero between micro-batches.

Step 3 deserves a note, because dividing by AA is not decorative. Without it you would get a sum of AA gradients, so a gradient AA times too large, and the optimiser's step would be AA times too long. That is one of the fastest ways to blow up a training run.

Loop diagram of gradient accumulation: a mini-batch is drawn from the training data, a forward pass through the model produces a loss and then a gradient, that gradient is added to the accumulated gradient, the loop goes back for the next mini-batch, and only at the end is the accumulated gradient used to update the model.
The loop, step by step. Arrows 1 to 4 go around several times without ever touching the weights: each micro-batch only adds its contribution to the accumulated gradient. The model update, step 5, happens once the loop is done.Source : Daily Dose of Data Science
Chart of effective batch size against the number of accumulation steps, with three straight lines for micro-batches of 4, 8 and 16 samples, and a horizontal line marking a target effective batch size of 256.
The relationship is a plain straight line: effective batch size is micro-batch size times the number of accumulation steps. To hit a given target (256 here), a smaller micro-batch simply accumulates for longer, while the GPU memory required depends on the micro-batch alone.Source : Marcel Brenndoerfer, Gradient Accumulation
for i in range(accumulation_steps):
    loss = model(batch[i]) / accumulation_steps  # divide here, before the backward pass
    loss.backward()                              # gradients add up

optimizer.step()
optimizer.zero_grad()

In practice you divide the loss before the backward pass rather than dividing the gradients after: it is mathematically identical and saves one more walk over every gradient.

Why splitting changes nothing about the learning

This is the point that makes the technique interesting, and it is worth seeing rather than believing.

A gradient is a derivative, and the derivative of a sum is the sum of the derivatives. The loss over a batch of 2,048 sequences is, by definition, the average of the losses over those 2,048 sequences. Its gradient is therefore the average of the 2,048 individual gradients. Whether you group those 2,048 sequences into one bundle of 2,048, sixteen bundles of 128, or 2,048 bundles of 1, the average is the same: addition does not care what order you add in.

So this is not an approximation. The model does not "simulate" a large batch in the sense of getting a degraded version of it: it gets exactly the same gradient, up to rounding noise. That sets gradient accumulation apart from most memory-saving techniques, which usually trade a little quality for room.

The caveat: layers that look at the whole batch

The equality holds as long as the computation done on one example does not depend on the other examples in the same bundle. A layer that mixes examples together breaks the equivalence, because it now sees only the micro-batch instead of the whole batch.

The textbook case is batch normalization: it recentres each value by subtracting a mean computed over all the examples in the bundle. With a micro-batch of 2 instead of a batch of 2,048, that mean is computed over 2 examples: it is far noisier, and the result is no longer the same. Accumulation genuinely changes the computation there.

The good news for large language models: they do not use batch normalization. They use layer normalization or its RMSNorm variant, which normalise each token from its own values, independently of the other examples in the bundle. They are therefore insensitive to micro-batch size, and the equivalence holds exactly. That difference is detailed in Normalization.

Keep the general rule: accumulation is exact for anything that treats examples separately, and wrong for anything that mixes them.

The loss-weighting trap

A second case, less theoretical and much more common in practice. If the micro-batches do not contain the same number of real tokens (which happens as soon as sequences have different lengths and you pad the rest) then dividing each loss by the number of accumulation steps gives every micro-batch the same weight, whereas a single large batch would have weighted every token equally.

The result is a slightly wrong gradient that produces no visible error: training runs, it just converges a little worse. Widely used fine-tuning libraries carried this defect for a long time before it was reported publicly in 2024. The fix is to accumulate the token count alongside the gradients, and divide by that total at the end rather than by the number of steps.

Why want large batches at all?

Reason 1: the compute-to-communication ratio

With a small batch spread over 64 cards, each card computes very little before it has to synchronise its gradients with the others. Time on the network dominates time computing. With a large batch, each card computes for a long stretch between synchronisations, and the exchange has time to hide underneath the computation, the compute-communication overlap described in Scaling infrastructure.

This is the most down-to-earth reason and often the decisive one: gradient accumulation is the cheapest lever for rescuing a training run that is network-bound.

Reason 2: stability of the gradient estimate

The gradient computed on a batch is only an estimate of the gradient you would get over the whole dataset. Like any sample estimate, it is noisier the smaller the sample. Over 16,000 tokens, two consecutive micro-batches can point in noticeably different directions. Over several million, the estimate settles down, and the optimiser can move further with confidence.

Two published reference points, for scale: GPT-3 175B was trained with a batch of 3.2 million tokens, the value given in the paper's hyperparameter table. Llama 3 405B ramps up in stages to 16 million tokens per batch.

Language Models are Few-Shot Learners (GPT-3) The Llama 3 Herd of Models

Reason 3: the critical batch size

Critical batch size

The critical batch size is the point beyond which doubling the batch no longer really reduces the number of iterations needed: you pay twice the compute per step for nearly as many steps. Below it, growing the batch pays off; above it, it is waste.

A commonly reported point is that this threshold is not fixed: it grows over the course of training. That is what justifies batch ramp-ups (start small, grow along the way) as Llama 3 does, going from 4 to 8 to 16 million tokens.

Skipping the pointless synchronisations

Synchronise only on the last micro-batch

With standard data parallelism, every backward pass automatically triggers a gradient synchronisation across all cards. With 16 accumulation steps, that is 16 synchronisations, of which 15 are pure waste: the intermediate gradients are of no use, only the final total will be consumed.

The fix is a switch, called no_sync in PyTorch, that suspends automatic synchronisation. You keep it closed for the first 15 micro-batches and open it for the last. Communication volume is divided by 16 without changing a comma of the result. On a multi-machine installation, where the network is eighteen times slower than the internal link, that is a first-order gain.

for i in range(accumulation_steps):
    loss = model(batch[i]) / accumulation_steps
    if i < accumulation_steps - 1:
        with model.no_sync():   # exchange nothing
            loss.backward()
    else:
        loss.backward()         # this last call triggers the synchronisation

optimizer.step()

The effect on the learning rate

The learning rate is the length of the step the optimiser takes in the direction the gradient points. As the batch grows, the gradient gets less noisy, hence more trustworthy, hence you can afford a longer step. The question is how much longer.

The most quoted rule is linear scaling: multiply the batch by kk and multiply the learning rate by the same kk. It was established for a vision training run with SGD with momentum, on batches up to 8,192 images.

Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour (Goyal et al., 2017)
The linear rule does not transport as is

Applied without thought to large language models, it yields absurd values. Going from a one-million-token batch to eight million would multiply the learning rate by 8, a model tuned at 10−410^{-4} would jump to 8×10−48 \times 10^{-4}, which at that scale usually blows the run up.

Two reasons. The rule was demonstrated for SGD, not for Adam, which already normalises gradients by their own magnitude and therefore behaves differently; in practice a square-root scaling is what you tend to meet with Adam. And more importantly, the rule assumes you are still below the critical batch size, precisely where it stops applying.

The right way to pose the question today is not to pick between two rules of thumb but to tune on a small model and transport: see μP and μTransfer.

One thing stays true whichever rule you use: a higher learning rate makes the start of training more fragile, when the weights are still random. So the warmup phase, during which the rate is ramped up from zero, has to be lengthened. The details are in Learning rate scheduling.

Past a point, a bigger batch buys nothing

Beyond a certain threshold, growing the batch becomes counter-productive, for two distinct reasons. First, the noise in a small batch acts as a regulariser: it stops the optimiser from committing too fast to one direction, and removing it entirely can hurt generalisation. Second, at a fixed token budget, a batch twice as large means half as many weight updates: the model sees the same data but takes half the steps.

An illustrative configuration for a 7-billion-parameter model

SettingValueWhere it comes from
Micro-batch2 sequences of 4,000 tokensfixed by the memory available on the card
Accumulation steps16chosen to reach the target effective batch
Cards in data parallelism64size of the installation
Effective batch2,048 sequences2 × 16 × 64
Tokens per batch8 million2,048 × 4,000

This table is a teaching example, not a recommendation drawn from a paper: the first three rows are choices, the last two follow by multiplication. It is here to show the direction of reading: you start from the hardware constraint and the target batch, and accumulation is the variable that joins the two.

Interaction with pipeline parallelism

In pipeline parallelism, the model's layers are spread over several cards placed in series, and micro-batches cross them one after another. At the start and end of each step, some cards have nothing to do: that is the bubble.

Gradient accumulation fills that bubble, because the micro-batches it supplies are exactly what the pipeline needs to be fed. The fraction of wasted time works out as:

bubble=G−1M+G−1\text{bubble} = \frac{G - 1}{M + G - 1}

The symbols: GG is the number of cards in series in the pipeline, MM the number of micro-batches pushed through it. The numerator G−1G - 1 is the number of steps during which the pipeline is filling or draining; the denominator is the total duration, counted in steps.

With 8 cards and 16 micro-batches: 7/23≈30%7 / 23 \approx 30\% wasted. With 32 micro-batches: 7/39≈18%7 / 39 \approx 18\%. The lesson is direct: the more you accumulate, the more the bubble is diluted, because the fill time is fixed while the total duration grows.

GPipe scheduling diagram over four pipeline stages and four micro-batches: each row shows forward passes F then backward passes B staggered in time, with an empty area in the middle labelled Bubble, and a shared Update column on the right.
The four rows are four pipeline GPUs, time runs left to right. The F cells are forward passes, the B cells backward passes, and the hole in the middle is the bubble: GPUs sitting idle. The more micro-batches you push through (only 4 here), the tighter the cells pack and the smaller the bubble becomes in proportion. The Update column on the right makes it clear the weight update happens only once every micro-batch has gone through.Source : GPipe paper, via Yue Shui

Key points

  1. Two numbers, not one. The micro-batch fixes the memory required, the effective batch fixes the learning dynamics. Gradient accumulation exists to decouple them.
  2. The mechanism: add up the gradients of several micro-batches, divide by their count, then update the weights once.
  3. It is not an approximation. The derivative of a sum is the sum of the derivatives: the gradient obtained is exactly the large batch's. What breaks the equality is layers that mix examples within a bundle, batch normalization. Large language models use layer normalization, which is insensitive to micro-batch size, so the equality holds.
  4. What is saved: activation memory, proportional to the micro-batch. Not the weights, gradients or optimiser state, whose size follows the model, for those, see ZeRO.
  5. The secondary gain, often the main one: more computation between synchronisations, so communication hides better underneath it, and 15 synchronisations out of 16 that can simply be skipped.
  6. Mind the learning rate. Growing the effective batch changes the right learning rate, but not by any simple universal rule. The reliable route is transfer from a small model: μP and μTransfer.
Check your understanding0 / 5

1. A card tops out at a micro-batch of 2 sequences, but the training recipe calls for an effective batch of 2,048. Which of the two numbers determines the memory needed, and which the learning dynamics?

2. Does splitting a batch of 2,048 sequences into 16 accumulated micro-batches give a degraded version of the large batch's gradient?

3. Your sequences have different lengths, padded to a common size, and you divide each loss by the number of accumulation steps. What is the risk?

4. You multiply the effective batch by 8. Should you multiply the learning rate by 8, as the linear scaling rule suggests?

5. At a fixed token budget, why does growing the batch without limit eventually become counter-productive?