Momentum and Nesterov acceleration
Before this lesson: lesson 03 (the factor of gradient descent on a quadratic and the best step ), and linear algebra 05 (eigenvalues of a matrix, complex eigenvalues). For the folded part on conjugate gradients: linear algebra 14 (Krylov subspaces and CG). Time: about 75 minutes, plus the notebook.
Why this matters #
Every optimizer used to train large models has a momentum term: SGD with momentum=0.9, and Adam's
(lesson 06). On an ill-conditioned
problem gradient descent needs about steps per digit of accuracy, and momentum about
. Nesterov's method is the version with a guarantee for all smooth convex functions, and no
method that only uses gradients can be faster in the worst case. It comes back in FISTA for the lasso
(lesson 09). Conjugate gradients push the same idea to the
limit on quadratics: they solve the large sparse linear systems of PDE solvers and the inner systems of
Newton-type methods.
1. Predict first #
2. The picture #
The zig-zag problem again. In a narrow valley the steep direction (curvature ) forces a step of about , or gradient descent diverges. Along the flat direction (curvature ) such a step makes progress of only about of the distance per step.
Heavy ball. Polyak's heavy-ball method adds a fraction of the last step:
Here is the step size and is the momentum coefficient. With it is gradient descent. Think of a heavy ball rolling in the valley. Across the valley the gradient flips sign from step to step, so the added parts cancel. Along the valley the gradient keeps its direction, so they add up.
The effective step. Suppose the gradient is a constant . Write for the step. Then . The steps approach the fixed point , that is,
For the step becomes : ten times the gradient-descent step.
Momentum as a filter. Unroll the step: . The step is a weighted sum of all past gradients, with weights that decay like . A part of the gradient that keeps its sign adds up to about times its size. A part that flips sign at every step adds up to about times its size. So momentum is a low-pass filter: it keeps the slow, consistent part of the gradient and damps the fast, oscillating part.
Press Play and watch the three paths: gradient descent (blue), heavy ball (orange) and Nesterov (violet), each with its theory parameters. The chart shows ; the dashed lines are the theory factors . Heavy ball first overshoots far across the valley, then wins by a wide margin. Increase and see the gap grow. With same η and β all three share one step (the slider is the step in units of ) and one . Then choose Rosenbrock: heavy ball with the parameters that are best near the minimizer diverges, while Nesterov converges.
The gradient stays equal to for many steps. Heavy ball uses and . About how long is one step after many steps?
The steps satisfy , which approaches . The value is only the second step. The growth stops because each old step is multiplied by .
One eigen-direction: a damped oscillator. Take . Then , and heavy ball becomes
This is a second-order recurrence: the new value depends on the two last values. Such a recurrence behaves like a damped spring. Look for solutions . They must satisfy the characteristic polynomial
Its two roots decide everything: (or for a double root).
- Over-damped (too little momentum for this ): two real positive roots. creeps toward 0 without oscillating, like gradient descent with a small step.
- Critically damped: a double root. The fastest decay without oscillation.
- Under-damped (much momentum): complex roots. oscillates around 0 and the oscillation decays.
Move and , or use the presets. The orange dots are the heavy-ball iterates , the faint blue line is gradient descent with the same , and the dashed lines are , where is the size of the largest root. In the under-damped case the roots are complex and their size is exactly , whatever is. Find the critically damped point for : it is at .
A quadratic in dimensions is such oscillators, one per eigenvalue of the Hessian. They share one and one . The best choice makes all of them decay at the same rate. Section 3 computes it.
3. Definitions and main results #
Throughout: with symmetric and its eigenvalues in , . The minimizer is , the error is , and .
Theorem 1 (heavy ball on a quadratic) #
With
every eigen-component of the heavy-ball error satisfies , with constants that depend on the start, and
These are Polyak's parameters.
Why this is true, in one sentence. The product of the two roots of is always ; when the roots are complex, both have size ; so we choose and to make the roots complex for every , with the smallest possible .
Proof.
- , so .
- Write . In the eigenbasis the components do not interact. For one eigenvalue with component :
is the iteration matrix: the second row only copies down. 3. The eigenvalues of solve . The product of the two roots is . Complex roots are conjugates, and , so then and , whatever is. 4. The roots are complex (or double) when the discriminant is : , that is, . This is the band . 5. We want every in the band, with the smallest possible . So we ask for equality at both ends: and . 6. Add the two equations: , so . Divide them: , so . 7. Now every has spectral radius . At and the root is double, and the component there is : the same rate, up to a factor .
The roots in the complex plane. For many eigenvalues between and , the figure draws both roots of as orange dots. The solid circle is the unit circle (outside it: divergence); the dashed circle has radius . With Polyak's parameters every root lies on the dashed circle. Make smaller: the roots for near leave the circle along the real axis, and the largest root size grows. Press β = 0 to see plain gradient descent, whose roots all lie on the real axis.
Compare with gradient descent. For heavy ball, . For gradient descent with its best step, . Per digit of accuracy, gradient descent needs steps and heavy ball .
Stability with momentum. Outside the band of step 4 one real root is larger than in size. Heavy ball on a quadratic converges from every start exactly when
So momentum also raises the stability limit of the step, from to . (These are the conditions for both roots of to lie inside the unit circle, for every eigenvalue.)
Why the factor matters. At a double root the error is , not . The factor grows while shrinks, so the error can grow at first, and the measured count is larger than . In the predict-first example this is 44 steps instead of 34.
Steps against , on log-log axes. Move the marker. Gradient descent (best step) lies on a line of slope 1: steps . Heavy ball and Nesterov lie on lines of slope : steps . The dashed lines are the formulas and . Conjugate gradient (grey) is never worse than heavy ball and is often better, because it adapts to the actual eigenvalues (folded part at the end of section 3).
A quadratic has . Gradient descent with its best step needs 691 steps for a factor . Which count is closest for heavy ball with Polyak's parameters?
, and . The factor from the double roots adds some steps: from on the count is 93. "About 10" is without the factor .
Nesterov's accelerated gradient #
Nesterov's method takes the gradient at an extrapolated look-ahead point instead of at . Start with . For :
So is a plain gradient step. Two choices of :
- for convex : , , . It starts at 0 and grows toward 1;
- for -strongly convex : the constant .
Compare with heavy ball: heavy ball computes the gradient at and then adds the momentum. Nesterov first moves with the momentum, then computes the gradient where it lands. This look-ahead corrects the step before the overshoot happens.
Theorem 2 (Nesterov's rates) #
For every -smooth convex with a minimizer (not only quadratics), the convex choice of gives
(Beck and Teboulle 2009, Thm 4.4). If is also -strongly convex, the constant gives
(Bubeck, Thm 3.18). Since , this is about . Gradient descent gets only and (lesson 03). The proofs use estimate sequences or a potential function (Bubeck, §3.7); here we only state the results.
On a quadratic you can see the . Per eigenvalue , Nesterov's recursion with step is . At its characteristic polynomial has a double root . For larger the roots are complex with , and at both roots are 0. So on quadratics the factor is exactly (Lessard, Recht and Packard, Prop. 1). This is slower than heavy ball's , but it comes with a proof for every smooth strongly convex .
The loss is not monotone. Gradient descent with step decreases at every step. Nesterov's method does not: can go up for a while. Example: the convex choice of on from gives and (checked in the notebook). The bound of Theorem 2 still holds at every step; only the path to it has ripples.
You run Nesterov's method (convex choice of ) and see at some step. What does this tell you?
Momentum can carry the iterate past the minimum along some direction, so can rise for a few steps. Theorem 2 bounds at every , but it does not say that decreases. Monotone decrease is a property of plain gradient descent with (descent lemma), not of accelerated methods.
Lower bounds: why these rates are the best possible #
Take any method whose iterates satisfy : it moves only along gradients it has seen. Gradient descent, heavy ball, Nesterov and CG all do. Bubeck (§3.5) proves:
- for there is an -smooth convex quadratic on with (Thm 3.14);
- there is an -smooth, -strongly convex function with (Thm 3.15). Bubeck numbers the start ; we write both bounds with the start .
Why. The hard function is a "chain" quadratic with a tridiagonal . A point that is nonzero only in its first coordinates has a gradient that is nonzero only in the first coordinates. So after gradients, the iterate is still zero in all later coordinates, but is not. Information travels one coordinate per step.
So Nesterov's method is optimal up to constants: in the convex case both bounds are of order (their ratio tends to ), and in the strongly convex case both need steps.
Why heavy ball has no global guarantee #
The proof of Theorem 1 uses one fixed matrix per eigenvalue. On a function that is not quadratic, the curvature changes from step to step, so the error is multiplied by a different matrix each time. Each matrix has spectral radius at most , but the matrices are not symmetric, and a product of such matrices can grow.
The counterexample of Lessard, Recht and Packard (2016, §4.6). A convex 1D function with and (its second derivative is 25, then 1, then 25):
With Polyak's parameters for , and , and a start , heavy ball falls into a cycle and never converges: it repeats forever (section 5 checks it). Nesterov's method with and converges on the same function, as Theorem 2 promises.
Goujaud, Taylor and Dieuleveut (2023) prove more: for every choice of constant parameters, heavy ball either does not accelerate on quadratics or fails to converge on some smooth strongly convex function. Locally it is fine: if is twice differentiable and , heavy ball started close enough to converges at a rate close to its quadratic rate (Polyak 1964). This is one reason why it works well in practice.
is smooth and strongly convex with and , but not quadratic. You run heavy ball with , . What can you say for sure?
Theorem 1 uses one fixed matrix per eigenvalue, which holds only for quadratics. On the Lessard–Recht–Packard function with exactly these constants, heavy ball repeats a 3-cycle. Near the function looks quadratic, so heavy ball started there converges. For a guarantee on the whole class, use Nesterov's method.
In PyTorch #
torch.optim.SGD(params, lr=η, momentum=β) keeps a buffer and does
This is heavy ball: .
With nesterov=True it uses . This is Nesterov's method with a
constant , written in the look-ahead variable: PyTorch's parameter after steps equals above
(checked in the notebook). We write the momentum as ; PyTorch's documentation calls it .
The Krylov view: gradient descent, heavy ball and conjugate gradients
Let and , the Krylov subspace. Write for the -norm.
- Gradient descent, heavy ball and Nesterov add to the current point a gradient (, or for Nesterov) and a multiple of the last step. By induction, .
- Hence for a polynomial of degree at most with . Gradient descent: . Heavy ball: , , . This is the Chebyshev iteration with its coefficients frozen at their limit values, so is close to the scaled Chebyshev polynomial, the polynomial with the smallest maximum on .
- Expand in the eigenvectors of . Then .
- Conjugate gradient (CG) chooses to minimize (linear algebra 14). So it uses the best polynomial for this spectrum and this . The heavy-ball polynomial is one of the candidates, so for every . The same holds against gradient descent and Nesterov.
- Two consequences. CG has the same worst-case bound, with , without knowing and . And if has distinct eigenvalues, is zero on the whole spectrum, so CG is exact after steps.
The CG figure in linear algebra 14 shows this on a 2D quadratic: CG reaches in 2 steps (two distinct eigenvalues), while steepest descent zig-zags.
Why is CG not used to train neural networks? Its optimality needs exact gradients of one fixed quadratic. Minibatch gradients are noisy and the loss is not quadratic, so conjugacy is lost. Momentum keeps working with noisy gradients and changing curvature.
Answers to section 1. (1) About 45: section 4 counts 44. The factor per step is instead of ; the factor from the double roots costs about 10 extra steps. (2) Not always. The Lessard–Recht–Packard function has exactly and , and heavy ball with these parameters cycles on it. Nesterov's method converges on it.
4. Worked example #
, , . So , , . "Steps" means the first with .
| Method | Parameters | Factor per step | Steps |
|---|---|---|---|
| gradient descent | 173 | ||
| heavy ball | , | 44 | |
| Nesterov | , | 73 | |
| conjugate gradient | none | — | 2 |
Gradient descent. Each coordinate is multiplied by : by and by . So , and .
Heavy ball, by hand. Step 1 has no momentum yet (): . The steep coordinate overshoots. Step 2:
For : , so the polynomial is . For : , so it is . Both roots are double, so each component is . The first two values fix and :
Check at : ✓ and ✓. The norm first grows, to at , then falls fast. Because of the factor we need 44 steps, not .
Nesterov. The step multiplies the steep coordinate by , so it is zero after one step and stays zero. The flat coordinate has the double root : , so and . That gives 73 steps.
Conjugate gradient. There are two distinct eigenvalues, so the polynomial is zero on both: exactly.
The polynomials after two steps, at and . Gradient descent, : 0.852 and 0.852. Heavy ball, : 0.741 and 1.926. CG: 0 and 0. Early on, heavy ball is even worse than gradient descent along the steep direction; CG is never worse than either.
5. In code #
NumPy checks the worked example and the counterexample. The notebook has these cells and the exercises.
import numpy as np
mu, L = 1.0, 25.0
s = np.sqrt(L / mu) # sqrt(kappa) = 5
eta = 4 / (np.sqrt(L) + np.sqrt(mu)) ** 2 # 1/9
beta = ((s - 1) / (s + 1)) ** 2 # 4/9
# 1) spectral radius of the 2x2 heavy-ball matrix, inside and outside [mu, L]
for lam in [0.5, 1, 9, 25, 30]:
T = np.array([[1 + beta - eta * lam, -beta], [1, 0]])
print(lam, round(np.abs(np.linalg.eigvals(T)).max(), 4))
# 0.5 0.8889 | 1 0.6667 | 9 0.6667 | 25 0.6667 | 30 1.6134
# 2) steps until ||e_k|| <= 1e-6 ||e_0|| on diag(1, 25) from (1, 1)
lam = np.array([mu, L])
def steps(update):
e, e_prev, y, k = np.ones(2), np.ones(2), np.ones(2), 0
while np.linalg.norm(e) > 1e-6 * np.sqrt(2):
e, e_prev, y = update(e, e_prev, y)
k += 1
return k
gd = lambda e, ep, y: ((1 - 2 / (mu + L) * lam) * e, e, y)
hb = lambda e, ep, y: (e - eta * lam * e + beta * (e - ep), e, y)
def nag(e, ep, y, b=(s - 1) / (s + 1)):
x = y - lam * y / L # gradient step at the look-ahead point
return x, e, x + b * (x - e)
print(steps(gd), steps(hb), steps(nag)) # 173 44 73
# 3) the Lessard-Recht-Packard function: mu = 1, L = 25, not a quadratic
def grad(x):
return 25 * x if x < 1 else (x + 24 if x < 2 else 25 * x - 24)
x, x_prev = 3.3, 3.3
for k in range(1000):
x, x_prev = x - eta * grad(x) + beta * (x - x_prev), x
print([round(float(v), 3) for v in (x_prev, x)]) # [0.647, -1.802]: part of the cycle 2.116 -> 0.647 -> -1.802
The cycle has length 3: the iterates repeat forever. The notebook also runs Nesterov's method on this function and checks that it converges.
6. Where it shows up #
- Training neural networks.
torch.optim.SGD(momentum=0.9)and Adam's : along a consistent direction the step is . With noisy minibatch gradients the gain over gradient descent is smaller, because the noise, not , limits the progress (Goh, "Why Momentum Really Works", section on stochastic gradients; lesson 05).nesterov=Truegives Nesterov's method. - Sparse and nonsmooth problems. FISTA (lesson 09) is Nesterov's method plus a proximal step. It is a standard solver for the lasso and for compressed sensing and imaging inverse problems.
- Scientific computing. Preconditioned CG solves the sparse symmetric positive definite systems of discretized elliptic PDEs (Poisson, implicit diffusion) and the Newton systems of Newton-CG with Hessian-vector products (lesson 10). In weather forecasting, the inner loop of incremental 4D-Var minimizes a quadratic cost with a preconditioned CG or Lanczos method.
7. Common mistakes #
- Expecting the rate of Polyak's parameters on a problem that is not quadratic. It is proven only for quadratics (and near a minimizer). For general functions heavy ball can cycle.
- Taking Nesterov's gradient at . That is heavy ball. Nesterov uses the look-ahead point .
- Ignoring the factor . At double roots the error is . It can grow at first, and a rate measured over a short window looks worse than .
- Keeping the gradient-descent stability limit. With momentum the limit on a quadratic is , not . And , not , is the effective step along a consistent direction: when you add momentum 0.9, divide the learning rate by about 10 to keep the same effective step.
- Expecting to decrease at every step. Heavy ball and Nesterov are not monotone.
- Calling CG "always better". It is optimal only for exact gradients of one fixed quadratic.
8. Check yourself #
- The eigenvalues lie in . Give Polyak's , and factor, and the gradient-descent factor
with its best step.
Answer
, , : , , factor . Gradient descent: . The factors depend only on ; the step scales like . - Why is for every inside the band ?
Answer
The product of the two roots of is . Inside the band the roots are complex conjugates (or a double root), so they have the same size, and . - You run heavy ball with , (tuned for ), but the true largest eigenvalue is 30. What
happens?
Answer
, which is above . One real root has size , so heavy ball diverges along that eigenvector. - Write one step of
torch.optim.SGD(lr=0.1, momentum=0.9)from with gradient . What is the change in the parameters?Answer
, and the parameters change by . - is symmetric positive definite with only 3 distinct eigenvalues. How many CG steps give
the exact solution, and why does this not contradict the lower bounds?
Answer
At most 3: vanishes on the spectrum. The lower bounds hold for a specific hard function with many distinct eigenvalues (and ); they are worst-case statements, not statements about every quadratic.
Write the heavy-ball update.
, with and .
Heavy ball with and a constant gradient : what step does it approach?
.
Polyak's parameters for heavy ball on a quadratic with eigenvalues in ?
and .
Factor per step of heavy ball with Polyak's parameters?
.
Why do the complex roots of have size ?
The product of the roots is , and complex roots are conjugates with equal size, so .
Steps per digit of accuracy: gradient descent against momentum?
About for gradient descent, about for heavy ball or Nesterov (constant factors aside).
Stability condition of heavy ball on a quadratic?
and .
Write Nesterov's method (step ).
, : the gradient is taken at the look-ahead point.
Nesterov's rate for an -smooth convex ?
, which matches the lower bound up to a constant.
Why has heavy ball no global guarantee?
Its proof uses a fixed matrix per eigenvalue. When the curvature changes, products of different matrices can grow; the Lessard–Recht–Packard function makes it cycle.
9. Interview angle #
- "Why does momentum speed up gradient descent?" — On a quadratic each eigen-direction becomes a two-term recurrence. The best parameters give all roots the size , so the step count per digit drops from to . Intuition: momentum averages the gradients, so the zig-zag across the valley cancels and the motion along it adds up.
- "Heavy ball or Nesterov?" — Gradient at or at the look-ahead point. Heavy ball's acceleration is proven only for quadratics; Nesterov is optimal for all smooth (strongly) convex functions.
- "What is the best possible first-order rate?" — for smooth convex functions, and steps for smooth strongly convex ones; Nesterov reaches both up to constants.
- "What does momentum 0.9 do to the step size?" — Up to times larger along consistent directions, and the stability limit on a quadratic becomes .
10. Practice #
The notebook for this lesson runs in Colab. It has four exercises, each with a check cell and a folded solution:
- Build the heavy-ball matrix and check its spectral radius against inside the band and outside it.
- Implement heavy ball and Nesterov, and count steps against gradient descent for .
- Run Nesterov's method (convex choice of ) on a convex least-squares problem; check the bound and find the steps where goes up.
- Implement conjugate gradients and check that CG is never worse than heavy ball in the -norm.
11. Watch and read #
- Gabriel Goh, "Why Momentum Really Works" (Distill, 2017): interactive figures of the damped oscillator, the best parameters, and the lower bound ("the limits of descent").
- Sébastien Bubeck, Convex Optimization: Algorithms and Complexity, free: §3.5 (lower bounds, Thm 3.14–3.15) and §3.7 (Nesterov's method, Thm 3.18–3.19).
- Lessard, Recht and Packard, "Analysis and Design of Optimization Algorithms via Integral Quadratic Constraints": §2.2 (Prop. 1, rates on quadratics) and §4.6 (the heavy-ball counterexample).
- Goujaud, Taylor and Dieuleveut, "Provable non-accelerations of the heavy-ball method" (2023).
- Beck and Teboulle, "A Fast Iterative Shrinkage-Thresholding Algorithm for Linear Inverse Problems", SIAM Journal on Imaging Sciences 2(1), 2009: Thm 4.4 is the bound.
- PyTorch,
torch.optim.SGD: the exact update withmomentumandnesterov.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.