Batch, Stochastic and Mini-Batch Gradient Descent
The training loss is an average over the whole training set, , so its exact gradient needs a pass over all examples. With a million images, that is one update per hour. The three classic variants of gradient descent differ only in how many examples they look at before taking a step, and that one choice trades the accuracy of each step against the number of steps you can afford. This lesson implements the three as one function with a batch argument, measures the noise of the gradient estimate, and shows why the noisy versions need a decaying learning rate. Gradient Descent and the Learning Rate covers the basic update; Batch Size, Iterations and Epochs the vocabulary.
Three estimates of the same gradient
At every step, pick a set of example indices and use the average gradient over :
| Variant | Updates per epoch | Each step | |
|---|---|---|---|
| batch (full-batch) GD | 1 | exact gradient, expensive | |
| stochastic GD (SGD) | 1 | very noisy, very cheap | |
| mini-batch GD | typically 16 to 1024 | a compromise; uses vector hardware well |
If is drawn at random, is an unbiased estimate: its expected value is the true gradient . Its error shrinks with the batch size. For a batch drawn with replacement, the variance of the average of independent per-example gradients is
(In practice libraries take each epoch's batches from a shuffled order, without replacement, which is slightly less noisy still.) In the deep-learning world "SGD" usually means mini-batch SGD; torch.optim.SGD does not know or care how big your batch is.
Measuring the noise
Linear regression with 1000 examples and 5 features. At , compare the full gradient with 2000 random mini-batch estimates of each size:
import numpy as np
rng = np.random.default_rng(0)
n, d = 1000, 5
X = rng.normal(size=(n, d))
y = X @ np.array([2.0, -1.0, 0.5, 0.0, 3.0]) + rng.normal(0, 0.5, n)
w = np.zeros(d) # look at the gradient at one fixed point
per_example = X * (X @ w - y)[:, None] # gradient of each example's loss, shape (n, d)
full = per_example.mean(axis=0)
print("full-batch gradient:", np.round(full, 3))
print(" batch mean squared error of the estimate x batch")
for B in [1, 4, 16, 64, 256]:
est = np.array([per_example[rng.integers(0, n, B)].mean(axis=0) for _ in range(2000)])
err = np.mean(np.sum((est - full) ** 2, axis=1))
print(f"{B:6d} {err:10.3f} {err * B:20.2f}")full-batch gradient: [-1.954 0.874 -0.383 0.04 -2.847]
batch mean squared error of the estimate x batch
1 81.884 81.88
4 20.966 83.86
16 4.901 78.42
64 1.223 78.28
256 0.316 80.81
The mean squared error of the estimate falls from 81.9 for single examples to 0.316 for batches of 256, and the last column, error times batch size, stays near 80: the law. So the standard deviation of the estimate only halves when the batch grows four times. A batch of 256 costs 256 times as much as a single example but is only 16 times as accurate, which is why many cheap noisy steps often beat a few exact ones.
All three on one problem
One function, three batch sizes, the same budget of 5 epochs (5000 example-gradients each). The excess loss is the training loss minus the best possible (the least-squares solution's); learning rates were picked to work well for each variant.
import numpy as np
rng = np.random.default_rng(0)
n, d = 1000, 5
X = rng.normal(size=(n, d))
w_true = np.array([2.0, -1.0, 0.5, 0.0, 3.0])
y = X @ w_true + rng.normal(0, 0.5, n)
w_best = np.linalg.lstsq(X, y, rcond=None)[0]
loss = lambda w: np.mean((X @ w - y) ** 2) / 2
best = loss(w_best)
def minibatch_gd(batch, lr, epochs, decay=0.0, seed=0):
r = np.random.default_rng(seed)
w, updates, history = np.zeros(d), 0, []
for epoch in range(epochs):
order = r.permutation(n) # reshuffle every epoch
for start in range(0, n, batch):
idx = order[start:start + batch]
g = X[idx].T @ (X[idx] @ w - y[idx]) / len(idx)
w -= lr / (1 + decay * updates) * g # decay=0: constant step
updates += 1
history.append(loss(w) - best)
return w, updates, history
for name, batch, lr, decay in [("batch GD", n, 0.5, 0), ("SGD", 1, 0.01, 0), ("SGD, decaying", 1, 0.01, 0.002),
("mini-batch 32", 32, 0.05, 0)]:
w, updates, hist = minibatch_gd(batch, lr, epochs=5, decay=decay)
print(f"{name:14s} updates {updates:5d} excess loss after epochs 1..5:", " ".join(f"{h:.1e}" for h in hist))
print("optimal loss (noise floor):", round(best, 4))batch GD updates 5 excess loss after epochs 1..5: 1.8e+00 5.1e-01 1.4e-01 3.9e-02 1.1e-02
SGD updates 5000 excess loss after epochs 1..5: 2.8e-04 1.6e-03 3.7e-03 8.3e-04 4.5e-03
SGD, decaying updates 5000 excess loss after epochs 1..5: 3.2e-04 1.0e-04 4.8e-05 2.5e-05 1.3e-05
mini-batch 32 updates 160 excess loss after epochs 1..5: 2.8e-01 1.0e-02 3.2e-04 7.2e-05 1.2e-04
optimal loss (noise floor): 0.1236
- Batch GD made only 5 updates. Each was exact, and the excess loss falls steadily by a factor of about 3.5 per epoch, but after 5 epochs it is still 0.011.
- SGD with a constant learning rate gets close almost at once (excess 2.8e-04 after one epoch) and then stops improving: it jumps around the minimum, between 2.8e-04 and 4.5e-03, because every step follows one example's noisy gradient. With a constant , SGD converges only to a noise ball whose size is proportional to .
- SGD with a decaying learning rate, , starts the same and keeps improving to 1.3e-05. Shrinking steps average the noise away.
- Mini-batch 32 made 160 updates, each 32 times less noisy than an SGD step, and reaches 7.2e-05 to 1.2e-04. On real hardware its 160 vectorised updates are also far faster than SGD's 5000 tiny ones.
The decaying schedule is not an accident. The classic Robbins-Monro conditions for SGD to converge are
steps large enough in total to travel anywhere, but shrinking fast enough for the noise to average out; satisfies both. Convergence rates are derived in Stochastic Gradient Methods and SGD Convergence. Deep-learning practice uses learning-rate schedules such as step decay or cosine for the same reason.
Choosing the batch size
- Hardware first. On a GPU a batch of 64 often takes about as long as a batch of 8, so small batches waste the device. The upper limit is memory: activations for the whole batch must fit.
- Large batches need a larger learning rate. Less noise per step allows bigger steps. The linear scaling rule (Goyal et al., 2017) multiplies the learning rate by when the batch grows by , with a warm-up at the start; it holds up to a point, then stops helping.
- Noise can help generalisation. Very large batches have been observed to generalise somewhat worse at the same number of epochs unless the learning rate and schedule are retuned; the noise of small batches acts as a mild regulariser. Treat batch size and learning rate as one joint hyperparameter.
- Shuffle every epoch. Batches taken in a fixed order (all of class A, then all of class B) give biased gradients and a loss curve that oscillates with the epoch.
Mini-batch SGD and its noise are the subject of the Mathematics lesson Mini-Batch SGD; the next lessons add momentum and per-parameter step sizes on top of it.
Pitfalls
- A last batch of a different size. With 1000 examples and batches of 32, the last batch has 8 examples. Averaging (not summing) keeps the gradient scale the same; PyTorch's
DataLoader(drop_last=True)drops it instead. - Judging SGD by its last value. The final iterate of constant-step SGD is one sample from the noise ball. Decay the learning rate, or average the last iterates.
- Comparing variants per update. One batch-GD update costs example-gradients; compare at equal compute (epochs or wall-clock time), as the example does.
Practice
- A data set has 50,000 examples. How many updates do 10 epochs make with batch sizes 1, 100 and 50,000?
Answer
500,000, 5,000 and 10.
- With per-example gradient variance , which batch size gives an estimate whose mean squared error is about 1?
Answer
gives . The table above (1.223 at 64) agrees.
- Does satisfy the Robbins-Monro conditions?
Answer
diverges (good), but also diverges, so the second condition fails. It is still a common practical choice (it gives the optimal rate for some convex problems with iterate averaging), but on its own it does not drive the noise to zero as fast.
Test yourself
How does the mean squared error of a mini-batch gradient estimate change when the batch size is multiplied by 4?
- It is divided by 16
- It is divided by 4
- It is divided by 2
- It does not change
With a constant learning rate, plain SGD (batch size 1) typically…
- converges exactly to the minimum
- gets close quickly, then fluctuates in a region around the minimum whose size grows with the learning rate
- diverges
- behaves exactly like batch gradient descent
Which statement about the mini-batch gradient with randomly chosen examples is true?
- Its expected value is the full gradient
- It is always smaller than the full gradient
- It is the gradient of a different loss
- It is exact when the batch has 32 examples
The linear scaling rule says that when you multiply the batch size by you should…
- divide the learning rate by
- multiply the learning rate by (with a warm-up)
- keep the learning rate
- multiply the number of epochs by