TExcelTAD
Home › Math for Deep Learning & LLMs › Mini-Batch SGD

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 L(θ)=1N∑iℓi(θ)\mathcal{L}(\boldsymbol{\theta}) = \frac{1}{N}\sum_i\ell_i(\boldsymbol{\theta}) and a batch B\mathcal{B} of size BB sampled uniformly,

g^=1B∑i∈B∇ℓi,E[g^]=∇L,Cov⁡(g^)≈ΣB\hat{\mathbf{g}} = \frac{1}{B}\sum_{i \in \mathcal{B}}\nabla\ell_i, \qquad \mathbb{E}[\hat{\mathbf{g}}] = \nabla\mathcal{L}, \qquad \operatorname{Cov}(\hat{\mathbf{g}}) \approx \frac{\Sigma}{B}

where Σ\Sigma is the covariance of per-example gradients. The noise standard deviation falls like 1/B1/\sqrt{B}: 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, ⌈N/B⌉\lceil N/B \rceil steps. Shuffling every epoch keeps batches unbiased; sampling without replacement within an epoch also slightly reduces variance compared with independent sampling.

python · try it yourself
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 BB, as 1/B1/\sqrt{B} predicts.

Batch size and learning rate

SGD with learning rate η\eta and batch BB behaves, to first order, like gradient descent plus noise of size proportional to η/B\eta/\sqrt{B}; over many steps what matters is roughly the ratio η/B\eta/B. Hence the linear scaling rule: when multiplying the batch size by kk, multiply the learning rate by kk (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 (η∝B\eta \propto \sqrt{B}) is often closer.

python · try it yourself
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 η/B\eta/B 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

N=1,281,167N = 1{,}281{,}167 images (ImageNet) and B=256B = 256. How many steps per epoch?

Answer
Solution

1,281,167/256=5004.61{,}281{,}167/256 = 5004.6, rounded up to 5005 (the last batch is partial).

Exercise 2: Linear scaling

A recipe uses B=256B = 256, η=0.1\eta = 0.1. What learning rate does the linear scaling rule suggest for B=8192B = 8192?

Answer

3.23.2.

Solution

k=8192/256=32k = 8192/256 = 32, so η=3.2\eta = 3.2, 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
python · try it yourself
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…

  1. 1/B1/B
  2. 1/B1/\sqrt{B}
  3. BB
  4. it does not depend on BB

The linear scaling rule says that when the batch size grows by kk…

  1. the learning rate should shrink by kk
  2. the learning rate should grow by kk
  3. the number of epochs should grow by kk
  4. nothing changes

Gradient accumulation is used to…

  1. add noise
  2. simulate a batch larger than fits in memory
  3. speed up each step
  4. replace backpropagation