9.8 Batch Size

In practice, the minibatch size bb is often chosen to fill accelerator memory and then left untouched. Yet the moment we scale training across multiple GPUs, or trade wall-clock training time against total compute FLOPs, we face a fundamental question: if we double the minibatch size bb (doubling the parallel computation per step), does the run reach our target loss in half as many steps?

In Section 9.2, we saw that a minibatch of bb examples reduces the gradient sampling variance to tr⁡(Σ)/b\operatorname{tr}(\boldsymbol{\Sigma})/b. This implies two distinct regimes:

  1. Small-batch (noise-dominated) regime: When sampling noise is larger than the true gradient, doubling bb halves the noise variance, allowing a larger learning rate that cuts the required step count S(b)S(b) in half while keeping total examples processed E(b)=b S(b)E(b) = b\,S(b) constant (perfect linear scaling).
  2. Large-batch (curvature-dominated) regime: Once bb is large enough that the minibatch gradient closely approximates the true full-batch gradient, further increasing bb yields diminishing reductions in S(b)S(b) while multiplying the data and compute cost E(b)E(b) linearly.

McCandlish et al. (2018) showed that the transition between these two regimes occurs at the critical batch size bcritb_{\text{crit}}, which is predicted by the gradient-noise scale bnoise=tr⁡(Σ)/∥∇f∥2b_{\text{noise}} = \operatorname{tr}(\boldsymbol{\Sigma}) / \|\nabla f\|^2. In this section, we build a two-batch estimator for bnoiseb_{\text{noise}}, derive the step-versus-data trade-off frontier and the learning-rate scaling rules for SGD (η∝b\eta \propto b) and Adam (η∝b\eta \propto \sqrt{b}), and test both predictions on TinyLM and FashionCNN.

import random

9.8.1 The Gradient-Noise Scale#

9.8.1.1 Signal, Noise, and a Two-Batch Estimator#

Let ∇f(x)\nabla f(\mathbf{x}) denote the exact full-dataset gradient and g^b\hat{\mathbf{g}}_b denote a minibatch gradient averaged over bb independent examples, with per-example gradient covariance Σ\boldsymbol{\Sigma}. Because E[g^b]=∇f\mathbb{E}[\hat{\mathbf{g}}_b] = \nabla f and E[∥g^b−∇f∥2]=tr⁡(Σ)/b\mathbb{E}[\|\hat{\mathbf{g}}_b - \nabla f\|^2] = \operatorname{tr}(\boldsymbol{\Sigma})/b, the expected squared norm of the minibatch gradient decomposes into signal power ∥∇f∥2\|\nabla f\|^2 plus noise power tr⁡(Σ)/b\operatorname{tr}(\boldsymbol{\Sigma})/b:

E[∥g^b∥2]=∥∇f∥2+tr⁡Σb.(9.8.1)\mathbb{E}\big[\|\hat{\mathbf{g}}_b\|^2\big] = \|\nabla f\|^2 + \frac{\operatorname{tr} \boldsymbol{\Sigma}}{b}. \tag{9.8.1}

The signal power and noise power are equal at the simple gradient-noise scale (McCandlish et al., 2018):

bnoise=tr⁡Σ∥∇f∥2.(9.8.2)b_{\textrm{noise}} = \frac{\operatorname{tr} \boldsymbol{\Sigma}}{\|\nabla f\|^2}. \tag{9.8.2}

We can estimate both tr⁡Σ\operatorname{tr}\boldsymbol{\Sigma} and ∥∇f∥2\|\nabla f\|^2 without a full pass over the dataset by measuring the mean squared gradient norm Nb=E[∥g^b∥2]N_b = \mathbb{E}[\|\hat{\mathbf{g}}_b\|^2] at two batch sizes bs<blb_{\text{s}} \lt b_{\text{l}} and solving the two-by-two linear system (9.8.1):

tr⁡Σ≈Nbs−Nbl1/bs−1/bl,∥∇f∥2≈blNbl−bsNbsbl−bs.\operatorname{tr} \boldsymbol{\Sigma} \approx \frac{N_{b_{\textrm{s}}} - N_{b_{\textrm{l}}}}{1/b_{\textrm{s}} - 1/b_{\textrm{l}}}, \qquad \|\nabla f\|^2 \approx \frac{b_{\textrm{l}} N_{b_{\textrm{l}}} - b_{\textrm{s}} N_{b_{\textrm{s}}}}{b_{\textrm{l}} - b_{\textrm{s}}}.

We first load WikiText-103 and Fashion-MNIST onto the accelerator and define the random minibatch samplers sample_fashion(b) and sample_lm(b):

device = d2l.try_gpu()
data = d2l.WikiText103(batch_size=64, num_steps=64)
fashion = d2l.FashionMNIST(batch_size=256)
X_f = (fashion.train.data.float() / 255).unsqueeze(1).to(device)
y_f = fashion.train.targets.to(device)

def sample_fashion(b):  # b random training images
    i = torch.randint(len(y_f), (b,), device=device)
    return X_f[i], y_f[i]

def sample_lm(b):  # b windows at random offsets in the training text
    starts = torch.randint(len(data.train) - data.num_steps, (b,))
    X, Y = data.windows(data.train, starts.numpy())
    return X.to(device), Y.to(device)
Downloading ../data/wikitext-103/train-00000-of-00002.parquet from https://huggingface.co/datasets/Salesforce/wikitext/resolve/main/wikitext-103-raw-v1/train-00000-of-00002.parquet...
Downloading ../data/wikitext-103/validation-00000-of-00001.parquet from https://huggingface.co/datasets/Salesforce/wikitext/resolve/main/wikitext-103-raw-v1/validation-00000-of-00001.parquet...

Using these samplers, we save the cross-entropy helper ce_loss, the parameter-wide squared gradient norm grad_sq_norm, and the two-batch estimator noise_scale in d2l:

def ce_loss(model, X, Y):
    """Mean cross-entropy of the logits model(X) for the labels Y."""
    logits = model(X)
    return F.cross_entropy(logits.reshape(-1, logits.shape[-1]),
                           Y.reshape(-1))

def grad_sq_norm(model, X, Y):
    """Squared norm of the gradient of ce_loss over all parameters."""
    grads = torch.autograd.grad(ce_loss(model, X, Y),
                                list(model.parameters()))
    return sum((g ** 2).sum() for g in grads)

def noise_scale(model, sample, b_small=16, b_big=2048, m=400):
    """Gradient-noise scale from the mean squared gradient norms of m
    minibatches of size b_small and m // 8 of size b_big from sample(b)."""
    def mean_sq_norm(b, m):  # N_b, averaged over m random minibatches
        return torch.stack([grad_sq_norm(model, *sample(b))
                            for _ in range(m)]).mean()
    n_small, n_big = mean_sq_norm(b_small, m), mean_sq_norm(b_big, m // 8)
    tr_sigma = (n_small - n_big) / (1 / b_small - 1 / b_big)
    sq_norm = (b_big * n_big - b_small * n_small) / (b_big - b_small)
    return (tr_sigma / sq_norm).item()

We now evaluate noise_scale on TinyLM (bs=8,bl=256b_{\text{s}} = 8, b_{\text{l}} = 256) at initialization and again after 500500 steps of Adam (η=3×10−3\eta = 3 \times 10^{-3}):

lm = d2l.TinyLM(len(data.vocab)).to(device)
print(f'noise scale at initialization: '
      f'{noise_scale(lm, sample_lm, b_small=8, b_big=256):.1f}')
optimizer = torch.optim.Adam(lm.parameters(), lr=0.003)
d2l.train_steps(lm, data, optimizer, num_steps=500)
print(f'after 500 steps of Adam: '
      f'{noise_scale(lm, sample_lm, b_small=8, b_big=256):.0f}')
noise scale at initialization: 2.2
after 500 steps of Adam: 93

Does the noise scale of a convolutional network on images grow in the same way? We repeat the measurement on FashionCNN, with the default bs=16b_{\text{s}} = 16 and bl=2,048b_{\text{l}} = 2{,}048 images, at initialization and after 200200 steps of Adam (η=0.004\eta = 0.004, the rate the sweep below uses at b=256b = 256):

cnn = d2l.FashionCNN().to(device)
print(f'noise scale at initialization: {noise_scale(cnn, sample_fashion):.0f}')
optimizer = torch.optim.Adam(cnn.parameters(), lr=0.004)
d2l.train_steps(cnn, fashion, optimizer, num_steps=200)
print(f'after 200 steps of Adam: {noise_scale(cnn, sample_fashion):.0f}')
noise scale at initialization: 64
after 200 steps of Adam: 120

On TinyLM at initialization, every window demands the same coarse unigram adjustment, so the signal ∥∇f∥2\|\nabla f\|^2 is large and bnoise≈2b_{\text{noise}} \approx 2 sequences. Once common byte statistics are learned (by step 500500), ∥∇f∥2\|\nabla f\|^2 drops while inter-sequence variance tr⁡Σ\operatorname{tr}\boldsymbol{\Sigma} persists, causing bnoiseb_{\text{noise}} to grow more than tenfold to ∼50–150\sim 50\text{--}150 sequences.

FashionCNN behaves differently. Its ten classes are balanced, so an untrained network finds no adjustment that every image agrees on, and the noise scale is of the order of 100100 images from the first step. Over the 200200 steps the estimate moves by less than a factor of two, in either direction depending on the run, and stays of the order of 100100 images.

9.8.2 Batch Size, Step Efficiency, and Learning-Rate Scaling#

9.8.2.1 Optimal Step Size and the Efficiency Frontier#

Taking expectations of the LL-smooth descent bound f(x−ηg^b)−f(x)≤−η∇f⊤g^b+L2η2∥g^b∥2f(\mathbf{x} - \eta\hat{\mathbf{g}}_b) - f(\mathbf{x}) \le -\eta\nabla f^\top \hat{\mathbf{g}}_b + \frac{L}{2}\eta^2\|\hat{\mathbf{g}}_b\|^2 and substituting (9.8.1) gives

E[f(x−η g^b)]−f(x)≤−η ∥∇f∥2+L2 η2(∥∇f∥2+tr⁡Σb).(9.8.3)\mathbb{E}\big[f(\mathbf{x} - \eta\, \hat{\mathbf{g}}_b)\big] - f(\mathbf{x}) \leq -\eta\, \|\nabla f\|^2 + \frac{L}{2}\, \eta^2 \Big(\|\nabla f\|^2 + \frac{\operatorname{tr} \boldsymbol{\Sigma}}{b}\Big). \tag{9.8.3}

Minimizing the right-hand side over η\eta yields the optimal step size ηopt(b)\eta_{\text{opt}}(b) and single-step guaranteed decrease:

ηopt(b)=1L⋅11+bnoise/b,f(x)−E[f(x−ηopt g^b)]≥∥∇f∥22L⋅11+bnoise/b.(9.8.4)\begin{aligned} \eta_{\textrm{opt}}(b) &= \frac{1}{L} \cdot \frac{1}{1 + b_{\textrm{noise}} / b}, \\ f(\mathbf{x}) - \mathbb{E}\big[f(\mathbf{x} - \eta_{\textrm{opt}}\, \hat{\mathbf{g}}_b)\big] &\geq \frac{\|\nabla f\|^2}{2L} \cdot \frac{1}{1 + b_{\textrm{noise}} / b}. \end{aligned} \tag{9.8.4}

(Replacing the scalar smoothness bound LIL\mathbf{I} with the local Hessian H\mathbf{H} yields the exact same expressions with the curvature-weighted noise scale tr⁡(HΣ)/(∇f⊤H∇f)\operatorname{tr}(\mathbf{H}\boldsymbol{\Sigma}) / (\nabla f^\top\mathbf{H}\nabla f) (McCandlish et al., 2018), for which bnoiseb_{\text{noise}} in (9.8.2) serves as a Hessian-free proxy.)

Because each step at batch size bb makes a fraction (1+bnoise/b)−1(1 + b_{\text{noise}}/b)^{-1} of the progress of an exact full-batch step, reaching a target loss that requires Smin⁡S_{\min} full-batch steps takes S(b)S(b) steps and E(b)=b S(b)E(b) = b\,S(b) total training examples:

S(b)Smin⁡=1+bnoiseb,E(b)Emin⁡=1+bbnoise,(9.8.5)\frac{S(b)}{S_{\min}} = 1 + \frac{b_{\textrm{noise}}}{b}, \qquad \frac{E(b)}{E_{\min}} = 1 + \frac{b}{b_{\textrm{noise}}}, \tag{9.8.5}

where Emin⁡=bnoiseSmin⁡E_{\min} = b_{\text{noise}} S_{\min} is the minimal data budget achieved in the small-batch limit b≪bnoiseb \ll b_{\text{noise}}. At the critical batch size bcrit=bnoiseb_{\text{crit}} = b_{\text{noise}}, both the step count and the example count equal twice their theoretical minimum (S=2Smin⁡,E=2Emin⁡S = 2S_{\min}, E = 2E_{\min}), marking the knee of the Pareto frontier ((E/Emin⁡−1)(S/Smin⁡−1)=1((E/E_{\min} - 1)(S/S_{\min} - 1) = 1).

9.8.2.2 Linear vs. Square-Root Learning-Rate Scaling#

When increasing the batch size from b0b_0 to bb in the noise-dominated regime (b0,b≪bnoiseb_0, b \ll b_{\text{noise}}), how must the learning rate η\eta scale?

  • SGD and Momentum (linear scaling): From (9.8.4), when b≪bnoiseb \ll b_{\text{noise}}, ηopt(b)≈bLbnoise∝b\eta_{\text{opt}}(b) \approx \frac{b}{L b_{\text{noise}}} \propto b. Equivalently, kk steps of size η0\eta_0 on batch size b0b_0 match one step of size kη0k\eta_0 on batch size kb0k b_0 while preserving the stationary noise floor ∝η/b\propto \eta / b (Goyal et al., 2017; Smith et al., 2018).
  • Adam and AdamW (square-root scaling): In the noise-dominated regime where a coordinate gradient has mean gˉ\bar{g} and standard deviation σ/b\sigma / \sqrt{b}, Adam normalizes the gradient by its RMS scale v^t≈σ/b\sqrt{\hat{v}_t} \approx \sigma / \sqrt{b}, yielding single-step drift −η(b/σ)gˉ-\eta(\sqrt{b}/\sigma)\bar{g} and step noise −ηz-\eta z (z∼N(0,1)z \sim \mathcal{N}(0, 1)). Because the denominator σ/b\sigma/\sqrt{b} already supplies a factor of b/b0\sqrt{b/b_0}, matching the drift and cumulative variance of k=b/b0k = b/b_0 small steps in a single large step requires scaling η\eta by b/b0\sqrt{b/b_0} (Malladi et al., 2022):
η(b)=bb0 η0    (SGD),η(b)=bb0 η0    (Adam / AdamW).(9.8.6)\begin{aligned} \eta(b) &= \frac{b}{b_0}\, \eta_0 \;\; \textrm{(SGD)}, \\ \eta(b) &= \sqrt{\frac{b}{b_0}}\, \eta_0 \;\; \textrm{(Adam / AdamW)}. \end{aligned} \tag{9.8.6}

Once bb exceeds bcritb_{\text{crit}}, gradient noise no longer dominates the denominator and the optimal learning rate saturates at the deterministic curvature limit rather than continuing to grow with bb (Shallue et al., 2019).

9.8.3 Empirical Verification: Steps to Target and Scaling Rules#

To measure the steps S(b)S(b) required to reach a fixed held-out loss target, we first define eval_loss to evaluate ce_loss over validation tensors in chunks of 4,0964{,}096 examples:

def eval_loss(model, X, Y, chunk=4096):
    with torch.inference_mode():
        return torch.stack([ce_loss(model, X[i:i + chunk], Y[i:i + chunk])
                            for i in range(0, len(Y), chunk)]).mean().item()

The stopping harness train_to_target checks eval_loss every eval_every steps inside d2l.train_steps and returns the step count at which target is reached (or inf if max_steps is exhausted):

def train_to_target(model, data, optimizer, X_eval, Y_eval, target,
                    max_steps, eval_every=10):
    """Return the number of steps until the eval loss reaches target."""
    def reached(step):
        return (step % eval_every == 0
                and eval_loss(model, X_eval, Y_eval) <= target)
    steps = len(d2l.train_steps(model, data, optimizer, max_steps,
                                stop=reached))
    return steps if reached(steps) else float('inf')

We first run train_to_target on TinyLM (target validation loss 1.91.9 nats/byte) across b∈{4,16,64,256}b \in \{4, 16, 64, 256\} sequences from a shared initialization, scaling the Adam learning rate as η=0.003b/64\eta = 0.003\sqrt{b / 64}:

starts = np.arange(0, len(data.val) - data.num_steps, data.num_steps)
X_val, Y_val = (t.to(device) for t in data.windows(data.val,
                                                   starts[::8][:2048]))
lm_bs, lm_steps = [4, 16, 64, 256], []
seed = random.getrandbits(32)  # One initialization for all batch sizes
for b in lm_bs:
    torch.manual_seed(seed)
    data.batch_size = b
    model = d2l.TinyLM(len(data.vocab)).to(device)
    optimizer = torch.optim.Adam(model.parameters(),
                                 lr=0.003 * math.sqrt(b / 64))
    lm_steps.append(train_to_target(model, data, optimizer, X_val, Y_val,
                                    target=1.9, max_steps=8000))
    print(f'b={b:4d}  steps={lm_steps[-1]:6.0f}  '
          f'examples={b * lm_steps[-1]:8.0f}')
d2l.plot(lm_bs, [lm_steps, [lm_steps[0] * lm_bs[0] / b for b in lm_bs]],
         'batch size (sequences)', 'steps to loss 1.9', xscale='log',
         yscale='log', legend=['measured', 'perfect scaling'])
b=   4  steps=  3880  examples=   15520
b=  16  steps=  1200  examples=   19200
b=  64  steps=   440  examples=   28160
b= 256  steps=   210  examples=   53760

We repeat the step-to-target sweep on FashionCNN (target loss 0.350.35) across b∈{8,32,128,512,2048}b \in \{8, 32, 128, 512, 2048\} images, scaling η=0.004min⁡(b,512)/256\eta = 0.004\sqrt{\min(b, 512)/256} up to b=512b = 512:

cnn_bs, cnn_steps = [8, 32, 128, 512, 2048], []
seed = random.getrandbits(32)  # One initialization for all batch sizes
for b in cnn_bs:
    torch.manual_seed(seed)
    fashion_b = d2l.FashionMNIST(batch_size=b)
    model = d2l.FashionCNN().to(device)
    lr = 0.004 * math.sqrt(min(b, 512) / 256)  # Held fixed above 512
    optimizer = torch.optim.Adam(model.parameters(), lr=lr)
    cnn_steps.append(train_to_target(model, fashion_b, optimizer,
                                     X_f[:8192], y_f[:8192], target=0.35,
                                     max_steps=8000))
    print(f'b={b:4d}  steps={cnn_steps[-1]:6.0f}  '
          f'examples={b * cnn_steps[-1]:8.0f}')
d2l.plot(cnn_bs, [cnn_steps,
                  [cnn_steps[0] * cnn_bs[0] / b for b in cnn_bs]],
         'batch size', 'steps to loss 0.35', xscale='log', yscale='log',
         legend=['measured', 'perfect scaling'])
b=   8  steps=  2340  examples=   18720
b=  32  steps=   650  examples=   20800
b= 128  steps=   230  examples=   29440
b= 512  steps=   130  examples=   66560
b=2048  steps=    80  examples=  163840

Because S(b)=Smin⁡(1+bcrit/b)S(b) = S_{\min}(1 + b_{\text{crit}}/b) is linear in 1/b1/b, fit_steps extracts the asymptotic step floor Smin⁡S_{\min} and empirical critical batch size bcritb_{\text{crit}} for both models via weighted least squares:

def fit_steps(bs, steps):
    """Fit S(b) = S_min (1 + b_crit / b) by least squares in 1/b."""
    b, S = np.array(bs, dtype=float), np.array(steps, dtype=float)
    ok = np.isfinite(S)  # Leave out runs that never reached the target
    slope, S_min = np.polyfit(1 / b[ok], S[ok], 1, w=1 / S[ok])
    assert S_min > 0, 'step counts never level off: no floor to fit'
    return S_min, slope / S_min

fits = {'TinyLM': fit_steps(lm_bs, lm_steps),
        'FashionCNN': fit_steps(cnn_bs, cnn_steps)}
for name, (S_min, b_crit) in fits.items():
    print(f'{name:10s}  S_min = {S_min:4.0f} steps  b_crit = {b_crit:4.0f}')
TinyLM      S_min =  157 steps  b_crit =  102
FashionCNN  S_min =   78 steps  b_crit =  241

Normalizing each run's example count E(b)=b S(b)E(b) = b\,S(b) by Emin⁡=bcritSmin⁡E_{\min} = b_{\text{crit}} S_{\min} and step count by Smin⁡S_{\min} plots both models against the universal Pareto frontier (9.8.5):

x = np.logspace(0.005, 1.3, 100)  # E / E_min along the model curve
xs, ys = [x], [1 + 1 / (x - 1)]
for (S_min, b_crit), bs, steps in zip(fits.values(), (lm_bs, cnn_bs),
                                      (lm_steps, cnn_steps)):
    xs.append([b * S / (b_crit * S_min) for b, S in zip(bs, steps)])
    ys.append([S / S_min for S in steps])
d2l.plot(xs, ys, 'examples / minimum', 'steps / minimum', xscale='log',
         yscale='log', fmts=('-', 'o', 's'),
         legend=['model', 'TinyLM', 'FashionCNN'])

Both architectures fall near the universal curve (E/Emin⁡−1)(S/Smin⁡−1)=1(E/E_{\min} - 1)(S/S_{\min} - 1) = 1 (a point close to E=Emin⁡E = E_{\min} sits on the curve's steep wall, where a small error in the measured step count moves it far up or down) with fitted critical batch sizes bcrit∼100b_{\text{crit}} \sim 100 sequences for TinyLM and bcrit∼200–400b_{\text{crit}} \sim 200\text{--}400 images for FashionCNN. For TinyLM the fit agrees with the two-batch estimate of bnoiseb_{\text{noise}} measured above, somewhat under 100100 sequences. For FashionCNN it is two to four times the estimate of about 100100 images. The simple noise scale ignores curvature, so it gives the order of magnitude of bcritb_{\text{crit}} and not its value.

Finally, we directly verify the linear (η∝b\eta \propto b) versus square-root (η∝b\eta \propto \sqrt{b}) learning-rate scaling rules (9.8.6) on FashionCNN at a fixed data budget of 12,80012{,}800 images (1/51/5 epoch). The helper final_loss_at runs d2l.lr_sweep for num_examples // b steps at batch size b and returns the terminal losses averaged over the final quarter of each run:

def final_loss_at(make_optimizer, lrs, b, seed, num_examples=12800):
    """Train the CNN once per learning rate; return the final losses."""
    curves, _ = d2l.lr_sweep(d2l.FashionCNN, make_optimizer,
                             d2l.FashionMNIST(batch_size=b), lrs, seed,
                             num_examples // b, verbose=False)
    return [d2l.final_loss(c, k=len(c) // 4) for c in curves.values()]

Under SGD with momentum (β=0.9\beta = 0.9), increasing the batch size 8×8\times from b=8b = 8 to b=64b = 64 across sgd_lrs shifts the optimal learning rate rightward by 4–8×4\text{--}8\times (at b=64b = 64 the final loss is nearly flat between η=0.05\eta = 0.05 and 0.10.1):

sgd_lrs = [0.003125, 0.00625, 0.0125, 0.025, 0.05, 0.1, 0.2]
make_sgd = lambda model, lr: torch.optim.SGD(model.parameters(), lr,
                                             momentum=0.9)
seed = random.getrandbits(32)
sgd_small = final_loss_at(make_sgd, sgd_lrs, b=8, seed=seed)
sgd_big = final_loss_at(make_sgd, sgd_lrs, b=64, seed=seed)
for b, loss in ((8, sgd_small), (64, sgd_big)):
    print(f'b={b:2d}: best lr {sgd_lrs[np.nanargmin(loss)]:g}')
d2l.plot(sgd_lrs, [sgd_small, sgd_big], 'learning rate', 'final loss',
         xscale='log', legend=['b=8', 'b=64'])
b= 8: best lr 0.0125
b=64: best lr 0.05

By contrast, increasing the batch size 64×64\times from b=2b = 2 to b=128b = 128 under Adam across adam_lrs shifts the optimal learning rate by only 4–8×4\text{--}8\times (22 to 33 grid steps of 2×2\times), matching 64=8×\sqrt{64} = 8\times rather than 64×64\times:

adam_lrs = [0.0001 * 2 ** k for k in range(13)]  # 0.0001 to 0.4096
make_adam = lambda model, lr: torch.optim.Adam(model.parameters(), lr)
seed = random.getrandbits(32)
adam_small = final_loss_at(make_adam, adam_lrs, b=2, seed=seed)
adam_big = final_loss_at(make_adam, adam_lrs, b=128, seed=seed)
i, j = int(np.nanargmin(adam_small)), int(np.nanargmin(adam_big))
print(f'best lr: {adam_lrs[i]:g} at b=2; {adam_lrs[j]:g} at b=128, '
      f'final loss {adam_big[j]:.3f}')
for rule, k in (('no scaling', 0), ('square root', 3), ('linear', 6)):
    if i + k < len(adam_lrs):
        print(f'{rule:11s}: lr {adam_lrs[i + k]:g} at b=128, '
              f'final loss {adam_big[i + k]:.3f}')
    else:
        print(f'{rule:11s}: lr {adam_lrs[i] * 2 ** k:g}, beyond the grid')
d2l.plot(adam_lrs, [adam_small, adam_big], 'learning rate', 'final loss',
         xscale='log', legend=['b=2', 'b=128'])
best lr: 0.0008 at b=2; 0.0064 at b=128, final loss 0.510
no scaling : lr 0.0008 at b=128, final loss 0.635
square root: lr 0.0064 at b=128, final loss 0.510
linear     : lr 0.0512 at b=128, final loss 0.726

9.8.3.1 Practical Procedure for Selecting Batch Size#

  1. Saturate hardware arithmetic first: Increase bb at least until per-step execution time begins to scale linearly with bb (Section 9.2).
  2. Estimate bnoiseb_{\text{noise}} post-warmup: Measure noise_scale after the initial loss drop (e.g., a few hundred steps into training), as bnoiseb_{\text{noise}} can start very small at initialization and grow by 1–21\text{--}2 orders of magnitude during training, as it did for TinyLM (motivating batch-size warmup ramps in large pretraining runs such as GPT-3 (Brown et al., 2020)).
  3. Position bb relative to bcrit≈bnoiseb_{\text{crit}} \approx b_{\text{noise}}: When compute/data is the bottleneck, choose b≲0.3 bcritb \lesssim 0.3\,b_{\text{crit}}; when wall-clock time across parallel accelerators is the bottleneck, choose b≈bcritb \approx b_{\text{crit}} (where S=2Smin⁡S = 2S_{\min} and E=2Emin⁡E = 2E_{\min}), and avoid b≫bcritb \gg b_{\text{crit}}.
  4. Scale η\eta via (9.8.6): Scale η∝b\eta \propto b for SGD/Momentum and η∝b\eta \propto \sqrt{b} for AdamW up to bcritb_{\text{crit}}, paired with linear warmup (Section 9.7.3).

9.8.4 Summary#

The gradient-noise scale bnoise=tr⁡(Σ)/∥∇f∥2b_{\text{noise}} = \operatorname{tr}(\boldsymbol{\Sigma}) / \|\nabla f\|^2 marks the batch size at which sampling noise power equals signal power, and can be estimated online without full-dataset passes from squared gradient norms at two batch sizes bs<blb_{\text{s}} \lt b_{\text{l}} ((9.8.1)). Under tuned learning rates, the steps S(b)S(b) and examples E(b)=b S(b)E(b) = b\,S(b) required to reach a target loss follow the hyperbolic trade-off S(b)/Smin⁡=1+bcrit/bS(b)/S_{\min} = 1 + b_{\text{crit}}/b and E(b)/Emin⁡=1+b/bcritE(b)/E_{\min} = 1 + b/b_{\text{crit}} around the knee bcrit≈bnoiseb_{\text{crit}} \approx b_{\text{noise}}, separating a data-efficient small-batch regime (b≪bcritb \ll b_{\text{crit}}) from a step-saturated large-batch regime (b≫bcritb \gg b_{\text{crit}}). Below bcritb_{\text{crit}}, the optimal learning rate scales linearly (η∝b\eta \propto b) for SGD and momentum and as the square root (η∝b\eta \propto \sqrt{b}) for Adam and AdamW, leveling off once bb passes bcritb_{\text{crit}}.

9.8.5 Exercises#

  1. Larger batch size at an unchanged learning rate. Using (9.8.3) and (9.8.4), show that if η\eta is held fixed at η0=ηopt(b0)\eta_0 = \eta_{\text{opt}}(b_0) while the batch size is increased to b>b0b > b_0, the guaranteed single-step decrease improves by factor 2−(1+bnoise/b)/(1+bnoise/b0)<22 - (1 + b_{\text{noise}}/b)/(1 + b_{\text{noise}}/b_0) \lt 2, never more than doubling even as b→∞b \to \infty.

  2. Time-optimal vs. compute-optimal batch size. If one step at batch size bb takes wall-clock time t(b)=t0(1+b/bsat)t(b) = t_0(1 + b/b_{\text{sat}}), use (9.8.5) to derive the batch size b⋆b^\star that minimizes total wall-clock time T(b)=t(b)S(b)T(b) = t(b)S(b) and compute its data overhead E(b⋆)/Emin⁡E(b^\star)/E_{\min}.

  3. [code] Evolution of signal and noise over training. Modify noise_scale to return tr⁡Σ\operatorname{tr}\boldsymbol{\Sigma}, ∥∇f∥2\|\nabla f\|^2, and their ratio bnoiseb_{\text{noise}} separately, track all three on TinyLM at steps 0,25,50,100,200,500,1000,2000,30000, 25, 50, 100, 200, 500, 1000, 2000, 3000, and verify that the 100×100\times growth in bnoiseb_{\text{noise}} is driven primarily by the drop in signal ∥∇f∥2\|\nabla f\|^2 rather than an increase in tr⁡Σ\operatorname{tr}\boldsymbol{\Sigma}.

  4. [code] Scaling past the critical batch size. Extend the TinyLM step-to-target sweep of Section 9.8.3 to b=1,024b = 1{,}024 under the square-root rule η∝b\eta \propto \sqrt{b} versus clamping η\eta at its b=256b = 256 value, and explain why continuing to scale η\eta above bcritb_{\text{crit}} degrades convergence.

Discussions