Batch Size, Iterations and Epochs
A training log says "epoch 3/20, step 1450, batch size 64". Three different counters, and people mix them up all the time: a paper reports "trained for 90 epochs", a library argument asks for max_steps, a learning-rate schedule counts one or the other. This lesson pins down the vocabulary, then looks at what the batch size really changes: how noisy each gradient is, how many updates you get per pass over the data, and how the learning rate has to follow.
Definitions
| Term | Meaning |
|---|---|
| batch (mini-batch) | the examples used to compute one gradient |
| batch size | how many examples are in a batch |
| iteration or step | one parameter update: one batch forward, backward and optimizer step |
| epoch | one full pass over the training examples |
With examples and batch size , one epoch has
and the last batch is smaller when does not divide (PyTorch's DataLoader(drop_last=True) drops it instead). The extremes have names: is batch (full-batch) gradient descent, is stochastic gradient descent, everything between is mini-batch; the optimizer lessons compare the three.
import math
n, epochs = 1000, 10
print(" batch steps/epoch last batch total steps")
for B in [1, 32, 100, 256, 1000]:
steps = math.ceil(n / B)
last = n - (steps - 1) * B
print(f"{B:6d} {steps:11d} {last:10d} {steps * epochs:11d}") batch steps/epoch last batch total steps
1 1000 1 10000
32 32 8 320
100 10 100 100
256 4 232 40
1000 1 1000 10
Ten epochs is 10 000 updates with and only 10 with . "Train for 10 epochs" therefore means very different things for different batch sizes, which is why schedules and warm-up are often specified in steps.
What a mini-batch gradient is
The full loss is an average over examples, , and so is its gradient. A mini-batch gradient averages over a random subset of size :
It is an unbiased estimate of the true gradient, with noise. If the per-example gradients have covariance , the batch average has covariance (sampling with replacement), so the typical error shrinks like : four times the batch, half the noise. Sampling without replacement from a finite set is slightly less noisy, by the factor (Stochastic Gradient Descent, SGD and Mini-Batches).
Measure it: fix a weight vector for logistic regression, compute the exact gradient on 4096 examples, then 400 random mini-batch gradients for each batch size.
import numpy as np
from sklearn.datasets import make_classification
X, y = make_classification(n_samples=4096, n_features=10, random_state=0)
w = np.full(10, 0.1) # some point during training
def grad(Xb, yb, w):
p = 1 / (1 + np.exp(-(Xb @ w)))
return Xb.T @ (p - yb) / len(yb) # mean log-loss gradient
g_full = grad(X, y, w)
print(f"full-batch gradient norm {np.linalg.norm(g_full):.4f}")
rng = np.random.default_rng(0)
for B in [8, 32, 128, 512]:
errs = []
for _ in range(400):
idx = rng.choice(len(y), size=B, replace=False)
errs.append(np.linalg.norm(grad(X[idx], y[idx], w) - g_full))
e = np.sqrt(np.mean(np.square(errs)))
print(f"B={B:4d} noise (rms of |g_B - g|) {e:.4f} noise * sqrt(B) {e * np.sqrt(B):.3f}")full-batch gradient norm 0.4440
B= 8 noise (rms of |g_B - g|) 0.5139 noise * sqrt(B) 1.453
B= 32 noise (rms of |g_B - g|) 0.2557 noise * sqrt(B) 1.447
B= 128 noise (rms of |g_B - g|) 0.1277 noise * sqrt(B) 1.444
B= 512 noise (rms of |g_B - g|) 0.0609 noise * sqrt(B) 1.379
The last column is nearly constant, the law. At it dips because 512 is an eighth of the data: . Note that with the noise (0.51) is larger than the gradient itself (0.44): a single small-batch step can point uphill. On average the steps still go downhill, and that noise can even help a network leave sharp minima.
Batch size and the learning rate
Each step moves the weights by about . Over one epoch a batch size of gives steps, so with the learning rate fixed, a bigger batch simply moves less per epoch. The linear scaling rule compensates: multiply the batch size by , multiply the learning rate by . The update over small steps is then roughly the same as one big step, as long as the gradient does not change much within those steps.
Five epochs of mini-batch logistic regression, scored by log-loss on 512 held-out examples:
import numpy as np
from sklearn.datasets import make_classification
X, y = make_classification(n_samples=2048, n_features=10, random_state=0)
X_val, y_val = X[1536:], y[1536:]
X, y = X[:1536], y[:1536]
def logloss(w, X, y):
z = X @ w
return np.mean(np.logaddexp(0, z) - y * z)
def train(B, lr, epochs=5, seed=0):
rng = np.random.default_rng(seed)
w = np.zeros(X.shape[1]); steps = 0
for epoch in range(epochs):
order = rng.permutation(len(y)) # reshuffle every epoch
for start in range(0, len(y), B):
idx = order[start:start + B]
p = 1 / (1 + np.exp(-(X[idx] @ w)))
w -= lr * X[idx].T @ (p - y[idx]) / len(idx)
steps += 1
return steps, logloss(w, X_val, y_val)
for B in [8, 64, 512]:
s1, l1 = train(B, lr=0.05)
s2, l2 = train(B, lr=0.05 * B / 8) # linear scaling from B=8
print(f"B={B:3d} steps {s1:4d} val loss: fixed lr 0.05 {l1:.4f} | scaled lr {0.05 * B / 8:5.2f} {l2:.4f}")B= 8 steps 960 val loss: fixed lr 0.05 0.3326 | scaled lr 0.05 0.3326
B= 64 steps 120 val loss: fixed lr 0.05 0.3703 | scaled lr 0.40 0.3326
B=512 steps 15 val loss: fixed lr 0.05 0.5555 | scaled lr 3.20 0.3327
With the learning rate fixed, the larger batches are far from done after 5 epochs (15 steps is not much training). With the scaled rate all three reach the same validation loss, the big batch in 64 times fewer steps. On a GPU those 15 large steps are much faster than 960 small ones, which is why large-batch training is attractive. The rule has limits: it fails when the scaled rate exceeds the stability limit from the learning-rate lesson (a convex, well-conditioned problem like this one tolerates a lot), and for deep networks it usually needs a warm-up of a few epochs. Beyond a "critical batch size" doubling no longer halves the number of steps needed. For Adam, a square-root rule () is a common starting point.
Choosing a batch size
- Memory sets the ceiling. Activations stored for backpropagation grow linearly with . When the batch you want does not fit, gradient accumulation sums the gradients of several small batches before one optimizer step, giving the same update as a big batch.
- Small batches (8 to 64) give noisy steps that can generalise slightly better and need less memory, but use the hardware poorly.
- Large batches (hundreds to thousands) use parallel hardware well and give smooth curves, but need learning-rate scaling and warm-up.
- Batch normalisation couples the examples of a batch; with tiny batches its statistics are unreliable.
- Reshuffle every epoch, as the code does, so batches differ between epochs. Never batch data sorted by label: every batch would hold one class.
Pitfalls
- Comparing runs by epochs when the batch sizes differ. Report steps too.
- Averaging vs summing. A loss summed over the batch has a gradient times larger than the mean; the learning rate silently changes with . Frameworks use the mean by default.
- Forgetting the partial last batch. Weighting it like a full batch over-counts its few examples a little; with
drop_last=Truesome examples are skipped each epoch (different ones, thanks to shuffling). - Doubling the batch to "go faster" without touching the learning rate: training gets slower per epoch, not faster.
Practice
- A data set has 50 000 examples. With , how many steps are in one epoch, how big is the last batch, and how many steps are 30 epochs?
Answer
steps (390 full batches hold 49 920 examples), the last batch has 80 examples, and 30 epochs are steps.
- With the gradient noise is 0.2. Roughly what is it with (ignoring the finite-population factor)?
Answer
The noise scales like ; , so it drops by to about 0.05.
- A recipe trains a network with and . You have 8 GPUs and want . What learning rate does the linear scaling rule suggest, and what else would you add?
Answer
, so , together with a warm-up over the first few epochs so the large rate is not applied to random initial weights.
Test yourself
A training set has 1000 examples and the batch size is 256. How many optimizer steps does one epoch take?
- 3
- 4
- 256
- 1000
How does the noise of a mini-batch gradient change when the batch size is multiplied by 4?
- It is divided by 4
- It is divided by 2
- It stays the same
- It is multiplied by 2
What does the linear scaling rule say?
- Multiply the number of epochs by the batch-size factor
- Multiply the learning rate by the same factor as the batch size
- Divide the learning rate by the batch-size factor
- Keep the learning rate fixed whatever the batch size
What is one iteration (step)?
- One pass over the whole training set
- One forward pass, backward pass and parameter update on one batch
- One evaluation on the validation set
- One example