Mini-Batch SGD and Gradient Noise
Deep networks are trained with stochastic gradient descent on mini-batches: each step estimates the gradient from a few dozen to a few million examples. The noise in that estimate is not just a nuisance: it decides how the learning rate should scale with the batch size, limits how large a batch is useful, and may help find solutions that generalize. The basic algorithm is in Stochastic Gradient Descent.
The estimator
With a dataset loss and a batch of size sampled uniformly,
where is the covariance of per-example gradients. The noise standard deviation falls like : four times the batch halves the noise but costs four times the compute.
Epochs, steps and shuffling
One epoch is a pass over the data, steps. Shuffling every epoch keeps batches unbiased; sampling without replacement within an epoch also slightly reduces variance compared with independent sampling.
import numpy as np
rng = np.random.default_rng(0)
N = 10000
X = rng.normal(size=(N, 5)); w_true = rng.normal(size=5); y = X @ w_true + rng.normal(0, 1, N)
w = np.zeros(5)
full = 2 * X.T @ (X @ w - y) / N
for B in (1, 16, 256):
ests = []
for _ in range(2000):
idx = rng.integers(0, N, B)
ests.append(2 * X[idx].T @ (X[idx] @ w - y[idx]) / B)
ests = np.array(ests)
print(f"B = {B:3d}: bias {np.abs(ests.mean(0) - full).max():.3f}, noise std {ests.std(0).mean():.3f}")B = 1: bias 0.096, noise std 4.799
B = 16: bias 0.014, noise std 1.220
B = 256: bias 0.006, noise std 0.307
The noise shrinks by about 4 for each 16-fold increase in , as predicts.
Batch size and learning rate
SGD with learning rate and batch behaves, to first order, like gradient descent plus noise of size proportional to ; over many steps what matters is roughly the ratio . Hence the linear scaling rule: when multiplying the batch size by , multiply the learning rate by (with warmup), which keeps training curves per epoch nearly unchanged. It breaks down above the critical batch size, where the gradient noise is already small and bigger batches only waste compute. For Adam-type optimizers a square-root rule () is often closer.
import numpy as np
rng = np.random.default_rng(1)
N = 4096
X = rng.normal(size=(N, 10)); w_true = rng.normal(size=10); y = X @ w_true + rng.normal(0, 0.5, N)
def train(B, lr, epochs=3):
w = np.zeros(10)
for _ in range(epochs):
perm = rng.permutation(N)
for s in range(0, N, B):
idx = perm[s:s + B]
w -= lr * 2 * X[idx].T @ (X[idx] @ w - y[idx]) / len(idx)
return np.mean((X @ w - y)**2)
for B, lr in ((8, 0.002), (32, 0.008), (128, 0.032), (128, 0.002)):
print(f"B = {B:3d}, lr = {lr:.3f}: loss after 3 epochs {train(B, lr):.4f}")B = 8, lr = 0.002: loss after 3 epochs 0.2574
B = 32, lr = 0.008: loss after 3 epochs 0.2574
B = 128, lr = 0.032: loss after 3 epochs 0.2575
B = 128, lr = 0.002: loss after 3 epochs 7.9062
Batch 128 with the small learning rate takes 16 times fewer steps and falls far behind; scaled up linearly it keeps pace.
Gradient accumulation
When a large batch does not fit in memory, run several micro-batches, sum their gradients (divided by the number of micro-batches), and update once. The result is mathematically the same as one big batch (except for batch normalization statistics).
Noise as a regularizer
Small-batch SGD tends to find flatter minima than large-batch training at the same number of epochs, and flatter minima often generalize better (Curvature). The noise scale acts like a temperature.
In software
DataLoader(dataset, batch_size=B, shuffle=True, drop_last=True)produces shuffled mini-batches.- LLM batch sizes are quoted in tokens (often millions per step), reached with data parallelism over many GPUs plus gradient accumulation.
- Distributed data parallel training averages gradients across devices with an all-reduce, which is exactly a larger batch.
Exercises
Exercise 1: Steps per epoch
images (ImageNet) and . How many steps per epoch?
Answer
Solution
, rounded up to 5005 (the last batch is partial).
Exercise 2: Linear scaling
A recipe uses , . What learning rate does the linear scaling rule suggest for ?
Answer
.
Solution
, so , used with several epochs of warmup.
Exercise 3: Accumulation equals a big batch (code)
Show that averaging gradients over 4 micro-batches of 8 equals the gradient of the 32-example batch.
Answer
They are identical.
Solution
import numpy as np
rng = np.random.default_rng(2)
X, y, w = rng.normal(size=(32, 3)), rng.normal(size=32), rng.normal(size=3)
grad = lambda Xb, yb: 2 * Xb.T @ (Xb @ w - yb) / len(yb)
acc = sum(grad(X[i:i + 8], y[i:i + 8]) for i in range(0, 32, 8)) / 4
print(np.allclose(acc, grad(X, y)))True
Test yourself
The standard deviation of a mini-batch gradient estimate scales like…
- it does not depend on
The linear scaling rule says that when the batch size grows by …
- the learning rate should shrink by
- the learning rate should grow by
- the number of epochs should grow by
- nothing changes
Gradient accumulation is used to…
- add noise
- simulate a batch larger than fits in memory
- speed up each step
- replace backpropagation