Foundations to Frontier
Tests
E. Deep Learning › E3 Optimizers (one page each)

Batch, stochastic and mini-batch gradient descent

Gradient descent steps downhill along the gradient of the loss. Batch gradient descent computes that gradient on the whole dataset, stochastic gradient descent on one example, and mini-batch gradient descent on a small random subset, the standard compromise. The mini-batch gradient is an unbiased but noisy estimate whose variance shrinks as 1/B. This page covers the three variants, epochs and steps, shuffling, gradient noise, the learning-rate–batch-size relationship and the critical batch size. In the exercises you verify unbiasedness and the 1/B noise law, then find that up to a critical batch size eight times larger batches need eight times fewer steps with a ten-times larger learning rate, and that beyond it the learning rate hits a stability limit and the extra data are partly wasted.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Downhill, with a noisy compass

Training means repeatedly nudging the parameters downhill on the loss. Measuring the slope exactly requires looking at every training example, which is slow for big datasets. Stochastic gradient descent measures the slope on a few randomly chosen examples instead: a noisy compass, but a cheap one. Many cheap, noisy steps usually beat a few expensive, exact ones, and the noise can even help.

Optimizer lab: gradient descent versus plain gradient descent
gradient descent: final loss 2.2e-9 (target reached at step 22) · gradient descent: final loss 2.2e-9 (step 22)
Orange: the chosen optimizer; grey dashed: plain gradient descent with the same learning rate. Darker shading means higher loss. On the ill-conditioned bowl, raise κ and watch gradient descent zig-zag across the narrow direction; on the saddle it stalls near the flat start; on the plateau its gradients are tiny. Adaptive methods rescale each direction; momentum methods build speed along consistent directions. The target is 1% of the starting loss (for the saddle, a loss below −0.2; its minima are at −0.25).
Why engineers care

Every neural network in perception, control or prediction is trained with a variant of mini-batch gradient descent. The batch size sets how much GPU memory is used, how well hardware is utilised, how many steps training takes and how noisy each step is. On-board or federated learning on small devices pushes toward small batches, data-centre training toward huge ones.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Stochastic gradient descent estimates the gradient from…
  2. 2. An epoch is…
  3. 3. Larger batches make each gradient estimate…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Update: w ← w − η·g, with g the gradient of the average loss over the batch.
  • Batch sizes:
    • batch GD uses all n examples, one step per epoch;
    • SGD uses 1, n steps per epoch;
    • mini-batch uses B, ⌈n/B⌉ steps per epoch: 8 for n = 500 and B = 64.
  • Example: w = (1, 2), g = (0.5, −1), η = 0.1 gives w = (0.95, 2.1).
  • Unbiasedness: with uniformly sampled examples, the mini-batch gradient’s expectation equals the full gradient.
  • Noise: its variance is σ²/B, where σ² is the per-example gradient variance. Four times the batch halves the noise’s standard deviation.
  • Shuffling: sampling without replacement (shuffling every epoch) visits every example once per epoch and usually works slightly better than sampling with replacement.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Steps per epoch for n = 1000, B = 100?
  2. 2. Quadrupling the batch size multiplies the gradient variance by…
  3. 3. Is the mini-batch gradient biased?

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Batches in code

Exercise 1. For least squares:

  • the average of 20 000 mini-batch gradients equals the full gradient;
  • an epoch of shuffled batches covers every example exactly once (8 batches of up to 64 for n = 500);
  • the measured gradient variance falls as 1/B: 21.9 at B = 1, 1.42 at B = 16, 0.34 at B = 64.

Choosing a batch size.

  • Memory and hardware: larger batches use parallel hardware better, up to memory limits.
  • Linear scaling rule (Goyal et al., 2017): when multiplying the batch by k, multiply the learning rate by k, with a warm-up. This keeps the noise scale η/B roughly fixed, and works up to a point.
  • Critical batch size (McCandlish et al., 2018): beyond it, larger batches stop reducing the number of steps proportionally, and data are wasted.
  • Generalisation: very large batches with untuned learning rates can generalise worse (Keskar et al., 2017), although good schedules close most of that gap.
loader = DataLoader(dataset, batch_size=64, shuffle=True, drop_last=False)
for x, y in loader: opt.zero_grad(); loss_fn(model(x), y).backward(); opt.step()
🐍 Exercise 1: mini-batch gradients
Implement the full and mini-batch least-squares gradients and epoch batching with shuffling, and measure how the gradient's variance depends on the batch size.
📝 Quick check (Level 2)
0/3 answered
  1. 1. The linear scaling rule multiplies the learning rate by…
  2. 2. Beyond the critical batch size…
  3. 3. shuffle=True in a DataLoader means…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Convergence.

  • For a convex, L-smooth loss, full gradient descent with η ≤ 1/L converges at rate O(1/t), and linearly for strongly convex losses.
  • SGD with a constant step converges only to a noise ball whose size is proportional to ηΣ/B. Reaching the exact optimum needs a decaying step, Σηₜ = ∞ and Σηₜ² < ∞ (Robbins and Monro, 1951), giving O(1/√t), or O(1/t) under strong convexity.
  • The noise ball is why learning-rate schedules matter (E3-20).

Stability limit. For a quadratic with largest curvature λ_max, gradient descent diverges if η > 2/λ_max, whatever the batch size. Larger batches allow larger learning rates only until η reaches this limit; beyond it the batch size no longer buys fewer steps. This is the mechanism behind a critical batch size.

SGD as noisy dynamics. With small steps, SGD resembles a diffusion with temperature proportional to η/B. A higher temperature explores more and tends to settle in wider minima; the noise scale, not η or B separately, governs this regime (Smith and Le, 2018; Mandt et al., 2017).

📝 Quick check (Level 3)
0/3 answered
  1. 1. With a constant step, SGD converges to…
  2. 2. Gradient descent on a quadratic diverges when η exceeds…
  3. 3. The Robbins–Monro conditions are…

Level 4: Expert

★★★★★ Expert⏱ 25 minResearchers: original papers and open problems.

How far does a bigger batch get you?

History.

  • A.-L. Cauchy (1847) introduced gradient descent.
  • H. Robbins and S. Monro (1951) introduced stochastic approximation.
  • L. Bottou (2010) argued for SGD at scale.
  • P. Goyal et al. (2017) trained ImageNet in an hour with batches of 8192 and linear scaling.
  • S. McCandlish et al. (2018) defined the critical batch size via the gradient noise scale.
  • C. Shallue et al. (2019) measured batch-size scaling across many tasks.

Exercise 2. Logistic regression with label noise (4096 examples, 20 features). For each batch size, the learning rate is searched on a grid from 0.01 to 30, and we count the fewest SGD steps for the full training loss to come within 0.002 of its optimum.

batch size best learning rate steps to target examples processed
8 0.03 1872 14 976
64 0.3 240 15 360
512 3 30 15 360
4096 10 5 20 480
  • Perfect scaling up to batch 512. Each eightfold increase in batch size cut the steps about eightfold, with the examples processed nearly constant at 15 000, and the best learning rate rose about tenfold each time.
  • Then a stability limit. At batch 4096 the best learning rate stopped at 10, because 30 failed to reach the target (a native probe showed 20 also failed). Steps fell only sixfold, and 33% more examples were needed. That is the critical-batch-size effect, caused here by the curvature limit η < 2/λ_max.
  • Practical rule: grow the batch with linear learning-rate scaling while the step count falls in proportion. Once it stops, larger batches only buy hardware throughput, not fewer epochs.
🐍 Exercise 2 (research): how far does a bigger batch get you?
For batch sizes 8 to 4096, tune the learning rate and count the SGD steps needed to come within 0.002 of the optimal logistic loss; relate steps, examples processed and the best learning rate.

Gradient descent in AI, robotics and aerospace

  • Large-scale perception training in data centres pushes batch sizes up for throughput, so the critical batch size determines how far parallelism helps.
  • On-device and federated learning on robots and aircraft systems uses small batches and few steps, where gradient noise and learning-rate choice dominate.
  • Online adaptation: adaptive controllers and learned models updated in flight are SGD with batch size one, which needs decaying or carefully bounded steps for stability.

References

  1. H. Robbins, S. Monro (1951). “A stochastic approximation method.” Annals of Mathematical Statistics 22(3).
  2. L. Bottou (2010). “Large-scale machine learning with stochastic gradient descent.” Proc. COMPSTAT.
  3. P. Goyal et al. (2017). “Accurate, large minibatch SGD: training ImageNet in 1 hour.” arXiv:1706.02677.
  4. S. McCandlish, J. Kaplan, D. Amodei et al. (2018). “An empirical model of large-batch training.” arXiv:1812.06162.
  5. C. J. Shallue et al. (2019). “Measuring the effects of data parallelism on neural network training.” Journal of Machine Learning Research 20.