TExcelTAD
Home › Training Mechanics, Evaluation & Model Improvement › Batch Size, Iterations and Epochs

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 BB examples used to compute one gradient
batch size BB 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 nn training examples

With nn examples and batch size BB, one epoch has

steps per epoch=⌈nB⌉,\text{steps per epoch} = \left\lceil \frac{n}{B} \right\rceil ,

and the last batch is smaller when BB does not divide nn (PyTorch's DataLoader(drop_last=True) drops it instead). The extremes have names: B=nB = n is batch (full-batch) gradient descent, B=1B = 1 is stochastic gradient descent, everything between is mini-batch; the optimizer lessons compare the three.

python · try it yourself
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 B=1B = 1 and only 10 with B=1000B = 1000. "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, L(w)=1n∑iℓi(w)L(\mathbf{w}) = \frac{1}{n} \sum_i \ell_i(\mathbf{w}), and so is its gradient. A mini-batch gradient averages over a random subset B\mathcal{B} of size BB:

gB=1B∑i∈B∇ℓi(w),E[gB]=∇L(w).\mathbf{g}_B = \frac{1}{B} \sum_{i \in \mathcal{B}} \nabla \ell_i(\mathbf{w}), \qquad \mathbb{E}[\mathbf{g}_B] = \nabla L(\mathbf{w}) .

It is an unbiased estimate of the true gradient, with noise. If the per-example gradients have covariance Σ\Sigma, the batch average has covariance Σ/B\Sigma / B (sampling with replacement), so the typical error shrinks like 1/B1/\sqrt{B}: four times the batch, half the noise. Sampling without replacement from a finite set is slightly less noisy, by the factor 1−B/n\sqrt{1 - B/n} (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.

python · try it yourself
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 1/B1/\sqrt{B} law. At B=512B = 512 it dips because 512 is an eighth of the data: 1.453⋅1−512/4096≈1.361.453 \cdot \sqrt{1 - 512/4096} \approx 1.36. Note that with B=8B = 8 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 η gB\eta \, \mathbf{g}_B. Over one epoch a batch size of BB gives n/Bn/B 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 kk, multiply the learning rate by kk. The update over kk small steps is then roughly the same as one big step, as long as the gradient does not change much within those kk steps.

Five epochs of mini-batch logistic regression, scored by log-loss on 512 held-out examples:

python · try it yourself
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 BB no longer halves the number of steps needed. For Adam, a square-root rule (η∝B\eta \propto \sqrt{B}) is a common starting point.

Choosing a batch size

  • Memory sets the ceiling. Activations stored for backpropagation grow linearly with BB. 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 BB times larger than the mean; the learning rate silently changes with BB. 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=True some 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

  1. A data set has 50 000 examples. With B=128B = 128, how many steps are in one epoch, how big is the last batch, and how many steps are 30 epochs?
Answer

⌈50000/128⌉=391\lceil 50000/128 \rceil = 391 steps (390 full batches hold 49 920 examples), the last batch has 80 examples, and 30 epochs are 391⋅30=11730391 \cdot 30 = 11730 steps.

  1. With B=32B = 32 the gradient noise is 0.2. Roughly what is it with B=512B = 512 (ignoring the finite-population factor)?
Answer

The noise scales like 1/B1/\sqrt{B}; 512/32=16512/32 = 16, so it drops by 16=4\sqrt{16} = 4 to about 0.05.

  1. A recipe trains a network with B=256B = 256 and η=0.1\eta = 0.1. You have 8 GPUs and want B=2048B = 2048. What learning rate does the linear scaling rule suggest, and what else would you add?
Answer

2048/256=82048 / 256 = 8, so η=0.8\eta = 0.8, 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?

  1. 3
  2. 4
  3. 256
  4. 1000

How does the noise of a mini-batch gradient change when the batch size is multiplied by 4?

  1. It is divided by 4
  2. It is divided by 2
  3. It stays the same
  4. It is multiplied by 2

What does the linear scaling rule say?

  1. Multiply the number of epochs by the batch-size factor
  2. Multiply the learning rate by the same factor as the batch size
  3. Divide the learning rate by the batch-size factor
  4. Keep the learning rate fixed whatever the batch size

What is one iteration (step)?

  1. One pass over the whole training set
  2. One forward pass, backward pass and parameter update on one batch
  3. One evaluation on the validation set
  4. One example