All courses

Batch size in tokens and gradient accumulation

Measure batch size in tokens (B·T) and simulate a large batch with gradient accumulation over microbatches. Explain the critical batch size beyond which a bigger batch stops reducing the number of steps needed.

Builds on: The LLM training loop

▶ Watch this lesson Start the whole course

What the animation says

Count predictions, not sequences

Your training loop averages the loss over a batch, then takes one optimizer step. But how big is a batch, really? Draw it as a grid. Each row is a sequence. Each column is a position in that sequence. Every cell is one next-token prediction, and every prediction adds its own term to the gradient. So the size that matters is rows times columns: the number of tokens. Two batches. A has thirty-two sequences of five hundred twelve tokens. B has eight sequences of four thousand ninety-six. Which gives more gradient terms?

Average it in pieces

B wins: about thirty-three thousand predictions against sixteen thousand. Count tokens, not sequences. Now say the batch you want doesn't fit in memory. A gradient is an average, so you can compute it in chunks. Split sixty-four rows into four equal microbatches. They run one after another, and each gives its own mean gradient. Divide each one by four, add them up, and you get exactly the full-batch gradient. Only then, one optimizer step. This loop forgot something. Tap the line that makes the gradient four times too big.

A million tokens on a small GPU

Now a real target: about one million tokens per step, with sequences of two thousand forty-eight tokens. One million divided by two thousand forty-eight is five hundred twelve sequences. But only eight fit on the GPU at once. Five hundred twelve divided by eight gives sixty-four microbatches. Each microbatch loss is divided by sixty-four, and the optimizer steps once, after all of them. Same update as the big batch, just slower. Say a one-million-token batch needs twenty thousand steps to reach your target loss. Make it four million. How many steps now?

Why bigger batches stop helping

Twelve thousand five hundred. Quadrupling the batch cut barely more than a third of the steps. Why? A batch gradient is the true direction plus noise, and more tokens shrink that noise. While noise dominates, steps must stay cautious, so doubling the batch nearly halves the steps. But the gradient is only a local slope. The loss surface curves away from it, so steps can't grow much, however precisely you measure. The crossover is the critical batch size. Past it, extra tokens just polish a direction that's already accurate.

Steps vs tokens: the trade

An empirical fit: steps equal the minimum steps, times one plus the critical batch over your batch. Take ten thousand minimum steps and a critical batch of one million tokens. A quarter million per batch needs fifty thousand steps. One million needs twenty thousand. Four million, twelve thousand five hundred. Now multiply by batch size to count tokens: twelve and a half billion, twenty billion, fifty billion. Below the critical batch, you waste steps. Above it, you waste tokens, and so compute.

How big is a batch, and how big should it be?

Your loop averages the loss over a batch and then takes one optimizer step. That raises three practical questions. Should batch size be counted in sequences or in tokens? If the batch you want, say 1M tokens, doesn't fit in memory, can you still train with it? And does doubling the batch always halve the number of steps needed to reach a target loss?

Count predictions; average them in pieces

Every token position is one next-token prediction that contributes a gradient term, so the batch size that matters is the token count $B\cdot T$. A gradient is an average, so you can compute it in chunks. Run several small **microbatches**, add up their gradients, then step once. This is **gradient accumulation**. The only cost is time, because the microbatches run one after another.

Why bigger batches stop helping

A batch gradient is the true direction plus noise, and the noise variance shrinks like $1/(B\cdot T)$. At small batch sizes noise dominates and steps must stay cautious, so doubling the batch roughly halves the steps needed. Once noise is small next to the signal, a different limit takes over. The gradient is only a local slope, and the loss surface curves away from it, so a step can't be much bigger however precisely you measure that slope. Extra tokens then only polish a direction that is already accurate. The crossover point is the **critical batch size**.

The formulas

Batch in tokens: $B_{tok}=B\cdot T$. Accumulation: with $k$ equal-sized microbatches whose mean losses are $\mathcal{L}_j$, $$\nabla\mathcal{L}=\tfrac1k\textstyle\sum_{j=1}^k\nabla\mathcal{L}_j$$ So scale each microbatch loss by $1/k$ before backward. Steps $S$ to reach a target loss (an empirical fit): $$S\approx S_{min}\Big(1+\tfrac{B_{crit}}{B_{tok}}\Big)$$ $S_{min}$ is the fewest steps possible, approached as the batch grows without limit. $B_{crit}$ is the critical batch size. Total tokens processed are $S\cdot B_{tok}\approx S_{min}(B_{crit}+B_{tok})$. At $B_{tok}=B_{crit}$ you pay 2× the minimum steps and 2× the minimum tokens ($S_{min}B_{crit}$). Below it you waste steps; above it you waste tokens.

1M tokens on a small GPU

Target: $B=512$, $T=2048$, so $B_{tok}=2^{20}\approx1.05$M tokens. Only 8 sequences fit at once, so use $k=512/8=64$ microbatches, each loss divided by 64. Now take $S_{min}=10{,}000$ and $B_{crit}=1$M: - 0.25M: $S=50{,}000$, tokens 12.5B - 1M: $S=20{,}000$, tokens 20B - 4M: $S=12{,}500$, tokens 50B Going from 1M to 4M quadruples the batch but saves only 37.5% of the steps.

Accumulated gradient = full-batch gradient

This is a linear model with squared error, but the identity is the same one your LLM loop relies on. Four microbatch gradients, each scaled by $1/k$ and summed, exactly reproduce the gradient of the full batch of 64.
import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(size=(64, 3)); y = rng.normal(size=64); w = np.ones(3)
def grad(Xb, yb):  # gradient of mean squared error
    return 2 * Xb.T @ (Xb @ w - yb) / len(yb)
full = grad(X, y)
k = 4; acc = np.zeros(3)
for Xm, ym in zip(np.split(X, k), np.split(y, k)):
    acc += grad(Xm, ym) / k   # like (loss / k).backward()
print(np.allclose(full, acc))  # True: then one optimizer step

Remember

Measure batch size in tokens, $B\cdot T$. Gradient accumulation sums $1/k$-scaled microbatch gradients and then takes one step, giving the same update as the big batch, only slower. Below the critical batch size, doubling the batch nearly halves the steps needed. Above it, steps barely drop while total tokens, and so total compute, keep growing.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.