Every training loop in this course has a number in it that we have passed over: the batch size. P2.7 wrote batch_size=64 and moved on. P1.F4 showed what it does to a single gradient. This lesson asks what it does to the whole of training.
A two-sentence recap of P1.F4. A mini-batch gradient is an unbiased estimate of the full gradient: its average over all possible batches is the full gradient, and its noise shrinks like when the examples are drawn independently. A step costs about gradient computations, so noise falls with while cost grows with .
What changes when you change
Take training examples and a budget of 20 epochs, which is examples seen. Only the batch size moves:
| Batch size | Steps per epoch | Steps in 20 epochs |
|---|---|---|
| 1 | 256 | 5120 |
| 8 | 32 | 640 |
| 64 | 4 | 80 |
| 256 (all) | 1 | 20 |
The same data and the same number of examples seen, but a very different number of updates. Four things change together:
- Steps per epoch, . A larger batch gives fewer updates for the same pass through the data.
- Noise per step, about (P1.F4). A larger batch gives a cleaner step.
- Time per step. A GPU works on many examples at once, so a step on 64 examples often takes less than 64 times as long as a step on one example, until the hardware is full. After that the time grows roughly in proportion to . The turning point depends on the model and the machine, so measure it rather than assume it.
- Memory. Backpropagation (P4.8) stores the activations of every example in the batch, and the shapes are throughout (P4.5). So activation memory grows in proportion to . The weights, their gradients and the optimizer state do not depend on (P4.13, P10.B4). A batch that does not fit simply cannot be used, which is the reason for gradient accumulation later in this lesson.
None of these is “good” or “bad” alone. The question is what you get for the price, and the answer depends on the learning rate.
The batch-size slider
The widget below trains the same tiny model for every setting: logistic regression (P3.A7) on 256 made-up two-dimensional points from two overlapping blobs, started from the same weights, with plain SGD (P1.F4) and the data shuffled every epoch. The budget is always 20 epochs. The solid blue line is the loss on all 256 points after each step. The faint line is the loss on the step’s own batch, which is the noisy thing a training log prints.
Things to try. Each value was checked against a NumPy run of the same model:
- The default (, ): 32 steps per epoch, 640 steps, final loss . That equals the lowest possible loss of this model, to three digits. The loss gets within of it after 184 steps (1472 examples).
- The same , a bigger batch. At the final loss is , and at it is . The curve is the same shape, only slower, because 80 steps () or 20 steps () of simply do not go far. Pin and compare, on the examples axis and then on the steps axis.
- A smaller batch. At and the loss gets within of the lowest after only 201 steps, which is 201 examples. With the same , a small batch takes a step after every example, so it makes progress sooner. The faint line shows the price: the loss on a single example reaches about 10 on one step, far above the average.
- Scale with . Tick the box. Now , so uses and uses . Every batch size from 1 to 256 ends at . On the examples axis the curves nearly coincide. On the steps axis the large batch is far ahead: gets within in 6 steps, in 23, in 184, and in 1470.
- Push it too far. Keep the box ticked and raise to . (so ) still ends at , but () ends at and the status line says that the loss rose above its starting value. With , ends at . The rule has limits, and the next section says why.
Matching the learning rate to the batch size
Compare two ways to use 4 batches of 64 examples. Take four small steps of rate , one on each batch. Or take one big step on all 256 examples with rate . If the weights did not move between the four small steps, each small step would use the gradient of its own batch at the starting weights, . The four steps add up to . The big step uses the average of the same four gradients, times , which is the same sum. The two agree exactly.
That is the linear scaling rule: when you multiply the batch size by , multiply the learning rate by . Goyal and others (2017) used it to train ResNet-50 on ImageNet with batches of up to 8,192 images. They matched the accuracy of small-batch training up to a batch of 8,192; for larger batches the accuracy fell. They also added a warmup: the learning rate starts small and rises over the early part of training, because early in training the weights change fast, which is when the “weights barely move” assumption is least likely to hold (P4.14).
The argument also says when the rule fails. It needs the gradient to stay about the same over the small steps. The cell below measures it on a model of the same kind as the widget’s, with a NumPy random data set, so its numbers differ from the widget’s: from the same start, four steps of 64 examples against one step of 256 with , and the size of the gap relative to the big step.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Running the code gives this (on the machine used for this lesson):
eta gap / length of the big step
0.001 0.0004
0.010 0.0041
0.100 0.0454
1.000 0.5444
For small rates the two agree to a fraction of a percent. At the four small steps end about half a step-length away from the big step, because the weights moved a long way between them. So the rule is an approximation that is good while the scaled rate stays small enough, and it cannot hold for ever: the widget showed it breaking at .
More limits.
- McCandlish and others (2018) searched for the best constant learning rate at each batch size. For plain SGD or momentum, the best rate rose roughly linearly with at first and then levelled off. Beyond that point a bigger batch no longer allows a bigger rate.
- For Adam and RMSProp they found the best rate growing like , with between and depending on the task, and then also levelling off.
- A square-root rule (multiply by for a batch times larger) was derived for Adam and RMSProp by Malladi and others (2022). Adam divides each step by a running size of the gradients (P4.13), so its steps do not add up the way plain SGD’s do, and the argument above does not carry over directly. So for Adam-style optimizers, is a common first guess and is the other end of the range seen in experiments.
Treat both rules as a first guess to test, not a law. The reliable practice is to change , start from the rule’s learning rate, and check a few rates around it (P4.23).
Sum or mean? P4.6 showed two examples with errors and . The mean loss gave a gradient (with respect to ) of and the sum gave . With a sum over a batch of examples the gradient is times the mean’s, so a summed loss with rate is the same step as a mean loss with rate . The linear rule says the good rate for a mean loss grows in proportion to , so for a summed loss it says to leave alone. It is the same rule in different units, and it is why P4.6 said that the best learning rate shifts with the batch size.
Where a bigger batch stops paying: the critical batch size
If the learning rate is scaled well, a times larger batch needs about times fewer steps. The widget showed it: 1470 steps at , 184 at , 23 at , 6 at . The total number of examples was almost the same each time, about 1500. So a larger batch used the hardware’s parallelism (several examples per step) for free. This cannot continue for ever. Once a batch is big enough that its gradient is already close to the full gradient, more examples in the batch change the step very little.
McCandlish and others (2018) gave a simple model for this. Let be the fewest steps needed to reach some loss (with an enormous batch) and the fewest examples (with tiny batches). With batch size , in the model the steps needed are
where is the critical batch size. This is a fit to their measurements, for a chosen target loss, not an exact law. Made-up numbers show its shape, with and :
| Steps | Examples | |
|---|---|---|
| 8 | 9,000 | 72,000 |
| 64 | 2,000 | 128,000 |
| 512 | 1,125 | 576,000 |
Going from to (eight times the batch) cuts the steps by times and costs times the examples. Going on from to cuts the steps by only times and costs times the examples. At you use twice the minimum steps and twice the minimum examples. Below extra batch size is nearly free speed. Above it, it mostly burns compute. That is why “just use the biggest batch that fits” is not the whole answer.
Go deeper The gradient noise scale
How could you know without trying many batch sizes? McCandlish and others proposed a statistic they call the gradient noise scale. Its simplest form is
where is the full gradient and is the covariance of the per-example gradients, so is the sum of the variances of the gradient’s entries. It compares how large the noise of one example is with how large the true gradient is. They found that it predicts the largest useful batch size to within about an order of magnitude on many tasks, and that it tends to rise as the loss falls, so the critical batch size grows during training.
The cell measures it on a model of the same kind as the widget’s, along a run with and .
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
epochs noise scale
0 2.7
1 3.7
2 5.7
5 25.1At the start the noise scale is , so with a batch of about 3 the noise in the batch gradient is already as large as the true gradient; far smaller batches are mostly noise, and larger ones give a clean step. By epoch 5 it is , because the full gradient has shrunk while the per-example gradients have not. Near the minimum the full gradient goes to zero and the statistic grows without limit, so it is only meaningful while the loss is still falling. This is a small convex model, so the numbers show the direction of the effect and not the size to expect in a real network.
Does the batch size change what you learn? The generalization debate
So far a bigger batch only changes how fast training goes. On the widget’s model there is one lowest loss, and every setting that converges ends at it. A neural network’s loss has many low regions, so the batch size could change which one training reaches, and a model that fits the training data equally well can do differently on new data (P3.A1). What is known?
- Keskar and others (posted 2016, ICLR 2017) trained networks with large and small batches and reported that large batches ended with worse test accuracy. They found that large-batch solutions were in sharp minima, where the loss rises quickly when the weights move a little, and small-batch solutions in flat ones. They proposed that the noise of small batches is what steers training away from sharp minima.
- Goyal and others (2017) found that on ImageNet much of the large-batch gap disappeared when the learning rate was scaled with the batch size and warmup was used, up to a batch of 8,192.
- Shallue and others (posted 2018, JMLR 2019) trained many models and datasets over a wide range of batch sizes. They reported no evidence that larger batch sizes hurt test performance, and argued that conflicting reports come from differences in how the learning rate and other settings were tuned, and in the compute budget.
So the claim “small batches generalize better” is an observation that held in some experiments with fixed settings, and it weakens when the learning rate is tuned for each batch size. It is not established as a general rule; whether noise helps generalization is still being studied. P4.24 comes back to generalization puzzles. What you can rely on is practical: a fair comparison tunes for each batch size, and with a fixed a bigger batch is a different training run, not just a faster one.
The two ends: and full batch
- is pure stochastic gradient descent. It takes the most steps, uses the least memory, and has the noisiest steps: the faint line in the widget. It usually leaves parallel hardware underused, and layers that need statistics over a batch cannot work with a batch of one (P4.19).
- is full-batch gradient descent. It has no sampling noise, one step per epoch, and needs the activations of every example at once. At the same it falls far behind in the widget, because a step is a good one but there are so few of them.
Almost all practical training sits in between, where the noise is small enough to use a large and the batch is small enough to fit and to give many steps.
Gradient accumulation: a bigger batch than memory allows
Suppose you want a batch of 256 but only 64 examples fit in memory. P2.7 pointed out that if you forget zero_grad, gradients add up in .grad. Adding gradients on purpose is a trick called gradient accumulation, which lets you simulate a larger batch than fits in memory. The algorithm:
- Split the batch into micro-batches (here micro-batches of 64).
- For each micro-batch, compute its loss, divide it by , and call
backward(). The gradient is added to.grad. - After micro-batches, take one optimizer step and then zero the gradients.
Why divide by ? Each micro-batch loss is a mean over its own 64 examples. The mean over all 256 is the average of the four micro-batch means: . Adding four gradients without dividing gives times the right answer, which is the same as multiplying the learning rate by .
The cell checks it in NumPy for the three-weight model: four micro-batches of 64 against one batch of 256, then the two mistakes that are easy to make.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
big batch: [ 0.1199 -0.2029 0.0219]
accumulated: [ 0.1199 -0.2029 0.0219]
largest difference: 8.3e-17
without /4, too big by 4.0 times
equal weights: 7.0e-03
weighted by size: 5.6e-17
The accumulated gradient matches the big-batch gradient to rounding ( in 64-bit floats). Dividing by matters, and so does weighting when the pieces are unequal: if the last micro-batch is smaller, weight each piece’s loss by its share of the examples, , instead of .
The same thing in PyTorch. Two steps on batches of 128 are compared with the same 256 examples as eight micro-batches of 32, one step per four (run locally with PyTorch 2.9.1, no shuffling so that both see the examples in the same order):
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
torch.manual_seed(0)
x = torch.randn(256, 3)
y = (torch.rand(256, 1) < 0.5).float()
data = TensorDataset(x, y)
loss_fn = nn.BCEWithLogitsLoss()
def make():
torch.manual_seed(1)
return nn.Linear(3, 1)
# plain loop: batches of 128, one step per batch
plain = make()
opt = torch.optim.SGD(plain.parameters(), lr=0.1)
for xb, yb in DataLoader(data, batch_size=128, shuffle=False):
opt.zero_grad()
loss_fn(plain(xb), yb).backward()
opt.step()
# accumulation: batches of 32, one step per 4 batches
model = make()
opt = torch.optim.SGD(model.parameters(), lr=0.1)
m = 4 # micro-batches per step
opt.zero_grad()
for k, (xb, yb) in enumerate(DataLoader(data, batch_size=32, shuffle=False)):
loss = loss_fn(model(xb), yb) / m # divide by the number of micro-batches
loss.backward() # adds to .grad
if (k + 1) % m == 0:
opt.step()
opt.zero_grad()
diff = max((a - b).abs().max().item()
for a, b in zip(plain.parameters(), model.parameters()))
print("two steps of 128 against 8 micro-batches of 32")
print(f"largest weight difference: {diff:.1e}")
two steps of 128 against 8 micro-batches of 32
largest weight difference: 1.5e-08
The is float32 rounding: the weights agree to the precision of the numbers.
What accumulation does not do.
- It does not save time. The same number of forward and backward passes happen. It trades speed for memory: one optimizer step now takes passes.
- It cannot copy layers that mix the examples of a batch. Batch normalization (P4.19) computes its statistics over the examples it sees, so with micro-batches it uses the statistics of 64 examples, not of 256. The result is not the big-batch result, however carefully you divide.
- Count in optimizer steps. A learning-rate schedule and warmup (P4.14) should advance once per optimizer step, not once per micro-batch, or the schedule runs times too fast. A logged micro-batch loss is divided by : multiply by to read that micro-batch’s mean, or add up the divided values to read the whole batch’s mean.
The batch size and learning rate go together
The pair is what matters, not alone. In practice:
- Compare at equal examples seen, as the widget does, or at equal epochs. At equal steps a larger batch has seen more data.
- Pick a batch that fits and keeps the hardware busy, then tune for it. If you change later, start from the scaling rule for your optimizer, add warmup if the jump is large, and check a few rates.
- Powers of two are a habit. Sizes such as 32, 64 and 128 are convenient for memory layouts and are what most code uses. A batch of 100 works the same way mathematically.
- A noisy loss curve is not a bug. The loss on a single batch jumps around, especially for small . Read the trend, or the loss on a fixed validation set (P4.22).
Summary: intuition, math, code
Intuition
Think of a survey. A small survey is cheap and a little off each time. A huge survey is expensive and very accurate, but once the answer is already accurate enough, asking more people changes little. Training takes many small surveys in a row and adjusts after each. A small batch means many cheap adjustments that are a bit shaky. A bigger batch means fewer, steadier adjustments, so each one can be bolder, which is the idea of the scaling rule. The picture breaks in one way: a survey sample is fixed, while each batch changes the weights before the next one is drawn. There is a size past which steadier no longer helps, because the shakiness is already small next to the true direction. That size is the critical batch size.
Math
Mini-batch step: , with . Steps per epoch: .
- Linear scaling. small steps of rate with batch gradients at the starting weights give ; one step at batch with rate gives , the same sum.
- Mean and sum. , so a sum with is a mean with .
- Critical batch size (a fitted model). , , . Equivalently .
- Noise scale. , and the expected squared error of a batch gradient is for independent draws.
- Accumulation. With micro-batches of sizes and : , which is when all are equal.
Code
The core of accumulation, with the batch size set in the data loader and not in the optimizer (P2.7). The full program with its output is in the section on gradient accumulation above.
loader = DataLoader(data, batch_size=32) # the micro-batch size
m = 4 # micro-batches per optimizer step
for k, (xb, yb) in enumerate(loader):
(loss_fn(model(xb), yb) / m).backward() # adds to .grad
if (k + 1) % m == 0:
opt.step()
opt.zero_grad()Check your understanding
You train with plain SGD at batch size 64 and learning rate 0.1. You move to batch size 512 and use the linear scaling rule. What learning rate do you start with?
The batch is 8 times larger, so the linear rule multiplies the rate by 8: . Keeping ignores the rule. The value is the square-root guess, , which is meant for Adam-style optimizers. The value divides by 8, the wrong direction.
A model is trained with a loss that is the SUM over the batch, not the mean. The batch size grows by a factor of 16 and the linear scaling rule is applied. What should happen to the learning rate of the summed loss?
A summed loss with rate is the same step as a mean loss with rate . The rule says the mean-loss rate should grow in proportion to , and already does, so stays. Multiplying by 16 would count the scaling twice, and dividing by 16 or multiplying by 4 does not follow from either form of the rule.
In a model of large-batch training, the critical batch size is 64. What is the main effect of raising the batch size from 64 to 1024?
Above the critical batch size the steps needed approach their minimum, so more examples in a batch buy little. With , going from 64 to 1024 cuts the steps from to about , while the examples grow about 8.5 times. A 16-fold cut in steps would need the regime below the critical size. Fewer examples is the opposite of what happens, and the model says nothing about a lower final loss.
Gradient accumulation uses 8 micro-batches per optimizer step. Each micro-batch loss is a mean over its own examples. What must be done to the loss before backward() so that the step matches one big batch?
Gradients are added in
.grad, so eight means added up are eight times the mean over the big batch. Dividing each loss by 8 fixes it. Multiplying makes it 64 times too big. Nothing is done automatically. Dividing by the micro-batch size would only turn a summed micro-batch loss into a mean, which is still 8 times too big; the extra division by 8 is what is missing.Which statement about batch size and generalization is best supported by the studies in this lesson?
Keskar and others reported a gap, while Goyal and others and Shallue and others found that tuning removed much or all of it, so the picture is mixed. The other three are absolute claims that the evidence does not support: the gap is not universal, scaling does not guarantee a match, and the batch size can change which solution is found.
Exercises
- A data set has examples. How many steps are there in one epoch, and in 10 epochs, with ? How many with ?
Show answer
steps per epoch, so steps in 10 epochs. With it is steps per epoch and in 10 epochs. Both see examples. - SGD with works well at . Using the linear rule, what is a starting at ? For Adam with at , what is the square-root guess?
Show answer
The batch is times larger. Linear: . Square root: . Both are first guesses to test. - You want an effective batch of 128 but only 16 examples fit. How many micro-batches per step, and what should each loss be divided by? What happens if you forget the division with plain SGD?
Show answer
micro-batches, so divide each loss by . Without it the gradient is times too big, which acts like a learning rate times larger. - In the critical-batch model with and , find the steps and the examples for and .
Show answer
. For : and . For : and . The larger batch saves four times the steps and costs four times the examples. - You have 100 examples split into micro-batches of 40, 40 and 20. What weights multiply the three mean losses so that the sum equals the mean over all 100?
Show answer
Each weight is the share of examples, : , and . Using each would give the small piece too much influence. - A summed-loss run uses and . What mean-loss learning rate gives the same step?
Show answer
The sum equals times the mean, so . P4.6 showed the same factor for two examples.
Next: P4.14 covers learning-rate schedules and warmup, which are the other half of the batch-size and learning-rate pair. P4.19 explains batch normalization, the layer that accumulation cannot copy, and P10.B6 shows how very large batches are spread across many devices.