Concept units

Minibatches: a few examples per step

Intermediate

Read these first if they are new to you

The idea in one paragraph

The loss of a model is an average over all its training examples. Computing its exact gradient means running every example through the model, which is far too slow when there are millions of them. So each training step picks a small random set of examples, called a minibatch, and uses the gradient of their average loss instead. That gradient is noisy, but it points the right way on average. Many cheap, noisy steps reach a good model much sooner than a few exact, expensive ones.

A small random batch estimates the full gradient

In gradient descent, each step moves a weight w against the gradient g of the loss: w ← w − η × g, where η is the learning rate. The loss is the average of one loss per training example. So its gradient is also an average: the average of the gradients of the single examples.

An average over a million numbers can be estimated from a few of them, picked at random. A minibatch (or just batch) is that random pick. The number of examples in it is the batch size, often between 16 and 1,024. Training with minibatches is called stochastic gradient descent, or SGD; "stochastic" means "random".

Worked example: ten examples, batches of two

Take ten training examples whose targets are y = 1, 2, 3, …, 10. The model is a single number w, and the loss for one example is (w − y)². Its gradient is 2(w − y). Start at w = 0.

  1. The full gradient uses all ten examples. The average target is 5.5, so the gradient is 2 × (0 − 5.5) = −11.
  2. A batch of two, the examples with targets 2 and 4, gives 2 × (0 − 3) = −6.
  3. The batch {9, 10} gives 2 × (0 − 9.5) = −19. The batch {3, 8} gives exactly −11.

Every batch gives a negative gradient, so every step moves w up, toward the targets. The sizes vary. Averaged over all 45 possible pairs, the batch gradient is exactly −11, the full gradient. Statisticians call such an estimate unbiased.

Your turn. What gradient does the batch {1, 6} give? (Answer: 2 × (0 − 3.5) = −7.)

Bigger batches are less noisy, but each step costs more

How far a batch gradient lands from the full gradient shrinks as the batch grows. The spread falls with the square root of the batch size: a batch 100 times bigger is 10 times less noisy, and 100 times more work per step. The snippet below measures this on 100,000 made-up examples. It uses a NumPy array and the "spread" of the mean and spread unit.

batch_noise.py

import numpy as np

rng = np.random.default_rng(0)
y = rng.normal(5.0, 2.0, size=100_000)   # one target number per example
w = 0.0                                   # the current weight

full = np.mean(2 * (w - y))               # gradient over all examples
print(f"full gradient: {full:.2f}")

for B in [1, 10, 100, 1000]:
    # y[...] takes the examples at B random positions: one random batch.
    est = [np.mean(2 * (w - y[rng.integers(0, len(y), B)]))
           for _ in range(2000)]          # 2000 random batches of size B
    # {B:4d} pads the whole number B to 4 characters, so the columns line up.
    print(f"batch size {B:4d}: average {np.mean(est):6.2f}, spread {np.std(est):.2f}")
full gradient: -10.00
batch size    1: average -10.05, spread 3.98
batch size   10: average -10.03, spread 1.24
batch size  100: average -10.02, spread 0.39
batch size 1000: average -10.00, spread 0.13

Every batch size gets the average right. Each tenfold increase in batch size cuts the spread by about 3.2, which is √10.

Noisy steps still find the bottom

The figure fits a straight line y = ax + b to 200 points. The rings are lines of equal loss, like the contour lines of a valley on a map. The best (a, b) sits at the center. Each dot is one step of 30, all with the same learning rate, 0.5.

Predict first. With a batch of 1, will the path still get near the center in 30 steps? Then pick each batch size in turn. Find the smallest batch size whose path ends close to the center most times you press "New random batches".

Thirty training steps, each using one random batch

Final loss after 30 steps.

What to notice. With all 200 examples, the path is smooth. With small batches, it zigzags, because each batch points a slightly different way. Yet small batches still reach the middle, and each of their steps costs a small fraction of a full pass.

An epoch is one pass through the data

In practice, the program shuffles the training examples into a random order and then cuts that order into consecutive batches. One full pass through all the examples is an epoch. Training usually runs for many epochs, with a new shuffle each time. Each batch processed is one step (also called an iteration).

Worked example: steps per epoch

A training set has 1,000,000 examples, and the batch size is 256. Then 1,000,000 ÷ 256 = 3,906.25. So one epoch is 3,906 full batches plus one last batch of 64 examples: 3,907 steps. Some programs drop that short last batch, giving 3,906 steps.

This is a simplification

The snippet and the figure drew each example in a batch at random from all examples, putting it back each time, so one batch can even hold the same example twice. Shuffling once per epoch and walking through the order draws without putting examples back, so batches within an epoch never repeat an example. The estimate behaves almost the same. Also, the best learning rate depends on the batch size: bigger batches often allow bigger steps. This unit holds the learning rate fixed to keep one idea in view.

Check yourself

  1. Using the ten examples above (y = 1 to 10, w = 0), which batch of two gives the gradient closest to zero, and what is it?

    Answer

    The batch {1, 2}: 2 × (0 − 1.5) = −3. Smaller targets give a smaller pull, because w = 0 is already close to them.

  2. A batch of 16 gives a gradient whose spread is 2.0. Roughly what spread would a batch of 64 give?

    Answer

    About 1.0. The batch is 4 times bigger, and the spread falls with the square root of the batch size, √4 = 2.

  3. A training set has 50,000 examples and the batch size is 128. How many steps are in one epoch if the program keeps the last short batch?

    Answer

    50,000 ÷ 128 = 390.6, so 390 full batches and one batch of 80 examples: 391 steps.

Go further

Optional background, for readers who want more depth.

Where this shows up

Units that build on this one