Simple Algorithm
Deep Learning · Representation · 22 min

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 1/B1/B, why a constant learning rate stalls in a noise ball proportional to η\eta, how tuned momentum turns a dependence on the condition number κ\kappa into κ\sqrt\kappa, 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: Σ/B\Sigma/B with replacement and n−Bn−1⋅Σ/B\frac{n-B}{n-1}\cdot\Sigma/B 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 η/(1−β)\eta/(1-\beta), and show how tuned momentum improves κ\kappa to κ\sqrt\kappa 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 ℓi(θ)=ℓ(fθ(xi),yi)\ell_i(\boldsymbol\theta)=\ell(f_{\boldsymbol\theta}(\mathbf x_i),y_i) for the loss on example ii, so that L=1n∑iℓi\loss=\frac1n\sum_i\ell_i. The per-example gradients scatter around their mean ∇L\nabla\loss, and their spread is the gradient covariance

Σ(θ)=1n∑i=1n(∇ℓi−∇L)(∇ℓi−∇L)⊤.\Sigma(\boldsymbol\theta)=\frac1n\sum_{i=1}^n\big(\nabla\ell_i-\nabla\loss\big)\big(\nabla\ell_i-\nabla\loss\big)^\top.

A mini-batch B\mathcal B of BB indices gives the estimate g=1B∑i∈B∇ℓi\mathbf g=\frac1B\sum_{i\in\mathcal B}\nabla\ell_i. 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.

DerivationMean and covariance of the mini-batch gradient
  1. E[g]=1B∑j=1BE[∇ℓij]=∇L\E[\mathbf g]=\frac1B\sum_{j=1}^B\E\big[\nabla\ell_{i_j}\big]=\nabla\loss

    Under either scheme each drawn index iji_j is uniform on {1,…,n}\{1,\dots,n\}, so each term has mean ∇L\nabla\loss and so does their average: the mini-batch gradient is unbiased.

  2. Cov⁡(g)=1B2⋅B Σ=ΣB\Cov(\mathbf g)=\frac1{B^2}\cdot B\,\Sigma=\frac{\Sigma}{B}

    With replacement the BB terms are independent, each with covariance Σ\Sigma, so their average has covariance Σ/B\Sigma/B.

  3. Cov⁡(∇ℓij,∇ℓik)=1n(n−1)∑a≠b(∇ℓa−∇L)(∇ℓb−∇L)⊤=−Σn−1\Cov\big(\nabla\ell_{i_j},\nabla\ell_{i_k}\big)=\frac{1}{n(n-1)}\sum_{a\ne b}(\nabla\ell_a-\nabla\loss)(\nabla\ell_b-\nabla\loss)^\top=-\frac{\Sigma}{n-1}

    Without replacement, two distinct draws are negatively correlated. The deviations ∇ℓa−∇L\nabla\ell_a-\nabla\loss sum to zero over the dataset, so for j≠kj\ne k, averaging over the n(n−1)n(n-1) ordered pairs of distinct examples:

  4. Cov⁡(g)=1B2(B Σ−B(B−1)n−1 Σ)=n−Bn−1⋅ΣB\Cov(\mathbf g)=\frac1{B^2}\Big(B\,\Sigma-\frac{B(B-1)}{n-1}\,\Sigma\Big)=\frac{n-B}{n-1}\cdot\frac{\Sigma}{B}

    Adding the BB variance terms and the B(B−1)B(B-1) cross terms gives the finite-population correction. It vanishes at B=nB=n, where the batch is the whole dataset and the gradient is exact.

In deep learning B≪nB\ll n, so the correction is negligible and the noise is Σ/B\Sigma/B for all practical purposes. What matters is its size relative to the signal, the ratio Tr⁡Σ/(B∥∇L∥2)\Tr\Sigma/(B\norm{\nabla\loss}^2): 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 BB.

Predict before you look

A dataset has n=1,001n=1{,}001 examples, and you draw a batch of B=501B=501 without replacement. Compared with 501501 draws with replacement, by what factor is the covariance of the mini-batch gradient multiplied?

Show the answer

0.5

n−Bn−1=5001000=0.5\frac{n-B}{n-1}=\frac{500}{1000}=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 B=128B=128 and n=106n=10^6 the factor is 0.999870.99987, 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 n/Bn/B 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 SS sets the wall-clock time, as long as the hardware processes one batch in roughly constant time, and the number of examples E=BSE=BS 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?

DerivationProof
  1. L(θt+1)≤L(θt)−η ∇L(θt)⊤gt+Λη22∥gt∥2\loss(\boldsymbol\theta_{t+1})\le\loss(\boldsymbol\theta_t)-\eta\,\nabla\loss(\boldsymbol\theta_t)^\top\mathbf g_t+\frac{\Lambda\eta^2}{2}\norm{\mathbf g_t}^2

    Smoothness bounds the loss after a step by a quadratic upper model:

  2. E[L(θt+1)]≤L(θt)−η2∥∇L(θt)∥2+Λη2σ22B\E\big[\loss(\boldsymbol\theta_{t+1})\big]\le\loss(\boldsymbol\theta_t)-\frac\eta2\norm{\nabla\loss(\boldsymbol\theta_t)}^2+\frac{\Lambda\eta^2\sigma^2}{2B}

    Take the expectation over the batch. Unbiasedness turns the middle term into η∥∇L∥2\eta\norm{\nabla\loss}^2, and E∥gt∥2=∥∇L∥2+E∥gt−∇L∥2\E\norm{\mathbf g_t}^2=\norm{\nabla\loss}^2+\E\norm{\mathbf g_t-\nabla\loss}^2. Since η≤1/Λ\eta\le1/\Lambda gives η−Λη2/2≥η/2\eta-\Lambda\eta^2/2\ge\eta/2:

  3. δt+1≤(1−ημ) δt+Λη2σ22B\delta_{t+1}\le(1-\eta\mu)\,\delta_t+\frac{\Lambda\eta^2\sigma^2}{2B}

    The PL inequality converts gradient size into suboptimality. With δt=E[L(θt)]−L⋆\delta_t=\E[\loss(\boldsymbol\theta_t)]-\loss^\star, after taking the full expectation:

  4. δ⋆=Λη2σ2/(2B)ημ=ηΛσ22μB,δt−δ⋆≤(1−ημ)t (δ0−δ⋆)\delta^\star=\frac{\Lambda\eta^2\sigma^2/(2B)}{\eta\mu}=\frac{\eta\Lambda\sigma^2}{2\mu B},\qquad\delta_t-\delta^\star\le(1-\eta\mu)^t\,(\delta_0-\delta^\star)

    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 ημ\eta\mu per step; the second is the noise ball, proportional to η/B\eta/B. Halving η\eta 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 1/t1/t, SGD does converge, at rate O(1/t)\order{1/t} 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 β\beta of the previous step to the gradient step. Libraries write it with a velocity buffer instead; the two forms are the same algorithm:

θt+1=θt−η gt+β (θt−θt−1)⟺vt+1=βvt+gt,θt+1=θt−η vt+1\boldsymbol\theta_{t+1}=\boldsymbol\theta_t-\eta\,\mathbf g_t+\beta\,(\boldsymbol\theta_t-\boldsymbol\theta_{t-1})\quad\Longleftrightarrow\quad\mathbf v_{t+1}=\beta\mathbf v_t+\mathbf g_t,\quad\boldsymbol\theta_{t+1}=\boldsymbol\theta_t-\eta\,\mathbf v_{t+1}
Substitute θt−θt−1=−ηvt\boldsymbol\theta_t-\boldsymbol\theta_{t-1}=-\eta\mathbf v_t to pass from one form to the other. Unrolled, vt+1=∑k≥0βkgt−k\mathbf v_{t+1}=\sum_{k\ge0}\beta^k\mathbf g_{t-k}: the step is a geometrically weighted sum of past gradients, with a memory of about 1/(1−β)1/(1-\beta) steps.

Nesterov momentum evaluates the gradient where the momentum is about to carry the parameters, so it can brake before it overshoots: vt+1=βvt+∇L(θt−ηβvt)\mathbf v_{t+1}=\beta\mathbf v_t+\nabla\loss(\boldsymbol\theta_t-\eta\beta\mathbf v_t), then θt+1=θt−ηvt+1\boldsymbol\theta_{t+1}=\boldsymbol\theta_t-\eta\mathbf v_{t+1}. 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 β\beta, 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: θ←θ−η(gt+βvt+1)\boldsymbol\theta\leftarrow\boldsymbol\theta-\eta(\mathbf g_t+\beta\mathbf v_{t+1}).

python
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 * g

Two 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 η\eta changes during a run. And the buffer sums gradients without the factor 1−β1-\beta of an exponential moving average: it is 1/(1−β)1/(1-\beta) times larger than momentum written as m←βm+(1−β)g\mathbf m\leftarrow\beta\mathbf m+(1-\beta)\mathbf g, so it needs a learning rate 1−β1-\beta 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).

DerivationThe effective step and the square-root speed-up
  1. vt→∑k≥0βkg=g1−β,effective step η1−β\mathbf v_t\to\sum_{k\ge0}\beta^k\mathbf g=\frac{\mathbf g}{1-\beta},\qquad\text{effective step }\frac{\eta}{1-\beta}

    On a constant slope, gt=g\mathbf g_t=\mathbf g, the velocity converges to a geometric series, so momentum multiplies the step by 1/(1−β)1/(1-\beta): ten for β=0.9\beta=0.9, a hundred for β=0.99\beta=0.99.

  2. max⁡λ∈[μ,Λ]∣1−ηλ∣=κ−1κ+1⟹about κ/2 steps per factor e\max_{\lambda\in[\mu,\Lambda]}\abs{1-\eta\lambda}=\frac{\kappa-1}{\kappa+1}\quad\Longrightarrow\quad\text{about }\kappa/2\text{ steps per factor }e

    On a quadratic whose Hessian eigenvalues lie in [μ,Λ][\mu,\Lambda], with condition number κ=Λ/μ\kappa=\Lambda/\mu, gradient descent multiplies the error along eigenvalue λ\lambda by 1−ηλ1-\eta\lambda. The best constant step, η=2/(Λ+μ)\eta=2/(\Lambda+\mu), balances the two extreme eigenvalues:

  3. ∣z∣=βwhenever(1−β)2≤ηλ≤(1+β)2\abs z=\sqrt\beta\qquad\text{whenever}\qquad(1-\sqrt\beta)^2\le\eta\lambda\le(1+\sqrt\beta)^2

    With momentum, each eigen-direction follows a two-term recurrence et+1=(1+β−ηλ) et−β et−1e_{t+1}=(1+\beta-\eta\lambda)\,e_t-\beta\,e_{t-1}, with characteristic equation z2−(1+β−ηλ)z+β=0z^2-(1+\beta-\eta\lambda)z+\beta=0. When its roots are complex, they are conjugates whose product is β\beta, so every such direction contracts by exactly β\sqrt\beta per step, whatever its curvature:

  4. β=κ−1κ+1,η=4(Λ+μ)2⟹about κ/2 steps per factor e\sqrt\beta=\frac{\sqrt\kappa-1}{\sqrt\kappa+1},\qquad\eta=\frac{4}{(\sqrt\Lambda+\sqrt\mu)^2}\quad\Longrightarrow\quad\text{about }\sqrt\kappa/2\text{ steps per factor }e

    Choose η\eta and β\beta so that this window is exactly [ημ,ηΛ][\eta\mu,\eta\Lambda]. Dividing its endpoints gives κ=(1+β1−β)2\kappa=\big(\tfrac{1+\sqrt\beta}{1-\sqrt\beta}\big)^2, hence Polyak's tuning:

The speed-up is real but specific: it holds asymptotically on quadratics, with exact gradients and tuned η\eta and β\beta. 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 1−1/κ1-1/\sqrt\kappa 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 η/(1−β)\eta/(1-\beta). That is why deep learning uses β=0.9\beta=0.9 as a default instead of tuning it to κ\kappa, and why momentum pays off mostly at large batch sizes.

Predict before you look

A quadratic has condition number κ=104\kappa=10^4. 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 κ/2=5000\kappa/2=5000 steps per factor ee, since ln⁡κ+1κ−1≈2/κ\ln\frac{\kappa+1}{\kappa-1}\approx2/\kappa; heavy ball needs about κ/2=50\sqrt\kappa/2=50, since ln⁡κ+1κ−1≈2/κ\ln\frac{\sqrt\kappa+1}{\sqrt\kappa-1}\approx2/\sqrt\kappa. The ratio is κ=100\sqrt\kappa=100.

Finding a good learning rate

Theory says η<2/λmax⁡\eta<2/\lambda_{\max}, but nobody knows λmax⁡\lambda_{\max} 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 η\eta 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 0.90.9, using the linear scaling rule η=0.1⋅B/256\eta=0.1\cdot B/256 and a warmup that raised the rate linearly from 0.10.1 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 kk steps, then kk steps with batch BB and rate η\eta move the parameters about as far as one step with batch kBkB and rate kηk\eta; equivalently, the ratio η/B\eta/B sets how much noise accompanies each unit of progress. The argument fails early in training, when gradients change quickly (hence warmup), and once kηk\eta reaches the stability threshold 2/λmax⁡2/\lambda_{\max}, which no amount of averaging lifts. For Adam the analogous rule is closer to η∝B\eta\propto\sqrt B (Malladi, Lyu, Panigrahi & Arora, 2022).

Check your understanding

A recipe trains with batch size 256 at peak rate 0.10.1 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?

  1. Keep η=0.1\eta=0.1: the per-example gradients have not changed
  2. Use η=0.4\eta=0.4, since the noise standard deviation fell by 16=4\sqrt{16}=4
  3. Use η=1.6\eta=1.6, reached by a warmup over the first few epochs; the run has 16 times fewer steps
  4. Use η=1.6\eta=1.6 from the first step, with 16 times as many steps
Show the answer

C. Use η=1.6\eta=1.6, reached by a warmup over the first few epochs; the run has 16 times fewer steps

4096/256=164096/256=16, so the target rate is 1.61.6. 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 1.61.6 immediately often diverges, which is what the warmup prevents.

Key takeaways

  • The mini-batch gradient is unbiased with covariance Σ/B\Sigma/B (times n−Bn−1\frac{n-B}{n-1} without replacement). Its relative noise Tr⁡Σ/(B∥∇L∥2)\Tr\Sigma/(B\norm{\nabla\loss}^2) grows as training proceeds.
  • Under smoothness and the PL inequality, constant-step SGD satisfies EL−L⋆≤(1−ημ)tδ0+ηΛσ2/(2μB)\E\loss-\loss^\star\le(1-\eta\mu)^t\delta_0+\eta\Lambda\sigma^2/(2\mu B): linear progress down to a noise ball proportional to η/B\eta/B. Only a decaying step converges.
  • Momentum, v←βv+g\mathbf v\leftarrow\beta\mathbf v+\mathbf g and θ←θ−ηv\boldsymbol\theta\leftarrow\boldsymbol\theta-\eta\mathbf v, has effective step η/(1−β)\eta/(1-\beta). Tuned heavy ball contracts a quadratic at κ−1κ+1\frac{\sqrt\kappa-1}{\sqrt\kappa+1} per step instead of κ−1κ+1\frac{\kappa-1}{\kappa+1}; 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 η∝B\eta\propto B 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.

Question 1

A mini-batch of BB examples is drawn independently and uniformly from the training set. What are the mean and covariance of its gradient g\mathbf g?

  1. Mean ∇L/B\nabla\loss/B, covariance Σ/B2\Sigma/B^2
  2. Mean ∇L\nabla\loss, covariance Σ\Sigma, whatever BB is
  3. Mean ∇L\nabla\loss, covariance Σ/B\Sigma/B
  4. Mean ∇L\nabla\loss, covariance Σ/B\Sigma/\sqrt B
Show the answer

C. Mean ∇L\nabla\loss, covariance Σ/B\Sigma/B

Each term has mean ∇L\nabla\loss, so the average does too. The BB independent terms each contribute covariance Σ\Sigma, and averaging divides it by BB. It is the standard deviation that falls like 1/B1/\sqrt B.

Question 2

In the noise-ball bound (1−ημ)tδ0+ηΛσ2/(2μB)(1-\eta\mu)^t\delta_0+\eta\Lambda\sigma^2/(2\mu B), what does halving the constant step η\eta do?

  1. It halves the floor, but forgetting the starting point takes about twice as many steps
  2. It halves the floor and speeds up the first phase
  3. It leaves the floor unchanged, because the floor depends only on BB
  4. 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 η\eta, and the contraction factor 1−ημ1-\eta\mu moves toward 11, so the transient decays about half as fast. That trade-off is why the step should be large early and small late.

Question 3

You train with momentum β=0.99\beta=0.99 and learning rate η=0.001\eta=0.001. Where the gradient stays roughly constant for many steps, how large is the effective step, as a multiple of the gradient?

  1. 0.0010.001
  2. 0.000990.00099
  3. 0.0990.099
  4. 0.10.1
Show the answer

D. 0.10.1

The velocity approaches g/(1−β)=100 g\mathbf g/(1-\beta)=100\,\mathbf g, so the step is η⋅100 g=0.1 g\eta\cdot100\,\mathbf g=0.1\,\mathbf g. Raising β\beta from 0.90.9 to 0.990.99 at fixed η\eta multiplies the effective learning rate by ten, so the two must be tuned together.

Question 4

What distinguishes Nesterov momentum from heavy-ball momentum?

  1. It uses a larger momentum coefficient
  2. It evaluates the gradient at the look-ahead point θt−ηβvt\boldsymbol\theta_t-\eta\beta\mathbf v_t, where momentum is about to carry the parameters
  3. It divides each coordinate's step by a running average of squared gradients
  4. It resets the velocity to zero whenever the loss increases
Show the answer

B. It evaluates the gradient at the look-ahead point θt−ηβvt\boldsymbol\theta_t-\eta\beta\mathbf v_t, 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 1−1/κ1-1/\sqrt\kappa on every smooth, strongly convex function, where heavy ball's accelerated guarantee covers only quadratics.

Go deeper

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).