To learn what a whole country thinks about a new law, you do not ask all 40 million people. You ask a random 1,000. The answer is a little off, but it costs almost nothing, and if you ask another random 1,000 tomorrow, the two errors tend to cancel out.
Training a model faces the same choice. The slope that gradient descent needs is an average over all the training examples. We can compute it exactly, or estimate it from a small random sample and take a step right away. This lesson is about the second choice: stochastic gradient descent, the version that trains nearly every neural network.
The cost of an exact step
P1.F1 said that training means minimizing the average loss over the data. With examples, and the loss on example ,
The second equation holds because the gradient of a sum is the sum of the gradients (P1.C5). So one step of full-batch gradient descent (P1.F3) needs the gradient of every example. With examples, one step means a million per-example gradients, and training takes thousands of steps. That is billions of gradient computations, to move the parameters a tiny distance each time.
The idea: estimate the average from a few examples
Pick a random batch of examples, average only their gradients, and step:
The only change from P1.F3 is that the exact gradient is replaced by an estimate . The batch size gives the three names:
- : full-batch gradient descent. No randomness.
- : stochastic gradient descent (SGD) in the strict sense: one random example per step.
- : mini-batch gradient descent. Typical values are 32 to a few thousand.
In deep learning, “SGD” almost always means the mini-batch version. In PyTorch, torch.optim.SGD just applies the update rule to whatever gradient it is given. The batch size is set by the data loader, not by the optimizer.
Averaging a random sample to estimate a quantity is the Monte Carlo idea of P1.D9: the batch gradient is a Monte Carlo estimate of the full gradient.
A small example you can check by hand
Take the model and the three data points from P0.2, and stand at . The errors are , and the loss is . The gradient of one example is for error (P1.C4), so the three per-example gradients are:
- example :
- example :
- example :
Their average is the full gradient, , the same numbers as in P1.C5. Now use batches of . There are only three possible pairs, and each gives a different estimate:
- examples 1 and 2:
- examples 1 and 3:
- examples 2 and 3:
No single estimate is right. But their average is : exactly the full gradient. That is what it means for the estimate to be unbiased: if you could average over all the batches you might draw, you would get the true gradient. Each estimate points roughly the right way (all three have negative entries, like the true gradient), but with different lengths.
One step with shows the noise. The full gradient moves to and lowers the loss from 6 to 0.83. The pair (1, 2) moves it to and the loss becomes 2.9, the pair (1, 3) gives loss 1.74, and the pair (2, 3) gives 2.20. A single example can mislead badly: example 3 alone moves to , where the loss is 14, higher than before. The steps are noisy, and an individual step can go uphill, but the average direction is the true one.
The code cell below reproduces all of this.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
How good is the estimate?
Three facts make mini-batches work. Write for the variance of one example’s gradient (one coordinate of it) across the data (P1.D4).
1. Unbiased. If every example is equally likely to be in the batch, then , by linearity of expectation (P1.D4). The example above is this fact in miniature. It needs the sampling to be uniform. If the data file is sorted (all cats, then all dogs) and you cut it into consecutive batches, the batches are not representative and the estimate is biased. That is one reason to shuffle (P1.D9, P1.D5).
2. The noise shrinks like . If the examples are drawn independently, the batch average has variance , so its spread is (P1.D4, P1.D8). Compared with one example:
- : noise , the full single-example noise
- : half of it
- : one quarter
- : one eighth
- : one sixteenth
To halve the noise you need four times the batch. The independence condition holds exactly when drawing with replacement, and approximately when is much larger than . With the three-point example and , the spread of the -part of the estimate drops from for a single example to with replacement. The three pairs above have instead, because drawing without replacement is smarter: the two examples cannot repeat. The variance is multiplied by , which is here. When is small next to , that factor is close to 1 and the simple formula is fine. At it is : no noise at all.
3. A step costs about gradient computations. So noise falls with while cost grows with : the first few examples in a batch buy a lot of accuracy, and later ones buy less and less.
Epochs, iterations and shuffling
One iteration (or step) uses one batch. One epoch is one pass through the whole data set. With examples and batch size :
The usual recipe, used by PyTorch’s data loader when you ask it to shuffle, is to put the examples in a new random order at the start of every epoch and cut that order into consecutive batches. Every example is used exactly once per epoch. This is sampling without replacement within an epoch (P1.D9), and it is often a little better than drawing independently. If is not a multiple of , the last batch is smaller. For and there are 3,906 full batches and one batch of 64; many programs keep it, others drop it.
For the data in the widget below, . With one epoch is 8 steps, and 20 epochs are 160 steps. With the same 20 epochs are 640 steps, and with they are 20.
Full-batch against SGD
The widget fits a line to 32 made-up points. The contour map is the average loss over the two parameters and (each oval is a set of points with the same loss, as in P1.F3). The diamond is the exact minimum. Both methods start from the same ring and are given the same number of examples to process, so the cost is equal: full-batch spends all 32 examples on each step, SGD spends . The comparison is fair for equal , but full-batch could use a larger one (it is stable up to about ). With 20 steps, ends from the minimum and ends away, still far from it. The distance is dominated by the flat valley direction, so the loss comparison below is the better yardstick.
Things to try. Each of these was checked by running the widget’s own code:
- The default. , , 20 epochs, seed 1. Full-batch has made 20 steps and is still from the minimum. SGD has made 160 steps and ended away (over seeds 1 to 20 the median is ). The loss chart shows why: measured in examples processed, SGD’s curve drops much faster at first. To get the loss within of its minimum, full-batch needs 640 examples (20 epochs) and SGD with needs 88.
- (all). The two paths are identical. With the whole data set in every batch, SGD is full-batch gradient descent.
- . The pink path is much more jagged. With seed 1 and it ends from the minimum. Move the seed slider: the final distance changes with the seed, and the readout summarizes seeds 1 to 20 (median , from to ). A single run of a random method is one draw, so report the spread over several seeds (P1.D13).
- A big step size. Set . On this loss, full-batch gradient descent is stable below , so with it converges. With every one of the 20 seeds diverges. Noise lets SGD blow up at a smaller than full-batch, here by a wide margin.
- Decay the step size. Set , , 40 epochs. With a constant the final distance is . Tick the decay box and it is .
- Draw with replacement. Each batch is now independent random draws. With this is no longer full-batch (some examples repeat and others are missed), so the paths differ.
Why SGD hovers instead of settling
At the exact minimum of the full loss, the full gradient is zero. But the batch gradients are not: each example’s own loss has its own slope there, and a batch sees only some of them. So SGD with a constant step size keeps being kicked, and it hovers in a noise ball around the minimum instead of settling at it. The widget shows it: after SGD arrives, the pink path keeps wandering.
Two things shrink the ball:
- A smaller . Smaller kicks.
- A larger . Less noise in each kick.
For independent draws and a small , the typical squared distance from the minimum is proportional to . On this data set with replacement, the squared distance divided by stayed between and across from to and from 1 to 16 (8 seeds each), and a calculation from the gradients at the minimum predicts for small . With shuffled epochs, which the widget uses by default, the ball is usually smaller still at the same and , so use the widget for the direction of the effect, not for this exact law. Full-batch gradient descent has no such ball, which is why it keeps improving if you run it long enough. After 200 epochs (longer than the widget allows) its loss is above the minimum, while SGD with and sits about above it on average (seed 1: ; across 20 seeds to , each averaged over the last 50 of 200 epochs, though single steps are sometimes much closer and sometimes much worse).
Go deeper Where the noise-ball law comes from
Take one parameter, a bowl with curvature , and noisy slopes whose noise has variance and is independent from step to step. The distance from the minimum then follows , where is the noise. Once the process settles, its variance satisfies , so
which for small is about
The variance is proportional to , which is the law above. With many parameters the same happens along every direction of the bowl, with its own . This is for independent noise of fixed size. Real losses have noise that depends on where you are, and shuffling makes the noise within an epoch dependent, so treat as a guide.
Letting SGD settle: decaying the step size
If the ball size is proportional to , shrink as training goes on. Early on, large steps make fast progress; later, small steps shrink the wobble. That is a learning-rate schedule. The widget’s decay option (applied to both methods) uses , where is the number of epochs so far: at epoch 12 the step is .
Shrinking too fast has a cost. If the steps become tiny before SGD has arrived, it makes slow progress and may not arrive by the end of training. With , and 40 epochs, the decayed run ends from the minimum while the constant-step run ends away. Choosing a schedule is a real design decision, treated in P4.14.
Go deeper The Robbins–Monro conditions
In 1951 Robbins and Monro studied stochastic approximation and gave conditions on the step sizes under which noisy-gradient iterations settle on the right answer:
The first says the steps are big enough in total to reach any distance, so the method cannot stall too early. The second says the noise they inject adds up to a finite amount, so the wobble dies out. A step of size satisfies both. Under these conditions and further assumptions on the loss (convex, smooth, noise of bounded variance), the iterates converge to the minimum. Deep-learning practice rarely follows these conditions exactly. Schedules that decay to a small value, not to zero, are common.
The trade-offs of batch size
Small batches. Each step is cheap and noisy, and you take many steps per epoch. Memory use is low. The noise can be a nuisance (a bigger wobble, a smaller safe ) and can also be useful (below).
Large batches. Each step is cleaner and costs more. You take fewer steps per epoch, and doubling does not double the progress per step once the noise is already small: remember the diminishing returns.
Wall-clock time is not the number of gradient computations. A GPU does many examples at once, so a step on 64 examples often takes about as long as a step on 8, because the hardware is not yet full. Past some size the time per step grows roughly in proportion to . That is why moderate batches are often the cheapest way to use the hardware, and why the best batch size depends on the machine.
Memory. Backpropagation (P4.8) stores values for every example in the batch, so memory grows with . A batch that does not fit simply cannot be used, and that is often what sets the upper limit.
Generalization. Some well-known experiments found that very large batches reached a worse test accuracy than small ones, and one explanation proposed was that the noise of small batches steers training to flatter minima (Keskar and others, 2016). Later work (Goyal and others, 2017) showed that, on ImageNet, much of the gap disappears when the learning rate is scaled with the batch size and increased gradually at the start. So treat “small batches generalize better” as an observation that held in some settings, not as a rule. P4.24 returns to generalization.
Escaping bad spots. The noise can kick the ball off a saddle (P1.F2) or out of a shallow valley, where exact gradient descent could sit. This tends to help. It is not guaranteed, and the noise in real mini-batches is not the same in every direction. The last code cell on this page shows the effect with noise added by hand.
Habits. Batch sizes are usually powers of two (32, 64, 128, and so on). That is a convention that fits memory and hardware, not a mathematical requirement. Batch size and step size interact: a larger batch has less noise, so it tolerates a larger before the wobble or divergence gets bad. A common heuristic, stated by Goyal and others for one family of image models, is to multiply by when the batch is multiplied by , with a gradual start (warmup). It is a rule of thumb that breaks down for very large batches, and other optimizers may need other rules. It fits with the law above: keeping fixed keeps the noise ball the same size. P4.14 and P4.23 cover choosing both in practice.
Go deeper Gradient accumulation and data parallelism
If the batch you want does not fit in memory, split it into smaller pieces (micro-batches), compute the gradient of each, and add them up before taking one step. Dividing each piece’s loss by makes the sum equal the average over the full batch. With equal pieces the result matches the big-batch gradient up to rounding; with unequal pieces you must weight by size, or the result is slightly off. Layers whose output depends on the whole batch, such as batch normalization (P4.19), see only the micro-batch, so the match is not exact for them.
for k, (xb, yb) in enumerate(loader):
loss = loss_fn(model(xb), yb) / 4 # 4 micro-batches per step
loss.backward() # gradients add up in .grad
if (k + 1) % 4 == 0:
opt.step()
opt.zero_grad()Data parallelism uses the same fact across machines. A global batch is split across devices, each computes the gradient of its share, and the shares are averaged before the update. The result is the gradient of the whole batch. Very large language models use global batches of millions of tokens; the GPT-3 paper lists 3.2 million tokens for its largest model. How the devices talk to each other is the subject of P10.B6.
Momentum (P1.F5) comes from the same noise problem: it averages recent gradients so the zig-zag cancels. Adam (P4.13) also builds on mini-batch gradients.
The recipe in one place
Intuition
You are in the fog from P1.F3 again, but now your slope meter is a bit shaky. Instead of reading the slope from a map of the whole mountain (slow), you glance at a few rocks near you (fast) and step downhill by what they say. Each glance is off a little, but the errors point in random directions, so over many steps they cancel and you still head down. Near the bottom the shaky meter keeps you stumbling around the lowest point rather than standing on it. Looking at more rocks, or taking smaller steps, steadies you.
Math
Let and . For a batch of indices drawn uniformly,
For independent draws, each coordinate of has variance with the variance of that coordinate of over the data. Without replacement the variance is multiplied by . The update is . Steps per epoch are . With a schedule, Robbins–Monro asks for and .
Code
# the standard PyTorch loop (P2.7): one optimizer step per batch
loader = torch.utils.data.DataLoader(data, batch_size=64, shuffle=True)
opt = torch.optim.SGD(model.parameters(), lr=0.05)
for epoch in range(20):
for xb, yb in loader: # a new random order each epoch
loss = loss_fn(model(xb), yb) # loss on this batch
opt.zero_grad()
loss.backward() # gradient of the batch loss
opt.step() # theta <- theta - lr * gradientThe batch size lives in DataLoader. opt.step() just uses whatever gradient the batch left in .grad.
Try it in code
The first cell runs full-batch gradient descent and mini-batch SGD on the same 32 points as the widget. It uses NumPy’s random numbers, so its numbers are not the widget’s, but the pattern is the same: SGD processes the same 640 examples in more, smaller steps.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The second cell shows noise acting on a saddle (P1.F2). On , exact gradient descent that starts at stays on the line and slides into the saddle at the origin. Here we add a small random number to every gradient by hand, standing in for the noise of mini-batches.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
With noise, grows without limit: has no minimum, so the ball runs away downhill and does not find a lower valley. A real loss has other terms that bend it back up, so this shows only that noise leaves the saddle.
Misconceptions
Check your understanding
You raise the batch size from 64 to 256, drawing examples independently. How does the noise of the batch gradient change?
The noise is σ/√B. Four times the batch gives 1/√4 = 1/2 of the noise. A quarter would need sixteen times the batch, and the noise is zero only for the full data set drawn without replacement.
What does it mean that the mini-batch gradient is unbiased?
Unbiased is a statement about the average over random batches, as the three pairs in the worked example showed. Individual batch gradients differ, they carry noise, and a single step can even raise the loss.
SGD with a constant step size hovers around the minimum. Which change does NOT make the hovering smaller?
The noise ball is set by η and B. Running longer with the same η and B only keeps the ball wandering at the same size. A smaller η, a larger B and a decaying η all reduce the kicks.
A data set has N = 1,000 examples. You train for 10 epochs with batch size 50. How many parameter updates happen?
One epoch is N/B = 1000/50 = 20 steps, so ten epochs are 200 steps. The count of 10 is the number of epochs, 20 is the number of steps in one epoch, and 500 would come from multiplying the epochs by the batch size.
In the widget you pick B = 32 (all) with “Draw with replacement” unticked. How does SGD compare with full-batch gradient descent?
With B = N every batch contains all the examples, so the batch gradient is the full gradient and no randomness remains. Noise, a speed difference and an earlier divergence all need smaller batches.
Exercises
- With the three-point example at , find the mini-batch gradient for the pair of examples and .
Show answer
The average of and is . - A data set has examples and you use . How many steps are in one epoch, and how many in 30 epochs?
Show answer
steps per epoch, so steps. - A single example’s gradient has noise (spread) 8. What is the spread of a batch average for and for , with independent draws?
Show answer
and . Quadrupling the batch halved the noise. - With the decay rule and a starting , what is the step size after 12 epochs?
Show answer
. - You want an effective batch of 256 but only 64 examples fit in memory. Describe a way to do it, and say what to divide each loss by.
Show answer
Run 4 micro-batches of 64, let their gradients add up, and take one optimizer step. Divide each micro-batch loss by 4 so the sum is the average over 256. - In the widget, set B to 1, then to 32, with . What do you see, and what does it say about step size and noise?
Show answer
With the step is below the full-batch limit of , so it converges. With the noisy steps make it diverge. Noise lowers the largest safe step size, so small batches need smaller .
Next: P1.F5 adds momentum, which averages recent gradients to smooth out noise like this, and adaptive steps. P1.F6 uses curvature to pick better steps, and P4.14 returns to learning-rate schedules and batch-size rules in practice.