9.8 Batch Size
In practice, the minibatch size 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 (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 examples reduces the gradient sampling variance to . This implies two distinct regimes:
- Small-batch (noise-dominated) regime: When sampling noise is larger than the true gradient, doubling halves the noise variance, allowing a larger learning rate that cuts the required step count in half while keeping total examples processed constant (perfect linear scaling).
- Large-batch (curvature-dominated) regime: Once is large enough that the minibatch gradient closely approximates the true full-batch gradient, further increasing yields diminishing reductions in while multiplying the data and compute cost linearly.
McCandlish et al. (2018) showed that the transition between these two regimes occurs at the critical batch size , which is predicted by the gradient-noise scale . In this section, we build a two-batch estimator for , derive the step-versus-data trade-off frontier and the learning-rate scaling rules for SGD () and Adam (), and test both predictions on TinyLM and FashionCNN.
import random9.8.1 The Gradient-Noise Scale#
9.8.1.1 Signal, Noise, and a Two-Batch Estimator#
Let denote the exact full-dataset gradient and denote a minibatch gradient averaged over independent examples, with per-example gradient covariance . Because and , the expected squared norm of the minibatch gradient decomposes into signal power plus noise power :
The signal power and noise power are equal at the simple gradient-noise scale (McCandlish et al., 2018):
We can estimate both and without a full pass over the dataset by measuring the mean squared gradient norm at two batch sizes and solving the two-by-two linear system (9.8.1):
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 () at initialization and again after steps of Adam ():
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 and images, at initialization and after steps of Adam (, the rate the sweep below uses at ):
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 is large and sequences. Once common byte statistics are learned (by step ), drops while inter-sequence variance persists, causing to grow more than tenfold to 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 images from the first step. Over the steps the estimate moves by less than a factor of two, in either direction depending on the run, and stays of the order of 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 -smooth descent bound and substituting (9.8.1) gives
Minimizing the right-hand side over yields the optimal step size and single-step guaranteed decrease:
(Replacing the scalar smoothness bound with the local Hessian yields the exact same expressions with the curvature-weighted noise scale (McCandlish et al., 2018), for which in (9.8.2) serves as a Hessian-free proxy.)
Because each step at batch size makes a fraction of the progress of an exact full-batch step, reaching a target loss that requires full-batch steps takes steps and total training examples:
where is the minimal data budget achieved in the small-batch limit . At the critical batch size , both the step count and the example count equal twice their theoretical minimum (), marking the knee of the Pareto frontier ).
9.8.2.2 Linear vs. Square-Root Learning-Rate Scaling#
When increasing the batch size from to in the noise-dominated regime (), how must the learning rate scale?
- SGD and Momentum (linear scaling): From (9.8.4), when , . Equivalently, steps of size on batch size match one step of size on batch size while preserving the stationary noise floor (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 and standard deviation , Adam normalizes the gradient by its RMS scale , yielding single-step drift and step noise (). Because the denominator already supplies a factor of , matching the drift and cumulative variance of small steps in a single large step requires scaling by (Malladi et al., 2022):
Once exceeds , gradient noise no longer dominates the denominator and the optimal learning rate saturates at the deterministic curvature limit rather than continuing to grow with (Shallue et al., 2019).
9.8.3 Empirical Verification: Steps to Target and Scaling Rules#
To measure the steps required to reach a fixed held-out loss target, we first define eval_loss to evaluate ce_loss over validation tensors in chunks of 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 nats/byte) across sequences from a shared initialization, scaling the Adam learning rate as :
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 ) across images, scaling up to :
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 is linear in , fit_steps extracts the asymptotic step floor and empirical critical batch size 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 by and step count by 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 (a point close to 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 sequences for TinyLM and images for FashionCNN. For TinyLM the fit agrees with the two-batch estimate of measured above, somewhat under sequences. For FashionCNN it is two to four times the estimate of about images. The simple noise scale ignores curvature, so it gives the order of magnitude of and not its value.
Finally, we directly verify the linear () versus square-root () learning-rate scaling rules (9.8.6) on FashionCNN at a fixed data budget of images ( 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 (), increasing the batch size from to across sgd_lrs shifts the optimal learning rate rightward by (at the final loss is nearly flat between and ):
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 from to under Adam across adam_lrs shifts the optimal learning rate by only ( to grid steps of ), matching rather than :
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#
- Saturate hardware arithmetic first: Increase at least until per-step execution time begins to scale linearly with (Section 9.2).
- Estimate post-warmup: Measure
noise_scaleafter the initial loss drop (e.g., a few hundred steps into training), as can start very small at initialization and grow by orders of magnitude during training, as it did forTinyLM(motivating batch-size warmup ramps in large pretraining runs such as GPT-3 (Brown et al., 2020)). - Position relative to : When compute/data is the bottleneck, choose ; when wall-clock time across parallel accelerators is the bottleneck, choose (where and ), and avoid .
- Scale via (9.8.6): Scale for SGD/Momentum and for AdamW up to , paired with linear warmup (Section 9.7.3).
9.8.4 Summary#
The gradient-noise scale 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 ((9.8.1)). Under tuned learning rates, the steps and examples required to reach a target loss follow the hyperbolic trade-off and around the knee , separating a data-efficient small-batch regime () from a step-saturated large-batch regime (). Below , the optimal learning rate scales linearly () for SGD and momentum and as the square root () for Adam and AdamW, leveling off once passes .
9.8.5 Exercises#
-
Larger batch size at an unchanged learning rate. Using (9.8.3) and (9.8.4), show that if is held fixed at while the batch size is increased to , the guaranteed single-step decrease improves by factor , never more than doubling even as .
-
Time-optimal vs. compute-optimal batch size. If one step at batch size takes wall-clock time , use (9.8.5) to derive the batch size that minimizes total wall-clock time and compute its data overhead .
-
[code] Evolution of signal and noise over training. Modify
noise_scaleto return , , and their ratio separately, track all three onTinyLMat steps , and verify that the growth in is driven primarily by the drop in signal rather than an increase in . -
[code] Scaling past the critical batch size. Extend the
TinyLMstep-to-target sweep of Section 9.8.3 to under the square-root rule versus clamping at its value, and explain why continuing to scale above degrades convergence.