Mini-Batch SGD & Momentum
Cheap noisy gradients, heavy-ball momentum and finding a good learning rate.
Almost every deep network is trained by the same loop: draw a mini-batch, compute its gradient, take a step. This lesson works out the statistics of that loop: why the mini-batch gradient is unbiased with noise of variance proportional to , why a constant learning rate stalls in a noise ball proportional to , how tuned momentum turns a dependence on the condition number into , and how practitioners pick and scale the learning rate.
What you’ll learn
- Prove that the mini-batch gradient is unbiased, and derive its covariance: with replacement and without.
- Derive the noise-ball bound for constant-step SGD under smoothness and the Polyak–Łojasiewicz inequality, and read off why the learning rate must decay.
- Write heavy-ball and Nesterov momentum as PyTorch implements them, derive the effective step , and show how tuned momentum improves to on a quadratic.
- Choose a learning rate with a range test or a sweep, and scale it with the batch size by the linear scaling rule with warmup.
The statistics of a mini-batch
Write for the loss on example , so that . The per-example gradients scatter around their mean , and their spread is the gradient covariance
A mini-batch of indices gives the estimate . Theory usually assumes independent uniform draws (with replacement); a shuffled data loader draws a random subset (without replacement). Both are unbiased, and they differ slightly in their noise.
Under either scheme each drawn index is uniform on , so each term has mean and so does their average: the mini-batch gradient is unbiased.
With replacement the terms are independent, each with covariance , so their average has covariance .
Without replacement, two distinct draws are negatively correlated. The deviations sum to zero over the dataset, so for , averaging over the ordered pairs of distinct examples:
Adding the variance terms and the cross terms gives the finite-population correction. It vanishes at , where the batch is the whole dataset and the gradient is exact.
In deep learning , so the correction is negligible and the noise is for all practical purposes. What matters is its size relative to the signal, the ratio : when it is small the mini-batch points almost exactly downhill, when it is large the step is mostly noise. As training proceeds the mean gradient shrinks while individual examples still disagree, so this ratio grows. Gradient Noise, Batch Size & Scaling Rules turns that observation into a rule for choosing .
A dataset has examples, and you draw a batch of without replacement. Compared with draws with replacement, by what factor is the covariance of the mini-batch gradient multiplied?
Show the answer
0.5
. Drawing half the dataset without replacement halves the noise relative to independent draws: no example can appear twice, so the batch is a more balanced sample. For and the factor is , which is why the correction is ignored in practice.
Epochs, shuffling and the noise ball
In practice SGD runs in epochs: shuffle the training set, cut it into batches, take one step per batch, and repeat with a fresh shuffle. Within an epoch every example is used exactly once. This random reshuffling is not the scheme most proofs assume, but it is the default for good reason: on smooth, strongly convex finite sums it provably converges faster than with-replacement sampling once enough epochs have passed (Gürbüzbalaban, Ozdaglar & Parrilo, 2021).
Two clocks run in every training job. The number of steps sets the wall-clock time, as long as the hardware processes one batch in roughly constant time, and the number of examples sets the computation. Comparing runs at equal epochs equalizes computation; comparing them at equal steps equalizes time. A bigger batch trades one clock for the other.
Now the central question: how close does SGD get with a constant step?
Smoothness bounds the loss after a step by a quadratic upper model:
Take the expectation over the batch. Unbiasedness turns the middle term into , and . Since gives :
The PL inequality converts gradient size into suboptimality. With , after taking the full expectation:
A contraction plus a constant kick. Its fixed point is the floor, and unrolling the recursion gives the theorem.
Read the bound as a race. The first term forgets the starting point at rate per step; the second is the noise ball, proportional to . Halving halves the floor but also halves the rate at which the start is forgotten, so no constant step is good at both. With steps that shrink like , SGD does converge, at rate in the strongly convex case (Robbins & Monro, 1951, for convergence; Bottou, Curtis & Nocedal, 2018, Theorem 4.7, for the rate). Deep networks satisfy none of these assumptions globally, yet their training curves show the same two phases, fast progress and then a noise-limited plateau, which is why every serious schedule decays.
Heavy-ball and Nesterov momentum
Polyak's heavy-ball method (1964) adds a fraction of the previous step to the gradient step. Libraries write it with a velocity buffer instead; the two forms are the same algorithm:
Nesterov momentum evaluates the gradient where the momentum is about to carry the parameters, so it can brake before it overshoots: , then . Nesterov introduced it in 1983 for convex optimization. Sutskever, Martens, Dahl & Hinton (2013) showed that momentum of either kind, with a good initialization and a slowly increasing schedule for , trains deep autoencoders and recurrent networks to levels previously reached only with Hessian-free second-order optimization. PyTorch's nesterov=True produces the same iterates in shifted variables, using only the gradient at its current parameters: .
import torch
opt = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9,
nesterov=True, weight_decay=5e-4)
# What opt.step() does to each parameter tensor p with gradient g:
# g = g + weight_decay * p # an L2 term added to the gradient
# b = momentum * b + g # b = g on the very first step
# g = g + momentum * b # nesterov=True (plain momentum: g = b)
# p = p - lr * gTwo PyTorch conventions matter when porting hyperparameters from papers. The learning rate multiplies the whole velocity rather than each gradient as it enters, which makes a difference once changes during a run. And the buffer sums gradients without the factor of an exponential moving average: it is times larger than momentum written as , so it needs a learning rate times as large. The weight_decay argument adds an L2 term to the gradient. For plain SGD that is exactly weight decay, and with momentum it is close to it; for Adam the two differ (Adaptive Optimizers: RMSProp, Adam & AdamW).
On a constant slope, , the velocity converges to a geometric series, so momentum multiplies the step by : ten for , a hundred for .
On a quadratic whose Hessian eigenvalues lie in , with condition number , gradient descent multiplies the error along eigenvalue by . The best constant step, , balances the two extreme eigenvalues:
With momentum, each eigen-direction follows a two-term recurrence , with characteristic equation . When its roots are complex, they are conjugates whose product is , so every such direction contracts by exactly per step, whatever its curvature:
Choose and so that this window is exactly . Dividing its endpoints gives , hence Polyak's tuning:
The speed-up is real but specific: it holds asymptotically on quadratics, with exact gradients and tuned and . On general strongly convex functions heavy ball with these settings can fail to converge at all (Lessard, Recht & Packard, 2016), whereas Nesterov's method provably contracts at rate on every smooth, strongly convex function. With noisy gradients most of the acceleration disappears: once noise dominates, momentum acts mainly as a larger effective learning rate . That is why deep learning uses as a default instead of tuning it to , and why momentum pays off mostly at large batch sizes.
A quadratic has condition number . Asymptotically, how many times fewer steps does optimally tuned heavy ball need than gradient descent with its best constant step, to shrink the error by the same factor?
Show the answer
100
Gradient descent needs about steps per factor , since ; heavy ball needs about , since . The ratio is .
Finding a good learning rate
Theory says , but nobody knows of a network in advance, and it changes during training. Two practical procedures are standard.
- The learning-rate range test (Smith, 2017): in one short run, raise steadily from tiny to huge and record the loss. It falls slowly, then quickly, then turns erratic and explodes. The explosion point bounds the usable rates from above; Smith used the test to pick the bounds of cyclical schedules.
- A sweep: train short runs at rates spaced by factors of 2 to 3 and keep the best. It costs more, but it measures what you care about, the loss after a full schedule, rather than behavior in the first few hundred steps.
In practice the best peak rate often lies within a small factor of the largest rate that trains stably, so both procedures concentrate on the region just below the explosion point.
Scaling with the batch size. Goyal et al. (2017) trained ResNet-50 on ImageNet with SGD and Nesterov momentum , using the linear scaling rule and a warmup that raised the rate linearly from to its target over the first five epochs. Validation error stayed flat from batch size 64 up to 8,192 images (trained on 256 GPUs in about an hour), rose beyond that, and with linear scaling training diverged beyond 64k.
Why linear? If gradients change little over steps, then steps with batch and rate move the parameters about as far as one step with batch and rate ; equivalently, the ratio sets how much noise accompanies each unit of progress. The argument fails early in training, when gradients change quickly (hence warmup), and once reaches the stability threshold , which no amount of averaging lifts. For Adam the analogous rule is closer to (Malladi, Lyu, Panigrahi & Arora, 2022).
A recipe trains with batch size 256 at peak rate for 90 epochs. You move to batch size 4,096 on 16 times as many accelerators and keep 90 epochs. What does the linear scaling rule prescribe?
- Keep : the per-example gradients have not changed
- Use , since the noise standard deviation fell by
- Use , reached by a warmup over the first few epochs; the run has 16 times fewer steps
- Use from the first step, with 16 times as many steps
Show the answer
C. Use , reached by a warmup over the first few epochs; the run has 16 times fewer steps
, so the target rate is . Ninety epochs at 16 times the batch are 16 times fewer steps, each meant to move about as far as 16 small ones. Starting at immediately often diverges, which is what the warmup prevents.
Key takeaways
- The mini-batch gradient is unbiased with covariance (times without replacement). Its relative noise grows as training proceeds.
- Under smoothness and the PL inequality, constant-step SGD satisfies : linear progress down to a noise ball proportional to . Only a decaying step converges.
- Momentum, and , has effective step . Tuned heavy ball contracts a quadratic at per step instead of ; Nesterov's look-ahead extends acceleration to all smooth, strongly convex functions; under heavy noise momentum mostly acts as a larger step.
- Learning rates are found by range tests or sweeps, usually just below the largest stable rate. Linear scaling with warmup keeps large-batch SGD on track up to a point, 8,192 images for ResNet-50 on ImageNet in Goyal et al. (2017).
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A mini-batch of examples is drawn independently and uniformly from the training set. What are the mean and covariance of its gradient ?
- Mean , covariance
- Mean , covariance , whatever is
- Mean , covariance
- Mean , covariance
Show the answer
C. Mean , covariance
Each term has mean , so the average does too. The independent terms each contribute covariance , and averaging divides it by . It is the standard deviation that falls like .
In the noise-ball bound , what does halving the constant step do?
- It halves the floor, but forgetting the starting point takes about twice as many steps
- It halves the floor and speeds up the first phase
- It leaves the floor unchanged, because the floor depends only on
- It removes the floor entirely
Show the answer
A. It halves the floor, but forgetting the starting point takes about twice as many steps
The floor is proportional to , and the contraction factor moves toward , so the transient decays about half as fast. That trade-off is why the step should be large early and small late.
You train with momentum and learning rate . Where the gradient stays roughly constant for many steps, how large is the effective step, as a multiple of the gradient?
Show the answer
D.
The velocity approaches , so the step is . Raising from to at fixed multiplies the effective learning rate by ten, so the two must be tuned together.
What distinguishes Nesterov momentum from heavy-ball momentum?
- It uses a larger momentum coefficient
- It evaluates the gradient at the look-ahead point , where momentum is about to carry the parameters
- It divides each coordinate's step by a running average of squared gradients
- It resets the velocity to zero whenever the loss increases
Show the answer
B. It evaluates the gradient at the look-ahead point , where momentum is about to carry the parameters
Both keep a velocity; Nesterov computes the gradient after the momentum part of the step, so it corrects an overshoot one step earlier. That is what gives it the accelerated rate on every smooth, strongly convex function, where heavy ball's accelerated guarantee covers only quadratics.
Go deeper
- Gradient Noise, Batch Size & Scaling Rules · The SDE view of SGD, the gradient noise scale and the critical batch size.
- How SGD Learns Features · Beyond the kernel regime: single-index models, information exponents and leap complexity.
- Sharpness-Aware Minimization · Optimizing for flat minima: the SAM update, what it regularizes and the flatness debate.
Further reading
- L. Bottou, F. E. Curtis & J. Nocedal, "Optimization methods for large-scale machine learning," SIAM Review 60(2), 223–311 (2018).
- B. T. Polyak, "Some methods of speeding up the convergence of iteration methods," USSR Computational Mathematics and Mathematical Physics 4(5), 1–17 (1964).
- I. Sutskever, J. Martens, G. Dahl & G. Hinton, "On the importance of initialization and momentum in deep learning," ICML (2013).
- P. Goyal, P. Dollár, R. Girshick, P. Noordhuis, L. Wesolowski, A. Kyrola, A. Tulloch, Y. Jia & K. He, "Accurate, large minibatch SGD: Training ImageNet in 1 hour," arXiv:1706.02677 (2017).