Batch Size

Dive into Deep Learning · §9.8

Batch Size, Gradient Noise Scale, and Critical Batch Size
signal vs. noise power · two-batch estimator · step-vs.-example Pareto frontier · critical batch size · linear & √b LR rules

When Does Doubling the Batch Size Halve the Step Count?

Motivation

  • Small batch (b: 4 \to 16, 4\times): Noise-dominated; averaging cuts sampling variance \operatorname{tr}(\boldsymbol{\Sigma})/b, delivering \approx 3\times fewer steps at nearly constant data cost (\approx 1.1\text{--}1.3\times E(4)).
  • Large batch (b: 64 \to 256, 4\times): Curvature-dominated; minibatch gradients already match \nabla f, yielding only \approx 2\times fewer steps while doubling data & FLOP cost.
  • The knee (b_{\text{crit}} \approx b_{\text{noise}}): Governed by the gradient-noise scale b_{\text{noise}} = \operatorname{tr}(\boldsymbol{\Sigma}) / \|\nabla f\|^2 (McCandlish et al., 2018).

Signal Power, Noise Power, and Gradient-Noise Scale

The Signal-to-Noise Ratio of a Minibatch

  • Expected squared norm decomposition: \mathbb{E}\big[\|\hat{\mathbf{g}}_b\|^2\big] = \underbrace{\|\nabla f\|^2}_{\text{Signal power}} + \underbrace{\frac{\operatorname{tr}\boldsymbol{\Sigma}}{b}}_{\text{Noise power}}
  • Simple gradient-noise scale: The batch size where noise power equals signal power: b_{\text{noise}} = \frac{\operatorname{tr}\boldsymbol{\Sigma}}{\|\nabla f\|^2}
  • For b \ll b_{\text{noise}}, \hat{\mathbf{g}}_b is mostly sampling noise; for b \gg b_{\text{noise}}, \hat{\mathbf{g}}_b \approx \nabla f.

A Two-Batch Estimator for b_noise Without Full Passes

Online Noise-Scale Estimation

  • Computing \|\nabla f\|^2 directly would require a full pass over the dataset.
  • Instead, measure the mean squared gradient norm N_b = \mathbb{E}[\|\hat{\mathbf{g}}_b\|^2] at two minibatch sizes b_{\text{s}} < b_{\text{l}} and solve the 2 \times 2 linear system N_b = \|\nabla f\|^2 + \frac{\operatorname{tr}\boldsymbol{\Sigma}}{b}: \operatorname{tr}\boldsymbol{\Sigma} \approx \frac{N_{b_{\text{s}}} - N_{b_{\text{l}}}}{1/b_{\text{s}} - 1/b_{\text{l}}}
  • The signal norm is then \|\nabla f\|^2 \approx \frac{b_{\text{l}} N_{b_{\text{l}}} - b_{\text{s}} N_{b_{\text{s}}}}{b_{\text{l}} - b_{\text{s}}}. For example, if N_{16} = 0.50 and N_{2048} = 0.103, then \operatorname{tr}\boldsymbol{\Sigma} \approx 6.4, \|\nabla f\|^2 \approx 0.10, and b_{\text{noise}} \approx 64.
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()

How b_noise Grows Over Training on TinyLM

Dynamic Evolution of the Noise Scale

  • Measuring noise_scale on TinyLM (b_{\text{s}} = 8, b_{\text{l}} = 256 sequences) before and after 500 steps of Adam (\eta = 3 \times 10^{-3}):
    • At initialization (step 0): b_{\text{noise}} \approx 2 sequences. Because every untrained window demands the same global byte-frequency shift, the coherent signal \|\nabla f\|^2 is huge.
    • After 500 steps: b_{\text{noise}} grows >30\times to \sim 50\text{--}150 sequences as \|\nabla f\|^2 falls while inter-sequence disagreement \operatorname{tr}\boldsymbol{\Sigma} persists.
noise scale at initialization: 2.2
after 500 steps of Adam: 93

Optimal Step Size and Single-Step Progress Under Noise

The Noisy Descent Bound

  • Noisy L-smooth descent bound: \mathbb{E}[f(\mathbf{x} - \eta\hat{\mathbf{g}}_b)] - f(\mathbf{x}) \le -\eta\|\nabla f\|^2 + \frac{L}{2}\eta^2\|\nabla f\|^2\Big(1 + \frac{b_{\text{noise}}}{b}\Big)
  • Optimal step size & single-step drop: \eta_{\text{opt}}(b) = \frac{1}{L\,(1 + b_{\text{noise}}/b)}, \quad \Delta f_{\text{opt}}(b) = \frac{\|\nabla f\|^2}{2L\,(1 + b_{\text{noise}}/b)}
  • At b = b_{\text{noise}}, both \eta_{\text{opt}} and \Delta f_{\text{opt}} equal exactly half of their full-batch (b \to \infty) values.

The Step–Data Pareto Frontier and Critical Batch Size

Universal Trade-Off Law

  • Steps S(b) vs. examples E(b) = b\,S(b) (E_{\min} = b_{\text{crit}}S_{\min}): \frac{S(b)}{S_{\min}} = 1 + \frac{b_{\text{crit}}}{b}, \qquad \frac{E(b)}{E_{\min}} = 1 + \frac{b}{b_{\text{crit}}}
  • Small batch (b = 0.1\,b_{\text{crit}}): 11\,S_{\min} steps, only 1.10\,E_{\min} data.
  • Critical knee (b = b_{\text{crit}}): Balanced 2\,S_{\min} steps and 2\,E_{\min} data.
  • Oversized (b = 10\,b_{\text{crit}}): Saves <50\% steps vs. b_{\text{crit}} at 5.5\times the data bill (11\,E_{\min}).

Why SGD Uses Linear LR Scaling (η ∝ b) Below b_crit

Linear Scaling Rule for Unnormalized Optimizers

  • Small-batch limit (b \ll b_{\text{noise}}): \eta_{\text{opt}}(b) = \frac{1}{L\,(1 + b_{\text{noise}}/b)} \approx \frac{b}{L\,b_{\text{noise}}} \implies \eta(b) = \frac{b}{b_0}\eta_0
  • Trajectory & noise-floor equivalence (Goyal et al., 2017): k = b/b_0 small steps at (\eta_0, b_0) equal one step at (k\eta_0, kb_0) while holding \eta/b (and excess loss \frac{\eta\operatorname{tr}\boldsymbol{\Sigma}}{4b}) constant.
  • Saturation past b_{\text{crit}}: For b \gg b_{\text{crit}}, \eta_{\text{opt}} \to 1/L; linear scaling past b_{\text{crit}} violates \eta < 2/L.

Why Adam Uses Square-Root Scaling (η ∝ √b) Below b_crit

Square-Root Scaling Rule for Adaptive Optimizers

Why does Adam / AdamW require square-root scaling \eta(b) = \sqrt{b/b_0}\,\eta_0 instead of linear scaling in the noise-dominated regime (Malladi et al., 2022)?

  • Consider a coordinate whose minibatch gradient has true mean \bar{g} and sampling noise z\,\frac{\sigma}{\sqrt{b}} (z \sim \mathcal{N}(0, 1)) with \frac{\sigma}{\sqrt{b}} \gg |\bar{g}|.
  • Adam’s denominator already scales with \sqrt{b}: Because \sqrt{\hat{v}_t} \approx \sqrt{\bar{g}^2 + \sigma^2/b} \approx \frac{\sigma}{\sqrt{b}}, dividing by \sqrt{\hat{v}_t} automatically amplifies the signal drift by \sqrt{b}: \Delta x_t \approx -\eta\,\frac{\bar{g} + z\,\sigma/\sqrt{b}}{\sigma/\sqrt{b}} = \underbrace{-\eta\,\frac{\sqrt{b}}{\sigma}\,\bar{g}}_{\text{Deterministic drift}} \;-\; \underbrace{\eta\,z}_{\text{Unit-variance step noise}}
  • Matching k = b/b_0 small steps in 1 large step: Over k small steps at (\eta_0, b_0), cumulative drift is k \cdot \eta_0\frac{\sqrt{b_0}}{\sigma}\bar{g} and cumulative noise variance is k\,\eta_0^2. A single step at batch size b = k b_0 matches both the cumulative drift and cumulative variance when: \eta(b) = \sqrt{k}\,\eta_0 = \sqrt{\frac{b}{b_0}}\;\eta_0

Empirical Step-to-Target Scaling on TinyLM

Language Model Sweep

  • Training TinyLM with Adam (\eta = 0.003\sqrt{b/64}) to a held-out validation loss of 1.9 nats across b \in \{4, 16, 64, 256\} sequences:
    • b = 4 \to 16 (4\times): Steps drop about 3\times (\approx 4{,}000 \to 1{,}200), closely tracking the dashed perfect-scaling line (S \propto 1/b).
    • b = 64 \to 256 (4\times): Steps drop by only about 2\times (\approx 430 \to 215), doubling the total sequences processed (\approx 27{,}000 \to 55{,}000) as b crosses b_{\text{crit}} \sim 100.

b=   4  steps=  3880  examples=   15520
b=  16  steps=  1200  examples=   19200
b=  64  steps=   440  examples=   28160
b= 256  steps=   210  examples=   53760

Empirical Step-to-Target Scaling on FashionCNN

Image Classifier Sweep

  • Training FashionCNN with Adam to loss 0.35 across b \in \{8, 32, 128, 512, 2048\} images:
    • b = 8 \to 32 \to 128: Near-linear step reductions (from 2{,}300\text{--}3{,}000 steps to about 700 and then about 240) with slowly rising total example cost (\sim 19{,}000\text{--}32{,}000 images).
    • b = 512 \to 2{,}048 (4\times): Saves only about a third of the steps (\approx 120 \to 80) while nearly tripling the data bill to 163{,}840 images.

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

Fitting S_min and b_crit by Least Squares in 1/b

Extracting the Critical Batch Size

  • Because S(b) = S_{\min}\!\left(1 + \frac{b_{\text{crit}}}{b}\right) = S_{\min} + (S_{\min}b_{\text{crit}})\frac{1}{b} is linear in 1/b, weighted linear regression extracts both asymptotes directly from the step counts:
    • Intercept: Minimum full-batch step floor S_{\min}.
    • Slope / Intercept: Empirical critical batch size b_{\text{crit}}.
  • The fitted values (b_{\text{crit}} \sim 80\text{--}110 sequences on TinyLM and b_{\text{crit}} \sim 200\text{--}350 images on FashionCNN) match the order of magnitude of our two-batch gradient-noise estimator b_{\text{noise}}.
TinyLM      S_min =  157 steps  b_crit =  102
FashionCNN  S_min =   78 steps  b_crit =  241

Collapse onto the Universal Normalized Pareto Curve

Steps vs. Examples Frontier

  • Eliminating b / b_{\text{crit}} between \frac{S(b)}{S_{\min}} = 1 + \frac{b_{\text{crit}}}{b} and \frac{E(b)}{E_{\min}} = 1 + \frac{b}{b_{\text{crit}}} (where E_{\min} = b_{\text{crit}}S_{\min}) yields an architecture-independent hyperbola: \left(\frac{E}{E_{\min}} - 1\right)\left(\frac{S}{S_{\min}} - 1\right) = 1
  • Rescaling TinyLM and FashionCNN by their fitted (S_{\min}, E_{\min}) collapses both models onto this single curve:
    • Upper-left arm (b \ll b_{\text{crit}}): Data-efficient (E \approx E_{\min}), many serial steps.
    • Knee (b = b_{\text{crit}}): (2E_{\min}, 2S_{\min}).
    • Lower-right arm (b \gg b_{\text{crit}}): Step count saturates (S \approx S_{\min}) while data cost explodes.

Verifying the Linear Scaling Rule (η ∝ b) for SGD

SGD with Momentum on FashionCNN

  • At a fixed data budget of E = 12{,}800 images (1/5 epoch), we sweep SGD with momentum (\beta = 0.9) across a factor-of-2 learning-rate grid at b = 8 (1{,}600 steps) and b = 64 (200 steps):
    • Increasing the batch size by 8\times (8 \to 64) shifts the U-shaped loss curve and its optimal learning rate rightward by 4\text{--}8\times (0.0125 \to 0.05\text{--}0.10).
    • Leaving \eta unscaled at 0.0125 when moving to b = 64 severely under-budgets the 200-step run.

b= 8: best lr 0.0125
b=64: best lr 0.05

Verifying the Square-Root Rule (η ∝ √b) for Adam

Adam on FashionCNN Across a 64× Batch Increase

  • At the same 12{,}800-image budget, we increase the batch size by 64\times (b = 2 \to 128) under Adam across a 13-point factor-of-2 grid:
    • No scaling (1\times): \eta is 4\text{--}8\times too small at b = 128, losing roughly 0.1 nats.
    • Square-root rule (\sqrt{64} = 8\times = 2^3, +3 grid steps): Lands at the empirical optimum (\eta = 0.0064) or within one grid step of it.
    • Linear rule (64\times = 2^6, +6 grid steps): Overshoots onto the unstable right wall: the loss is the worst of the three, and at this rate or one grid step above it the loss stays at \log 10 \approx 2.3, so the network learns nothing.

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

Dynamic Batch Size Ramps and Practical Selection Recipe

Engineering Playbook

  • Why ramp b over training? Because b_{\text{noise}} can grow 10\text{--}100\times from step 0 to mid-training, frontier runs ramp b up dynamically (e.g., Llama 3: 4\text{M} \to 16\text{M} tokens).
  • Four-step selection protocol:
    1. Set b \ge b_{\text{sat}} so GPU tensor cores saturate.
    2. Measure post-warmup b_{\text{noise}} at step 300\text{--}500.
    3. Choose b \lesssim 0.3\,b_{\text{crit}} (compute-bound) or b \approx b_{\text{crit}} (wall-clock bound).
    4. Scale \eta \propto b (SGD) or \eta \propto \sqrt{b} (AdamW) with linear warmup.

Concept Check: Two-Batch Estimator and Scaling Rules

Check Your Understanding

Work out the quantitative prediction for each batch-size scenario:

  1. Two-batch estimator: At step 500, measuring mean squared gradient norms at b_{\text{s}} = 10 and b_{\text{l}} = 100 gives N_{10} = 1.0 and N_{100} = 0.19. What are \operatorname{tr}\boldsymbol{\Sigma}, \|\nabla f\|^2, and b_{\text{noise}}?
  2. Adding GPUs near b_{\text{crit}}: TinyLM trains with AdamW at b = 64 and \eta = 3 \times 10^{-3} where b_{\text{crit}} = 100. If you double the batch size to b = 128 across two GPUs, what learning rate does the square-root rule recommend, by what factor does the step count S(b) fall, and by what factor does total data E(b) increase?
  3. Why warmup is mandatory at large b: If b_{\text{crit}} = 256 in mid-training, why can’t we apply the \sqrt{256/16} = 4\times scaled-up learning rate at step t = 1 without warmup?

Answers:

  1. \operatorname{tr}\boldsymbol{\Sigma} = \frac{1.0 - 0.19}{1/10 - 1/100} = \frac{0.81}{0.09} = 9.0; \|\nabla f\|^2 = 0.19 - \frac{9.0}{100} = 0.10; and b_{\text{noise}} = \frac{9.0}{0.10} = 90.
  2. Square-root scaling gives \eta = \sqrt{2} \times 3 \times 10^{-3} \approx 4.24 \times 10^{-3}. Step count drops by \frac{1 + 100/64}{1 + 100/128} = \frac{2.5625}{1.78125} \approx 1.44\times (taking 69\% of wall-clock time across 2 GPUs), while total data processed rises by \frac{1 + 128/100}{1 + 64/100} = \frac{2.28}{1.64} \approx 1.39\times (+39\% data).
  3. At step t = 0, b_{\text{noise}}(0) \approx 2 \ll 256, so b = 256 is initially deep in the curvature-dominated regime (b \gg b_{\text{noise}}(0)) where a 4\times scaled-up learning rate exceeds the initial stability ceiling.

Summary: Gradient-Noise Scale and Critical Batch Size

Key Takeaways

Quantity / Law Mathematical Formula Regime / Scaling Behavior Practical Implication
Minibatch Squared Norm \mathbb{E}\|\hat{\mathbf{g}}_b\|^2 = \|\nabla f\|^2 + \frac{\operatorname{tr}\boldsymbol{\Sigma}}{b} Signal power +\; 1/b noise power Allows estimating \operatorname{tr}\boldsymbol{\Sigma} and \|\nabla f\|^2 from two batch sizes b_{\text{s}} < b_{\text{l}}
Gradient-Noise Scale b_{\text{noise}} = \frac{\operatorname{tr}\boldsymbol{\Sigma}}{\|\nabla f\|^2} Can grow 10\text{--}100\times during training as \|\nabla f\|^2 drops Hessian-free predictor of the critical batch size b_{\text{crit}}
Step–Data Pareto Curve \frac{S(b)}{S_{\min}} = 1 + \frac{b_{\text{crit}}}{b},\; \frac{E(b)}{E_{\min}} = 1 + \frac{b}{b_{\text{crit}}} Universal hyperbola (E/E_{\min}-1)(S/S_{\min}-1) = 1 At b = b_{\text{crit}}, S = 2S_{\min} and E = 2E_{\min}; diminishing returns above b_{\text{crit}}
SGD LR Scaling \eta(b) = \frac{b}{b_0}\,\eta_0 (b \ll b_{\text{crit}}) Linear growth up to b_{\text{crit}}, then saturates at 1/L Matches k small steps to 1 large step at constant noise floor \eta/b
AdamW LR Scaling \eta(b) = \sqrt{\frac{b}{b_0}}\,\eta_0 (b \ll b_{\text{crit}}) Square-root growth because \sqrt{\hat{v}_t} \approx \sigma/\sqrt{b} supplies \sqrt{b} Pair with linear warmup (or batch-size ramp) to handle small initial b_{\text{noise}}(0)