Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 4: Neural Network Foundations

Batch size and training dynamics

P4.1540 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

Every training loop has a batch size, and it is tied to the learning rate: change one and the other usually has to move too. Knowing what a bigger batch buys, and where it stops paying, is how you choose settings for a laptop and for a thousand GPUs.

  • Large models are trained with very large batches split across many devices, and the learning rate is raised with the batch size. (P10.B6: Distributed training, coming soon)
  • Activations are stored for every example in the batch, so the batch size is a main part of the memory a training step needs. (P10.B4: Counting compute and memory, coming soon)
  • Large batches are usually combined with a warmup period, and the schedule is counted in optimizer steps. (P4.14: Learning-rate schedules)
  • Batch size and learning rate are the first settings to search over when a model trains badly. (P4.23: Hyperparameter tuning)

Before this: Stochastic and mini-batch gradient descent, Backpropagation: step by step with numbers, Optimizers, The PyTorch training loop

After this lesson you can

  • Say what changes when the batch size changes
  • Use the linear scaling rule for plain SGD and the square-root guess for Adam-style optimizers, and say where they stop working
  • Explain the critical batch size and why larger batches give diminishing returns
  • State the large-batch generalization debate carefully, with what each side found
  • Write gradient accumulation correctly, and say what it cannot reproduce

Every training loop in this course has a number in it that we have passed over: the batch size. P2.7 wrote batch_size=64 and moved on. P1.F4 showed what it does to a single gradient. This lesson asks what it does to the whole of training.

A two-sentence recap of P1.F4. A mini-batch gradient is an unbiased estimate of the full gradient: its average over all possible batches is the full gradient, and its noise shrinks like σ/B\sigma/\sqrt{B} when the examples are drawn independently. A step costs about BB gradient computations, so noise falls with B\sqrt{B} while cost grows with BB.

What changes when you change BB

Take N=256N = 256 training examples and a budget of 20 epochs, which is 51205120 examples seen. Only the batch size moves:

Batch size BBSteps per epochSteps in 20 epochs
12565120
832640
64480
256 (all)120

The same data and the same number of examples seen, but a very different number of updates. Four things change together:

  • Steps per epoch, N/BN/B. A larger batch gives fewer updates for the same pass through the data.
  • Noise per step, about 1/B1/\sqrt{B} (P1.F4). A larger batch gives a cleaner step.
  • Time per step. A GPU works on many examples at once, so a step on 64 examples often takes less than 64 times as long as a step on one example, until the hardware is full. After that the time grows roughly in proportion to BB. The turning point depends on the model and the machine, so measure it rather than assume it.
  • Memory. Backpropagation (P4.8) stores the activations of every example in the batch, and the shapes are B×…B\times\dots throughout (P4.5). So activation memory grows in proportion to BB. The weights, their gradients and the optimizer state do not depend on BB (P4.13, P10.B4). A batch that does not fit simply cannot be used, which is the reason for gradient accumulation later in this lesson.

None of these is “good” or “bad” alone. The question is what you get for the price, and the answer depends on the learning rate.

The batch-size slider

The widget below trains the same tiny model for every setting: logistic regression (P3.A7) on 256 made-up two-dimensional points from two overlapping blobs, started from the same weights, with plain SGD (P1.F4) and the data shuffled every epoch. The budget is always 20 epochs. The solid blue line is the loss on all 256 points after each step. The faint line is the loss on the step’s own batch, which is the noisy thing a training log prints.

Horizontal axis:
Steps per epoch
32
Steps in 20 epochs
640
Learning rate used
0.03
Final loss
0.443
First within 0.05 of the lowest
184 steps, 1472 examples

With B = 8 the loss on all 256 points ends at 0.443 after 640 steps of η = 0.03; the lowest possible is 0.443. That is within 0.05 of the lowest.

01211010010005120examples seen (log scale)
  • Loss on all 256 points (now)
  • Loss on each step’s own batch (noisy)
  • Lowest possible loss, 0.443
0 of 3 pinned

The vertical axis stops at 2.6, so a larger loss runs off the top. Fixed: 256 made-up points, logistic regression starting from the same weights, plain SGD with the data shuffled every epoch, 20 epochs, seeded. Change one control, pin, change another.

Batch size against training loss for logistic regression on 256 made-up points, 20 epochs. Move the batch-size slider (1 to 256, which is the whole data set) and the learning-rate slider. Switch the horizontal axis between examples seen and steps. Tick the box to scale η with B. Press Pin this curve to keep a curve, then change a setting and compare. Both axes are logarithmic.

Things to try. Each value was checked against a NumPy run of the same model:

  • The default (B=8B = 8, η=0.03\eta = 0.03): 32 steps per epoch, 640 steps, final loss 0.4430.443. That equals the lowest possible loss of this model, 0.4430.443 to three digits. The loss gets within 0.050.05 of it after 184 steps (1472 examples).
  • The same η\eta, a bigger batch. At B=64B = 64 the final loss is 0.8410.841, and at B=256B = 256 it is 1.7251.725. The curve is the same shape, only slower, because 80 steps (B=64B = 64) or 20 steps (B=256B = 256) of η=0.03\eta = 0.03 simply do not go far. Pin B=8B = 8 and compare, on the examples axis and then on the steps axis.
  • A smaller batch. At B=1B = 1 and η=0.03\eta = 0.03 the loss gets within 0.050.05 of the lowest after only 201 steps, which is 201 examples. With the same η\eta, a small batch takes a step after every example, so it makes progress sooner. The faint line shows the price: the loss on a single example reaches about 10 on one step, far above the average.
  • Scale η\eta with BB. Tick the box. Now η=η0B/8\eta = \eta_0 B/8, so B=64B = 64 uses 0.240.24 and B=256B = 256 uses 0.960.96. Every batch size from 1 to 256 ends at 0.4430.443. On the examples axis the curves nearly coincide. On the steps axis the large batch is far ahead: B=256B = 256 gets within 0.050.05 in 6 steps, B=64B = 64 in 23, B=8B = 8 in 184, and B=1B = 1 in 1470.
  • Push it too far. Keep the box ticked and raise η0\eta_0 to 0.30.3. B=64B = 64 (so η=2.4\eta = 2.4) still ends at 0.4470.447, but B=256B = 256 (η=9.6\eta = 9.6) ends at 0.7630.763 and the status line says that the loss rose above its starting value. With η0=1\eta_0 = 1, B=64B = 64 ends at 1.5471.547. The rule has limits, and the next section says why.

Matching the learning rate to the batch size

Compare two ways to use 4 batches of 64 examples. Take four small steps of rate η\eta, one on each batch. Or take one big step on all 256 examples with rate 4η4\eta. If the weights did not move between the four small steps, each small step would use the gradient of its own batch at the starting weights, g1,…,g4\mathbf{g}_1,\dots,\mathbf{g}_4. The four steps add up to η(g1+g2+g3+g4)\eta(\mathbf{g}_1+\mathbf{g}_2+\mathbf{g}_3+\mathbf{g}_4). The big step uses the average of the same four gradients, times 4η4\eta, which is the same sum. The two agree exactly.

That is the linear scaling rule: when you multiply the batch size by kk, multiply the learning rate by kk. Goyal and others (2017) used it to train ResNet-50 on ImageNet with batches of up to 8,192 images. They matched the accuracy of small-batch training up to a batch of 8,192; for larger batches the accuracy fell. They also added a warmup: the learning rate starts small and rises over the early part of training, because early in training the weights change fast, which is when the “weights barely move” assumption is least likely to hold (P4.14).

The argument also says when the rule fails. It needs the gradient to stay about the same over the kk small steps. The cell below measures it on a model of the same kind as the widget’s, with a NumPy random data set, so its numbers differ from the widget’s: from the same start, four steps of 64 examples against one step of 256 with 4η4\eta, and the size of the gap relative to the big step.

Try it: four small steps against one big step

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Running the code gives this (on the machine used for this lesson):

   eta  gap / length of the big step
 0.001   0.0004
 0.010   0.0041
 0.100   0.0454
 1.000   0.5444

For small rates the two agree to a fraction of a percent. At η=1\eta = 1 the four small steps end about half a step-length away from the big step, because the weights moved a long way between them. So the rule is an approximation that is good while the scaled rate stays small enough, and it cannot hold for ever: the widget showed it breaking at η=9.6\eta = 9.6.

More limits.

  • McCandlish and others (2018) searched for the best constant learning rate at each batch size. For plain SGD or momentum, the best rate rose roughly linearly with BB at first and then levelled off. Beyond that point a bigger batch no longer allows a bigger rate.
  • For Adam and RMSProp they found the best rate growing like BαB^{\alpha}, with α\alpha between 0.50.5 and 1.01.0 depending on the task, and then also levelling off.
  • A square-root rule (multiply η\eta by k\sqrt{k} for a batch kk times larger) was derived for Adam and RMSProp by Malladi and others (2022). Adam divides each step by a running size of the gradients (P4.13), so its steps do not add up the way plain SGD’s do, and the argument above does not carry over directly. So for Adam-style optimizers, k\sqrt{k} is a common first guess and kk is the other end of the range seen in experiments.

Treat both rules as a first guess to test, not a law. The reliable practice is to change BB, start from the rule’s learning rate, and check a few rates around it (P4.23).

Sum or mean? P4.6 showed two examples with errors −1-1 and 0.50.5. The mean loss gave a gradient (with respect to ww) of −1.5-1.5 and the sum gave −3-3. With a sum over a batch of BB examples the gradient is BB times the mean’s, so a summed loss with rate η\eta is the same step as a mean loss with rate BηB\eta. The linear rule says the good rate for a mean loss grows in proportion to BB, so for a summed loss it says to leave η\eta alone. It is the same rule in different units, and it is why P4.6 said that the best learning rate shifts with the batch size.

Where a bigger batch stops paying: the critical batch size

If the learning rate is scaled well, a kk times larger batch needs about kk times fewer steps. The widget showed it: 1470 steps at B=1B = 1, 184 at B=8B = 8, 23 at B=64B = 64, 6 at B=256B = 256. The total number of examples was almost the same each time, about 1500. So a larger batch used the hardware’s parallelism (several examples per step) for free. This cannot continue for ever. Once a batch is big enough that its gradient is already close to the full gradient, more examples in the batch change the step very little.

McCandlish and others (2018) gave a simple model for this. Let Smin⁡S_{\min} be the fewest steps needed to reach some loss (with an enormous batch) and Emin⁡E_{\min} the fewest examples (with tiny batches). With batch size BB, in the model the steps needed are

S=Smin⁡(1+BcritB),E=B S,\begin{aligned} S &= S_{\min}\left(1 + \frac{B_{\text{crit}}}{B}\right),\\ E &= B\,S, \end{aligned}

where Bcrit=Emin⁡/Smin⁡B_{\text{crit}} = E_{\min}/S_{\min} is the critical batch size. This is a fit to their measurements, for a chosen target loss, not an exact law. Made-up numbers show its shape, with Smin⁡=1000S_{\min} = 1000 and Bcrit=64B_{\text{crit}} = 64:

BBSteps SSExamples E=BSE = BS
89,00072,000
642,000128,000
5121,125576,000

Going from B=8B = 8 to B=64B = 64 (eight times the batch) cuts the steps by 4.54.5 times and costs 1.81.8 times the examples. Going on from 6464 to 512512 cuts the steps by only 1.81.8 times and costs 4.54.5 times the examples. At B=BcritB = B_{\text{crit}} you use twice the minimum steps and twice the minimum examples. Below BcritB_{\text{crit}} extra batch size is nearly free speed. Above it, it mostly burns compute. That is why “just use the biggest batch that fits” is not the whole answer.

Go deeper The gradient noise scale

How could you know BcritB_{\text{crit}} without trying many batch sizes? McCandlish and others proposed a statistic they call the gradient noise scale. Its simplest form is

Bsimple=tr⁡Σ∥G∥2,B_{\text{simple}} = \frac{\operatorname{tr}\Sigma}{\lVert\mathbf{G}\rVert^2},

where G\mathbf{G} is the full gradient and Σ\Sigma is the covariance of the per-example gradients, so tr⁡Σ\operatorname{tr}\Sigma is the sum of the variances of the gradient’s entries. It compares how large the noise of one example is with how large the true gradient is. They found that it predicts the largest useful batch size to within about an order of magnitude on many tasks, and that it tends to rise as the loss falls, so the critical batch size grows during training.

The cell measures it on a model of the same kind as the widget’s, along a run with B=8B = 8 and η=0.03\eta = 0.03.

Try it: the noise scale grows as training goes on

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

epochs  noise scale
     0         2.7
     1         3.7
     2         5.7
     5        25.1

At the start the noise scale is 2.72.7, so with a batch of about 3 the noise in the batch gradient is already as large as the true gradient; far smaller batches are mostly noise, and larger ones give a clean step. By epoch 5 it is 25.125.1, because the full gradient has shrunk while the per-example gradients have not. Near the minimum the full gradient goes to zero and the statistic grows without limit, so it is only meaningful while the loss is still falling. This is a small convex model, so the numbers show the direction of the effect and not the size to expect in a real network.

Does the batch size change what you learn? The generalization debate

So far a bigger batch only changes how fast training goes. On the widget’s model there is one lowest loss, and every setting that converges ends at it. A neural network’s loss has many low regions, so the batch size could change which one training reaches, and a model that fits the training data equally well can do differently on new data (P3.A1). What is known?

  • Keskar and others (posted 2016, ICLR 2017) trained networks with large and small batches and reported that large batches ended with worse test accuracy. They found that large-batch solutions were in sharp minima, where the loss rises quickly when the weights move a little, and small-batch solutions in flat ones. They proposed that the noise of small batches is what steers training away from sharp minima.
  • Goyal and others (2017) found that on ImageNet much of the large-batch gap disappeared when the learning rate was scaled with the batch size and warmup was used, up to a batch of 8,192.
  • Shallue and others (posted 2018, JMLR 2019) trained many models and datasets over a wide range of batch sizes. They reported no evidence that larger batch sizes hurt test performance, and argued that conflicting reports come from differences in how the learning rate and other settings were tuned, and in the compute budget.

So the claim “small batches generalize better” is an observation that held in some experiments with fixed settings, and it weakens when the learning rate is tuned for each batch size. It is not established as a general rule; whether noise helps generalization is still being studied. P4.24 comes back to generalization puzzles. What you can rely on is practical: a fair comparison tunes η\eta for each batch size, and with a fixed η\eta a bigger batch is a different training run, not just a faster one.

The two ends: B=1B = 1 and full batch

  • B=1B = 1 is pure stochastic gradient descent. It takes the most steps, uses the least memory, and has the noisiest steps: the faint line in the widget. It usually leaves parallel hardware underused, and layers that need statistics over a batch cannot work with a batch of one (P4.19).
  • B=NB = N is full-batch gradient descent. It has no sampling noise, one step per epoch, and needs the activations of every example at once. At the same η\eta it falls far behind in the widget, because a step is a good one but there are so few of them.

Almost all practical training sits in between, where the noise is small enough to use a large η\eta and the batch is small enough to fit and to give many steps.

Gradient accumulation: a bigger batch than memory allows

Suppose you want a batch of 256 but only 64 examples fit in memory. P2.7 pointed out that if you forget zero_grad, gradients add up in .grad. Adding gradients on purpose is a trick called gradient accumulation, which lets you simulate a larger batch than fits in memory. The algorithm:

  1. Split the batch into mm micro-batches (here m=4m = 4 micro-batches of 64).
  2. For each micro-batch, compute its loss, divide it by mm, and call backward(). The gradient is added to .grad.
  3. After mm micro-batches, take one optimizer step and then zero the gradients.

Why divide by mm? Each micro-batch loss is a mean over its own 64 examples. The mean over all 256 is the average of the four micro-batch means: 14(mean1+⋯+mean4)\tfrac14(\text{mean}_1 + \dots + \text{mean}_4). Adding four gradients without dividing gives 44 times the right answer, which is the same as multiplying the learning rate by 44.

The cell checks it in NumPy for the three-weight model: four micro-batches of 64 against one batch of 256, then the two mistakes that are easy to make.

Try it: accumulated gradients equal the big-batch gradient

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

big batch:   [ 0.1199 -0.2029  0.0219]
accumulated: [ 0.1199 -0.2029  0.0219]
largest difference: 8.3e-17
without /4, too big by 4.0 times
equal weights: 7.0e-03
weighted by size: 5.6e-17

The accumulated gradient matches the big-batch gradient to rounding (10−1710^{-17} in 64-bit floats). Dividing by mm matters, and so does weighting when the pieces are unequal: if the last micro-batch is smaller, weight each piece’s loss by its share of the examples, nk/Nn_k/N, instead of 1/m1/m.

The same thing in PyTorch. Two steps on batches of 128 are compared with the same 256 examples as eight micro-batches of 32, one step per four (run locally with PyTorch 2.9.1, no shuffling so that both see the examples in the same order):

import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

torch.manual_seed(0)
x = torch.randn(256, 3)
y = (torch.rand(256, 1) < 0.5).float()
data = TensorDataset(x, y)
loss_fn = nn.BCEWithLogitsLoss()

def make():
    torch.manual_seed(1)
    return nn.Linear(3, 1)

# plain loop: batches of 128, one step per batch
plain = make()
opt = torch.optim.SGD(plain.parameters(), lr=0.1)
for xb, yb in DataLoader(data, batch_size=128, shuffle=False):
    opt.zero_grad()
    loss_fn(plain(xb), yb).backward()
    opt.step()

# accumulation: batches of 32, one step per 4 batches
model = make()
opt = torch.optim.SGD(model.parameters(), lr=0.1)
m = 4                                       # micro-batches per step
opt.zero_grad()
for k, (xb, yb) in enumerate(DataLoader(data, batch_size=32, shuffle=False)):
    loss = loss_fn(model(xb), yb) / m       # divide by the number of micro-batches
    loss.backward()                         # adds to .grad
    if (k + 1) % m == 0:
        opt.step()
        opt.zero_grad()

diff = max((a - b).abs().max().item()
           for a, b in zip(plain.parameters(), model.parameters()))
print("two steps of 128 against 8 micro-batches of 32")
print(f"largest weight difference: {diff:.1e}")
two steps of 128 against 8 micro-batches of 32
largest weight difference: 1.5e-08

The 1.5×10−81.5\times10^{-8} is float32 rounding: the weights agree to the precision of the numbers.

What accumulation does not do.

  • It does not save time. The same number of forward and backward passes happen. It trades speed for memory: one optimizer step now takes mm passes.
  • It cannot copy layers that mix the examples of a batch. Batch normalization (P4.19) computes its statistics over the examples it sees, so with micro-batches it uses the statistics of 64 examples, not of 256. The result is not the big-batch result, however carefully you divide.
  • Count in optimizer steps. A learning-rate schedule and warmup (P4.14) should advance once per optimizer step, not once per micro-batch, or the schedule runs mm times too fast. A logged micro-batch loss is divided by mm: multiply by mm to read that micro-batch’s mean, or add up the mm divided values to read the whole batch’s mean.

The batch size and learning rate go together

The pair (B,η)(B, \eta) is what matters, not BB alone. In practice:

  • Compare at equal examples seen, as the widget does, or at equal epochs. At equal steps a larger batch has seen more data.
  • Pick a batch that fits and keeps the hardware busy, then tune η\eta for it. If you change BB later, start from the scaling rule for your optimizer, add warmup if the jump is large, and check a few rates.
  • Powers of two are a habit. Sizes such as 32, 64 and 128 are convenient for memory layouts and are what most code uses. A batch of 100 works the same way mathematically.
  • A noisy loss curve is not a bug. The loss on a single batch jumps around, especially for small BB. Read the trend, or the loss on a fixed validation set (P4.22).

Summary: intuition, math, code

Intuition

Think of a survey. A small survey is cheap and a little off each time. A huge survey is expensive and very accurate, but once the answer is already accurate enough, asking more people changes little. Training takes many small surveys in a row and adjusts after each. A small batch means many cheap adjustments that are a bit shaky. A bigger batch means fewer, steadier adjustments, so each one can be bolder, which is the idea of the scaling rule. The picture breaks in one way: a survey sample is fixed, while each batch changes the weights before the next one is drawn. There is a size past which steadier no longer helps, because the shakiness is already small next to the true direction. That size is the critical batch size.

Math

Mini-batch step: θ←θ−η g^B\boldsymbol{\theta}\leftarrow\boldsymbol{\theta}-\eta\,\hat{\mathbf{g}}_B, with g^B=1B∑i∈batch∇Li\hat{\mathbf{g}}_B=\frac1B\sum_{i\in\text{batch}}\nabla L_i. Steps per epoch: N/BN/B.

  • Linear scaling. kk small steps of rate η\eta with batch gradients g1,…,gk\mathbf{g}_1,\dots,\mathbf{g}_k at the starting weights give η∑jgj\eta\sum_j\mathbf{g}_j; one step at batch kBkB with rate kηk\eta gives kη⋅1k∑jgjk\eta\cdot\frac1k\sum_j\mathbf{g}_j, the same sum.
  • Mean and sum. ηsum∑i∇Li=B ηsum g^B\eta_{\text{sum}}\sum_i\nabla L_i = B\,\eta_{\text{sum}}\,\hat{\mathbf{g}}_B, so a sum with ηsum\eta_{\text{sum}} is a mean with BηsumB\eta_{\text{sum}}.
  • Critical batch size (a fitted model). S=Smin⁡(1+Bcrit/B)S = S_{\min}(1+B_{\text{crit}}/B), E=BSE = BS, Bcrit=Emin⁡/Smin⁡B_{\text{crit}} = E_{\min}/S_{\min}. Equivalently (SSmin⁡−1)(EEmin⁡−1)=1\left(\tfrac{S}{S_{\min}}-1\right)\left(\tfrac{E}{E_{\min}}-1\right)=1.
  • Noise scale. Bsimple=tr⁡Σ/∥G∥2B_{\text{simple}} = \operatorname{tr}\Sigma/\lVert\mathbf{G}\rVert^2, and the expected squared error of a batch gradient is tr⁡Σ/B\operatorname{tr}\Sigma/B for independent draws.
  • Accumulation. With micro-batches of sizes n1,…,nmn_1,\dots,n_m and N=∑nkN=\sum n_k: g=∑knkN gk\mathbf{g}=\sum_k\frac{n_k}{N}\,\mathbf{g}_k, which is 1m∑kgk\frac1m\sum_k\mathbf{g}_k when all nkn_k are equal.

Code

The core of accumulation, with the batch size set in the data loader and not in the optimizer (P2.7). The full program with its output is in the section on gradient accumulation above.

loader = DataLoader(data, batch_size=32)      # the micro-batch size
m = 4                                         # micro-batches per optimizer step
for k, (xb, yb) in enumerate(loader):
    (loss_fn(model(xb), yb) / m).backward()   # adds to .grad
    if (k + 1) % m == 0:
        opt.step()
        opt.zero_grad()

Check your understanding

  1. You train with plain SGD at batch size 64 and learning rate 0.1. You move to batch size 512 and use the linear scaling rule. What learning rate do you start with?

  2. A model is trained with a loss that is the SUM over the batch, not the mean. The batch size grows by a factor of 16 and the linear scaling rule is applied. What should happen to the learning rate of the summed loss?

  3. In a model of large-batch training, the critical batch size is 64. What is the main effect of raising the batch size from 64 to 1024?

  4. Gradient accumulation uses 8 micro-batches per optimizer step. Each micro-batch loss is a mean over its own examples. What must be done to the loss before backward() so that the step matches one big batch?

  5. Which statement about batch size and generalization is best supported by the studies in this lesson?

Exercises

  1. A data set has N=51,200N = 51{,}200 examples. How many steps are there in one epoch, and in 10 epochs, with B=256B = 256? How many with B=32B = 32?
    Show answer51,200/256=20051{,}200/256 = 200 steps per epoch, so 20002000 steps in 10 epochs. With B=32B = 32 it is 16001600 steps per epoch and 16,00016{,}000 in 10 epochs. Both see 512,000512{,}000 examples.
  2. SGD with η=0.05\eta = 0.05 works well at B=128B = 128. Using the linear rule, what is a starting η\eta at B=1024B = 1024? For Adam with η=0.05\eta = 0.05 at B=128B = 128, what is the square-root guess?
    Show answerThe batch is k=8k = 8 times larger. Linear: 0.05×8=0.40.05\times8 = 0.4. Square root: 0.05×8≈0.1410.05\times\sqrt{8}\approx0.141. Both are first guesses to test.
  3. You want an effective batch of 128 but only 16 examples fit. How many micro-batches per step, and what should each loss be divided by? What happens if you forget the division with plain SGD?
    Show answer128/16=8128/16 = 8 micro-batches, so divide each loss by 88. Without it the gradient is 88 times too big, which acts like a learning rate 88 times larger.
  4. In the critical-batch model with Smin⁡=500S_{\min} = 500 and Bcrit=100B_{\text{crit}} = 100, find the steps and the examples for B=25B = 25 and B=400B = 400.
    Show answerS=500(1+100/B)S = 500(1+100/B). For B=25B = 25: S=2500S = 2500 and E=62,500E = 62{,}500. For B=400B = 400: S=625S = 625 and E=250,000E = 250{,}000. The larger batch saves four times the steps and costs four times the examples.
  5. You have 100 examples split into micro-batches of 40, 40 and 20. What weights multiply the three mean losses so that the sum equals the mean over all 100?
    Show answerEach weight is the share of examples, nk/Nn_k/N: 0.40.4, 0.40.4 and 0.20.2. Using 1/31/3 each would give the small piece too much influence.
  6. A summed-loss run uses B=32B = 32 and ηsum=0.001\eta_{\text{sum}} = 0.001. What mean-loss learning rate gives the same step?
    Show answerThe sum equals 3232 times the mean, so 0.001×32=0.0320.001\times32 = 0.032. P4.6 showed the same factor for two examples.

Next: P4.14 covers learning-rate schedules and warmup, which are the other half of the batch-size and learning-rate pair. P4.19 explains batch normalization, the layer that accumulation cannot copy, and P10.B6 shows how very large batches are spread across many devices.

Key takeaways

  • The batch size BB changes four things: the number of steps per epoch (N/BN/B), the noise in each step (about 1/B1/\sqrt{B}), the time per step, and the memory (the activations grow with BB).
  • Compare batch sizes at the same number of examples seen, not the same number of steps. With one fixed learning rate, a large batch has few steps and falls behind.
  • Linear scaling rule: multiply BB by kk and multiply the learning rate by kk (for plain SGD), usually with a warmup. It works while the weights barely move between kk small steps, so it fails when the scaled rate gets large.
  • For Adam-style optimizers a common starting guess is k\sqrt{k} instead of kk. Both are rules of thumb: retune the learning rate when you change BB.
  • Below a critical batch size, doubling BB nearly halves the steps needed. Above it, the steps barely fall and the extra examples are wasted. The gradient noise scale gives a rough estimate of where it lies.
  • Whether small batches generalize better is debated. Early large-batch results were worse, and later work with tuned learning rates found no such gap in many settings.
  • Gradient accumulation adds the gradients of mm micro-batches, each loss divided by mm, before one optimizer step. It matches the big batch up to rounding, saves memory and not time, and cannot copy batch normalization.
Found a mistake? Tell us