Explain why adding inertia to gradient descent changes dependence on κ to √κ: exact spectral analysis of Polyak's heavy ball on quadratics, Nesterov accelerated gradient at O(1/k²), and its matching lower bound. Conclude with the damped differential-equation view and adaptive restarts.
After this lesson you can
Write heavy ball and Nesterov in two-sequence and velocity forms and translate between them.
Analyze heavy ball on a quadratic using the 2×2 iteration matrix for each eigendirection, obtaining optimal parameters and rate (√κ − 1)/(√κ + 1).
State the first-order complexity lower bound and explain Nesterov's worst-case function.
Prove the O(1/k²) rate of Nesterov's method on L-smooth convex functions using a Lyapunov function.
Relate the method to the ODE ẍ + (3/t)ẋ + ∇f(x) = 0 and justify adaptive restart when oscillations occur.
In lesson 7 you saw that on a quadratic gradient descent contracts error in each eigendirection by factor 1−ηλi (GD dynamics on quadratics). That factor contains the problem. The step must be below 2/L to prevent the highest-curvature direction exploding, and with such a step the lowest-curvature direction μ contracts only by 1−ημ>1−2/κ each iteration, with κ=L/μ the condition number. With κ=104, modest for logistic regression with correlated features, reducing error 106 times costs at least about 7⋅104 iterations, even with the best step. In the language of rates, linear GD convergence requires O(κlog(1/ε)) iterations, and no step choice fixes it.
Watch GD in a narrow valley. The gradient points nearly perpendicular to the floor, so the method bounces between walls and advances little along the valley. Gradient components across the valley change sign each iteration and cancel when added over several iterations. Components along the valley always point the same way and accumulate. A moving average of recent gradients keeps the latter and erases the former. This is momentum: a massive ball rolling through the landscape of f with some friction, rather than a memoryless walker looking only at the ground underfoot.
Three questions guide the lesson. How much inertia should we use? Does it change only a constant or the exponent of κ? Is there a limit no first-order method can cross? The short answer: well-tuned momentum changes κ to κ, that change is optimal, and a second ingredient—evaluating the gradient at an extrapolated point (Nesterov)—is needed for it to hold beyond quadratics.
InteractiveThe ball in the valley
Gradient descent
Heavy ball
Nesterov
Valley
k = 84
Gradient descent: iterations to f−f⋆≤10−6(f0−f⋆)553
Heavy ball: iterations to f−f⋆≤10−6(f0−f⋆)64
Nesterov: iterations to f−f⋆≤10−6(f0−f⋆)71
κ and κ100 and 10.0
Heavy ball at λ=μcritical
Heavy ball at λ=Lunderdamped
Heavy ball is underdamped (or critically damped) throughout the spectrum [μ,L]: its rate is β, regardless of η or direction.
Three methods with the same η, β and starting point (drag it). Above, level curves and trajectories; below, f−f⋆ on a logarithmic scale. With initial settings (κ=100, η=1/L, β=0.82), gradient descent needs 553 iterations and the other two 64 and 71. Increase κ and compare how each counter grows. Then press “Optimal GD” and “Polyak”: why is Polyak's step so large that Nesterov diverges with it? Try high β in a smooth valley and watch heavy ball overshoot, then switch to nonquadratic Rosenbrock.
Take this from the figure. With well-tuned inertia, heavy ball and Nesterov reduce error by a much smaller factor than GD each step: at κ=100 they gain about 8 times in iterations, and the code shows the ratio grows as κ as κ increases. Heavy ball’s curve oscillates, as does Nesterov’s at high β: these are not descent methods. Settings for one do not work for the other.
Polyak’s heavy ball
The forms are identical because vk+1=xk+1−xk: velocity is the last displacement. With β=0 we recover GD. Two-step form shows what β does: carry a fraction of the previous movement. Velocity form explains the name: v is velocity of a particle receiving impulse −η∇f each step and losing fraction 1−β of velocity to friction.
Unrolling the recurrence shows what it really is. Since vk+1=−η∑j=0kβj∇f(xk−j),
xk+1=xk−ηj=0∑kβj∇f(xk−j).
Displacement is an exponentially weighted average of all past gradients, with weights βj. If the gradient were constant, effective step would be η∑jβj=η/(1−β): with β=0.9, ten times larger. If the gradient alternates sign (valley walls), the sum nearly cancels. That is the figure’s intuition; now quantify it.
Spectral analysis: a 2×2 matrix per eigendirection
All heavy-ball analysis on quadratics fits in a 2×2 matrix. Let f(x)=21x⊤Ax−b⊤x with symmetric A and spectrum in [μ,L], μ>0, and x⋆=A−1b. Error ek=xk−x⋆ satisfies ∇f(xk)=Aek, so
ek+1=((1+β)I−ηA)ek−βek−1.
Diagonalize A=QΛQ⊤ and let ek(i) be coordinate i of Q⊤ek. Coordinates decouple: each eigenvalue λ follows the scalar recurrence ek+1=(1+β−ηλ)ek−βek−1, i.e.
[ek+1ek]=Tλ[ekek−1],Tλ=[1+β−ηλ1−β0].
The trace of Tλ is τ=1+β−ηλ and determinant is β. Eigenvalues are roots of characteristic polynomial z2−τz+β, and speed in that direction is set by the larger magnitude, the spectral radiusρ(Tλ). With GD (β=0) the matrix is scalar 1−ηλ. Roots obey z1z2=β and z1+z2=τ, yielding everything.
Proof
The three regimes are the sign of discriminant τ2−4β of z2−τz+β. In the first, roots are τ/2±i4β−τ2/2, conjugates, so ∣z∣2=zzˉ=β. In the second, the double root is τ/2 with τ2/4=β. In the third, real roots have product β and the larger in magnitude is (∣τ∣+τ2−4β)/2, exceeding β because the smaller magnitude is β divided by the larger.
For stability, if roots are complex, ρ=β<1 whenever β<1, and ∣τ∣<2β<1+β by the mean inequality. If real, polynomial p(z)=z2−τz+β is a convex parabola and both roots lie in (−1,1) iff p(1)>0, p(−1)>0 and vertex τ/2 lies in (−1,1). Now p(1)=1−τ+β=ηλ and p(−1)=1+τ+β=2(1+β)−ηλ. Positivity of both gives ∣τ∣<1+β<2, including the vertex condition. In both cases the condition is 0<ηλ<2(1+β).
∎
Stability brings good news: inertia widens admissible steps from η<2/L in GD to η<2(1+β)/L, nearly double with β near 1. The underdamped regime holds the lesson’s key: while underdamped in every direction, speed is β and does not depend on curvature. A direction of curvature L and another with μ=L/104 contract at exactly the same rate. GD instead contracts each direction at its own rate 1−ηλ, tied to the worst.
InteractiveThe convergence plane
color: iterations (light = fast)
cursor (η,β)
best GD
Polyak optimum (hollow)
underdamped region boundaries
stability limit ηL=2(1+β)
roots at λ=μ
roots at λ=L
circle of radius β
intermediate roots
Method
Underdamped region boundaries
ρ at cursor (over [μ,L])0.9055
Iterations to reduce error by a factor of 106140
Best GD: ρ=(κ−1)/(κ+1)0.9802, 691 it.
Best heavy ball: ρ=(κ−1)/(κ+1)0.8182, 69 it.
All roots are complex (or repeated at critical damping) and lie on the circle of radius β=0.906: ρ depends only on β.
Heat map of iterations needed to reduce error 106 times versus step ηL (horizontal) and inertia β (vertical), using exact spectral radius over [μ,L]. Drag the cursor: at right are iteration-matrix roots for each λ against the unit circle. Inside the region between dashed curves all roots are complex and fall on the radius-β circle (dashed). Move the cursor to the vertex where curves cross and inspect both root sets for spectrum endpoints: what is special? Then switch to Nesterov and compare its best quadratic rate.
The figure answers where to put the cursor. The light region is where roots of both endpoints μ and L are complex (between dashed curves) and β is as small as possible. Curves intersect once. That point is optimal; calculate it next.
Polyak’s optimal parameters
For fixed η and β, speed over the spectrum is ρ(η,β)=maxλ∈[μ,L]ρ(Tλ). Function λ↦ρ(Tλ) equals β on underdamped interval [(1−β)2/η,(1+β)2/η] and grows outside, so the maximum occurs at an endpoint μ or L. This suggests where to seek the optimum, confirmed next.
Proof
Values. The region where a root of Tλ has magnitude β is τ2≤4β, i.e. (1−β)2≤ηλ≤(1+β)2. To contain all [μ,L] requires ημ≥(1−β)2 and ηL≤(1+β)2, requiring κ≤((1+β)/(1−β))2. The smallest β allowing it gives equality, κ=(1+β)/(1−β), hence β=(κ−1)/(κ+1)=q. At equality, ηL=(1+q)2, and since 1+q=2κ/(κ+1),
η=L(κ+1)24κ=μ(κ+1)24=(L+μ)24.
Optimality. Suppose some pair has ρ(η,β)=r; if r≥1 nothing remains, so let r<1. Then for λ=μ and λ=L, both roots of z2−τz+β have magnitude at most r; their product is β, so β≤r2. For real roots, ∣τ∣=∣z1+z2∣≤r+β/r, because ∣z1+β/z1∣ grows with ∣z1∣ for ∣z1∣≥β. For complex roots, ∣τ∣<2β≤r+β/r by the mean inequality. Both cases give ∣1+β−ηλ∣≤r+β/r for λ∈{μ,L}, i.e.
Dividing, κ≤(1−r)(1−β/r)(1+r)(1+β/r). This bound increases with β on [0,r2], and at β=r2 equals ((1+r)/(1−r))2. Hence κ≤(1+r)/(1−r), i.e. r≥q.
∎
Iteration count follows from q. Since −lnq=lnκ−1κ+1≈2/κ, reducing error by ε needs about 2κln(1/ε) iterations, versus 2κln(1/ε) for best GD (step 2/(L+μ) and rate (κ−1)/(κ+1)). With κ=100 and ε=10−6 these are 69 versus 691, factor κ=10. Polyak’s step is enormous: ηL=4/(1+1/κ)2≈3.31 for κ=100, nearly double GD’s 2/L limit. Inertia allows this, as stability showed; the cursor does it at the figure’s vertex.
Beyond quadratics: heavy ball’s fragility
None of the above holds if ∇f is nonlinear. The analysis depends on the iteration matrix being the same each step. On a general function the “matrix” varies with position, and each having spectral radius below 1 guarantees nothing about their products. This is not a technicality. Lessard, Recht and Packard (arXiv:1408.3595) give a strongly convex f:R→R, with μ=1 and L=25, and continuous piecewise-linear gradient:
f′(x)=⎩⎨⎧25xx+2425x−24x<1,1≤x<2,x≥2.
With Polyak parameters η=1/9 and β=4/9, heavy ball starting at x0=3.3does not converge to minimum x⋆=0: it enters a limit cycle. Local curvature always lies between 1 and 25, yet heavy ball tuned to the worst quadratic does not approach the minimum. Nesterov and GD converge on the same function; check in the first code section.
A bound no first-order method crosses
Before Nesterov’s method, ask how much it can deliver. Is κ best possible, or is there a κ1/4 method? The answer depends on what a method may do. GD, heavy ball and Nesterov use only gradients of f and combine gradients already known.
GD, heavy ball and Nesterov are of this type: every iterate is x0 plus a linear combination of previous gradients (evaluated at xj or extrapolated points, which combine iterates). Nesterov’s construction makes each gradient reveal only one new coordinate.
Before the proof, the figure. It shows the truncated worst-case function: dimension n=48 for the strongly convex version and n=2k0+1 for the convex version.
InteractiveThe function that fools every first-order method
solution x⋆, coordinate i
iterate xk (Nesterov)
coordinates outside the support
GD
Nesterov
Heavy ball
Conjugate gradient
floor (no method crosses it)
q²ᵏ
Function
Method shown in bars
k = 0
Iteration k and reachable coordinates0 of 48
∥xk−x⋆∥2/∥x0−x⋆∥2 (Nesterov)1
Floor: what remains outside the support1
q2k con q=(κ−1)/(κ+1)1
Measured error / floor1.00
At x0=0 only the first gradient coordinate is nonzero: any method’s first step can move only x1.
The function is tridiagonal quadratic (2 on the diagonal, −1 off diagonal). Gray bars are solution x⋆, colored bars the selected method's iterate xk. Play the animation: the shaded region right of k is unreachable for any first-order method because each gradient extends support by one coordinate. Below, each method's measured error versus the floor no method crosses. In the strongly convex version compare Polyak's heavy ball (touching the floor) and Nesterov; in the convex version see how conjugate gradient, a first-order method, reaches the best possible value. Move k0: bound 3LR2/(32(k0+1)2) holds at k=k0 because dimension is 2k0+1.Proof
(a) Convex. Let An be tridiagonal with 2 on the diagonal and −1 off diagonal, and f(x)=4L(21x⊤Anx−e1⊤x). Since x⊤Anx=x12+∑i=1n−1(xi−xi+1)2+xn2, it is nonnegative and, by (xi−xi+1)2≤2xi2+2xi+12, bounded by 4∥x∥2. Thus 0⪯An⪯4I and f is convex and L-smooth.
Where the method ends.∇f(x)=4L(Anx−e1). If x∈span{e1,…,ej}, then Anx∈span{e1,…,ej+1}, and so does the gradient. By induction, with x0=0, every first-order iterate satisfies xk∈span{e1,…,ek}.
The cost of being there. The minimizer solves Anx=e1, giving xi⋆=1−i/(n+1) and f⋆=−8L(1−n+11). For x supported on the first k coordinates, x⊤Anx=x12+∑i<k(xi−xi+1)2+xk2 is the quadratic form of Ak, so the minimum of f on that subspace is the optimum of the k-dimensional version, −8L(1−k+11). Thus
f(xk)−f⋆≥8L(k+11−n+11)=16(k+1)L(n=2k+1).
Express it in distance: ∥x⋆∥2=∑j=1n(n+1j)2=6(n+1)n(2n+1)≤3n+1=32(k+1). Substitution gives 16(k+1)L≥32(k+1)23L∥x⋆∥2.
(b) Strongly convex. On ℓ2 use f(x)=8L−μ(x⊤Ax−2x1)+2μ∥x∥2, with infinite tridiagonal A. Its Hessian is between μ and L. Support grows similarly: xk∈span{e1,…,ek}. Optimality is (A+κ−14I)x⋆=e1, directly solved by xi⋆=qi: rows i≥2 give q−1+q=2+κ−14=κ−12(κ+1), true for q=(κ−1)/(κ+1); the first row checks likewise. Since xk has no components past k, ∥xk−x⋆∥2≥∑i>kq2i=q2k∑i≥1q2i=q2k∥x0−x⋆∥2. The bound in f follows from f(x)−f⋆≥2μ∥x−x⋆∥2.
∎
Read carefully: each says something different. (a) says no first-order method has error o(1/k2) uniformly over all L-smooth convex functions, since for each k some function (with n=2k+1 variables) has error at least cLR2/k2. (b) says no method needs fewer than about 4κln(1/ε) iterations to reduce f−f⋆ by ε uniformly over strongly convex functions: Polyak heavy ball achieves it on quadratics (its rate q2k in f matches the floor), so the figure shows it hugging the bound. GD with κln(1/ε) does not come close.
Four conditions matter. Dimension: the worst case has n≥2k+1 variables; with n<k steps the quadratic can be solved exactly. First-order assumption: conjugate gradient, first-order on quadratics, minimizes f on each subspace span{e1,…,ek} and reaches the convex figure’s floor without knowing μ or L (studied in numerical linear algebra). Note minimizing f is not minimizing distance; in the strongly convex version measuring ∥xk−x⋆∥2, heavy ball lies below it. Worst case: one function can be easier; the theorem says no universal bound can improve. Deterministic: noise or randomness changes the picture (SGD, lessons 18 and 19).
Nesterov accelerated gradient
Heavy ball evaluates the gradient at xk and then adds momentum: decide where to push, then move by inertia. Nesterov reverses the order: first extrapolate using momentum, then evaluate the gradient there and correct. Look ahead: if inertia already takes you to yk, the gradient at yk is more informative than that at xk about overshooting. The small-looking difference separates a method working only on quadratics from one guaranteed for every convex L-smooth f.
Each iteration takes a 1/L gradient step from the extrapolated point, and extrapolation coefficient (tk−1)/tk+1 grows from 0 toward 1. Since tk≥(k+1)/2 and tk≈k/2, the coefficient is about 1−3/k, the same 3 seen in the ODE. PyTorch stores extrapolated point yk as parameter and evaluates the gradient exactly there; reconstruct it in the library section.
The proof uses the descent inequality and a Lyapunov function: a combination of f error and a distance that does not increase. This is the GD bound pattern with one extra piece.
Proof
Write gk=∇f(yk) and δk=f(xk)−f⋆. Since xk=yk−gk/L, the descent lemma gives f(xk)≤f(yk)−∥gk∥2/(2L), and convexity gives f(yk)≤f(z)+gk⊤(yk−z) for every z. Together:
f(xk)≤f(z)+gk⊤(yk−z)−2L1∥gk∥2para todo z.
Apply with z=xk−1, multiply by tk−1≥0, and with z=x⋆, and add:
where zk=wk−tkgk/L=tkxk−(tk−1)xk−1−x⋆ (the equality expands ∥wk−tkgk/L∥2). Now definition of yk+1 gives exactly wk+1=zk. Therefore energy
Ek=tk2δk+2L∥zk∥2
satisfies Ek≤Ek−1 for k≥2. At k=1, t1=1 and w1=x0−x⋆, and the inequality with z=x⋆ gives E1≤2L∥x0−x⋆∥2. Thus tk2δk≤Ek≤E1≤2L∥x0−x⋆∥2. Finally tk+1≥tk+21 (since 1+4tk2≥2tk), so tk≥(k+1)/2 and δk≤2L∥x0−x⋆∥2/(k+1)2.
∎
Compared with GD’s L∥x0−x⋆∥2/(2k), this is an order jump: for error 10−4 with LR2=1, GD guarantees the result in 5000 iterations, Nesterov in 141. The preceding section’s lower bound 323LR2/(k+1)2 differs only by factor 64/3≈21: the exponent of k cannot improve. Nesterov is optimal for smooth convex functions, as for strongly convex functions with factor (1−1/κ)k:
The proof follows the same pattern with energy f(xk)−f⋆+2μ∥vk−x⋆∥2, where vk is an auxiliary sequence combining two consecutive iterates; energy contracts by 1−1/κ each step (Nesterov, 2018, §2.2, and d’Aspremont, Scieur and Taylor, 2021). Check it numerically here. This is κ rather than κ, with a slightly worse constant than Polyak on quadratics (the lower bound resembles (1−4/κ)k, factor 4 better), in exchange for guarantees for every function. On quadratics, hand-tuning η and β lowers iterate rate to 1−2/3κ+1 (with η=4/(3L+μ)): the same 2×2 analysis checks it, and the plane figure marks that point when switching to Nesterov.
The continuous limit: an ODE with 3/t friction
Why 3? Su, Boyd and Candès (arXiv:1503.01243) explain with a continuous-limit argument. Take the method in form xk+1=yk−s∇f(yk), yk=xk+k+2k−1(xk−xk−1), with step s≤1/L and coefficient (k−1)/(k+2), a convenient form of (tk−1)/tk+1. Identify index with time via t=ks and curve X(t) with X(ks)≈xk. Taylor expansion gives xk+1−xk≈sX˙+2sX¨ and xk−xk−1≈sX˙−2sX¨. Since k+2k−1=1−k+23, the recurrence becomes
sX˙+2sX¨≈(1−k+23)(sX˙−2sX¨)−s∇f(X),
and collecting order-s terms (with k≈t/s, so k+23s≈t3s, and ∇f(yk)≈∇f(X)) gives the ODE. Their rigorous limit proof establishes existence and uniqueness at t=0 (where coefficient 3/t is singular) and method convergence to it as s→0.
Second-order linear ODE theory shows the mechanism in a curvature-λ direction, with f=2λx2 and r=3: solution x(t)=x0λt2J1(λt) (J1 is the Bessel function of the first kind, checked by differentiation). While λt≪1 it moves like a falling ball; afterward it oscillates at frequency λ with amplitude decaying as t−3/2. Smaller λ delays oscillation. Afterward friction 3/t falls below the 2λ needed to critically damp that direction.
The proof idea matches the discrete one. With Z=X+r−1tX˙−x⋆, Z˙=r−1t(X¨+trX˙)=−r−1t∇f(X); differentiating E cancels the X˙ terms, leaving E′(t)=2t[r−12(f−f⋆)−∇f(X)⊤(X−x⋆)]. By convexity, ∇f(X)⊤(X−x⋆)≥f−f⋆, so E′≤2t(r−12−1)(f−f⋆), nonpositive exactly when r≥3. There is the 3: the least friction coefficient for which this energy works. With r=3, t2(f−f⋆)≤E(0)=2∥x0−x⋆∥2. The last exercise treats r=3 step by step.
InteractiveFrom method to ODE
Nesterov, s
Nesterov, s/4
Nesterov, s/16
ODE
bound ∝ 1/t²
Adaptive restart
t = 89.0
f(x(t))−f⋆ in the ODE6.07·10⁻⁶
f(xk)−f⋆ for the method with step s2.99·10⁻⁶
Method iterations where f rises94
E(t)/E(0) in the ODE0.0279
Largest increase in E so far0 (no increase)
With r=3, Nesterov’s value, the energy E(t)=t2(f−f⋆)+2∥x+2tx˙−x⋆∥2 never increases, which yields f−f⋆≤E(0)/t2.
Nesterov with steps s, s/4 and s/16 (time t=ks) versus the ODE solution on a quadratic with adjustable κ. With r=3 method curves approach the ODE as step shrinks. Play the animation and inspect the readings: energy does not increase, although f rises and falls. Raise κ and see ripples appear as tμ nears 1. Change r: with r<3 the general convex guarantee is lost (on this quadratic, where ∇f(x)⊤x=2f, energy increases only below r=2); high r initially damps more. Finally enable function or gradient restart and compare final f−f⋆.
Nonmonotonicity, oscillations and adaptive restart
The preceding graph shows Nesterov’s defect on strongly convex problems. Bound 1/t2 is worst-case for convex functions and does not exploit curvature. The ODE with r=3 in a curvature-μ direction oscillates with amplitude t−3/2, so f−f⋆ in that direction decays as t−3 with ripples: polynomially, without linear convergence, even when f is strongly convex. Constant momentum β(κ) does converge linearly, but requires knowing μ.
The correction is to restart momentum when movement stops helping. O’Donoghue and Candès (arXiv:1204.3982) propose two tests requiring no μ:
Using the definition’s notation, where xk=yk−∇f(yk)/L is the newly calculated iterate:
Function-based: restart if f(xk)>f(xk−1).
Gradient-based: restart if ∇f(yk)⊤(xk−xk−1)>0. This says the current step goes against descent: inertia pushes uphill. No f evaluation is needed.
With restart, the ball again has huge friction (the ODE’s r/t grows enormous when resetting t) just as it begins rising, preventing oscillation. In the ODE the gradient test is ∇f(X)⊤X˙>0. A clean result explains why, with periodic restart and known κ:
Proof
Starting at x with excess f(x)−f⋆, the convex bound gives after j steps f(xj)−f⋆≤2L∥x−x⋆∥2/(j+1)2. Strong convexity gives ∥x−x⋆∥2≤μ2(f(x)−f⋆). Together,
f(xj)−f⋆≤(j+1)24κ(f(x)−f⋆).
With j=m, (m+1)2≥4e2κ, so the factor is at most e−2. Chaining blocks yields the bound and, since m≈2eκ, the per-iteration factor is e−2/m≈exp(−1/(eκ)). Nothing is claimed inside a block: initially 4κ/(j+1)2 exceeds 1.
∎
This is linear convergence with κ, like constant momentum, but from a method needing μ only to choose the period. Adaptive restart achieves nearly the same by monitoring f or gradient, without precise μ or L (only L for the step). Code measures it on regularized logistic regression; the ODE figure shows its effect.
Implementation from scratch
Start with four methods as generators (count iterations without storing trajectories) and check iteration growth as κ for heavy ball and Nesterov, κ for GD. The problem is a diagonal quadratic with μ=1, L=κ and spectrum geometrically spaced between extremes; count iterations to reduce error norm 106 times.
[ ]GD, heavy ball and Nesterov: iterations versus κBrowser
import numpy as np
from math import sqrt
def gd(grad, x0, eta):
"""Descenso por gradiente: generador de x_0, x_1, ..."""
x = np.array(x0, dtype=float)
while True:
yield x
x = x - eta * grad(x)
def heavy_ball(grad, x0, eta, beta):
"""Bola pesada: x_{k+1} = x_k - eta grad(x_k) + beta (x_k - x_{k-1})."""
x_prev = x = np.array(x0, dtype=float)
while True:
yield x
x, x_prev = x - eta * grad(x) + beta * (x - x_prev), x
def nesterov_sc(grad, x0, L, mu):
"""Nesterov con momentum constante: paso 1/L y beta = (sqrt(kappa) - 1)/(sqrt(kappa) + 1)."""
r = sqrt(L / mu)
beta = (r - 1) / (r + 1)
x_prev = x = np.array(x0, dtype=float)
while True:
yield x
y = x + beta * (x - x_prev) # primero se extrapola ...
x, x_prev = y - grad(y) / L, x # ... y el gradiente se evalúa en y
def nesterov_convex(grad, x0, L):
"""Nesterov convexo con t_{k+1} = (1 + sqrt(1 + 4 t_k^2))/2: genera x_0, x_1, ..."""
x = np.array(x0, dtype=float)
y, t = x.copy(), 1.0
yield x
while True:
x_new = y - grad(y) / L
t_new = (1 + sqrt(1 + 4 * t * t)) / 2
y = x_new + (t - 1) / t_new * (x_new - x)
x, t = x_new, t_new
yield x
def iters_to(method, dist, tol, kmax=200_000):
"""Primer k con dist(x_k) <= tol * dist(x_0)."""
d0 = None
for k, x in enumerate(method):
d = dist(x)
d0 = d if d0 is None else d0
if d <= tol * d0:
return k
if k >= kmax:
return None
n = 20
print(f"{'kappa':>6} {'GD':>8} {'bola pesada':>12} {'Nesterov':>9} {'GD/HB':>7} {'sqrt(kappa)':>11}")
for kappa in [10, 100, 1000, 10000]:
mu, L = 1.0, float(kappa)
lam = np.geomspace(mu, L, n) # espectro con los dos extremos
grad = lambda x: lam * x
norm = lambda x: np.linalg.norm(x)
x0 = np.ones(n)
eta_hb = 4 / (sqrt(L) + sqrt(mu)) ** 2 # parámetros de Polyak
beta_hb = ((sqrt(kappa) - 1) / (sqrt(kappa) + 1)) ** 2
k_gd = iters_to(gd(grad, x0, 2 / (L + mu)), norm, 1e-6)
k_hb = iters_to(heavy_ball(grad, x0, eta_hb, beta_hb), norm, 1e-6)
k_nag = iters_to(nesterov_sc(grad, x0, L, mu), norm, 1e-6)
print(f"{kappa:>6} {k_gd:>8} {k_hb:>12} {k_nag:>9} {k_gd / k_hb:>7.1f} {sqrt(kappa):>11.1f}")
Each time κ is multiplied by 10, GD needs about 10 times as many iterations (64, 634, 6333, 63322), heavy ball only 10≈3.2 times as many (25, 87, 296, 996). The ratio grows toward κ (2.6, 7.3, 21.4, 63.6), not yet reaching it at κ=104 because of the critical-damping k factor. Nesterov is slightly slower than heavy ball (40, 143, 470, 1502): its quadratic constant is worse, but it alone has guarantees beyond quadratics. Check that fragility with Lessard, Recht and Packard’s function.
[ ]Polyak heavy ball without convergenceBrowser
from itertools import islice
def grad_1d(x):
"""f'(x) de Lessard, Recht y Packard: mu = 1, L = 25, fuertemente convexa."""
x = float(np.asarray(x).reshape(()))
if x < 1:
return np.array(25 * x)
if x < 2:
return np.array(x + 24)
return np.array(25 * x - 24)
mu, L = 1.0, 25.0
r = sqrt(L / mu)
eta, beta = 4 / (sqrt(L) + sqrt(mu)) ** 2, ((r - 1) / (r + 1)) ** 2 # Polyak: 1/9 y 4/9
x0 = 3.3
hb = [float(x[0]) for x in islice(heavy_ball(grad_1d, [x0], eta, beta), 3000)]
print(f"Polyak: eta = {eta:.4f}, beta = {beta:.4f}")
print("bola pesada, últimos iterados:", [round(v, 4) for v in hb[-6:]])
print("bola pesada, |x_k| mínimo en los últimos 1000 pasos:", round(min(abs(v) for v in hb[-1000:]), 4))
print("GD (1/L) :", float(list(islice(gd(grad_1d, [x0], 1 / L), 300))[-1][0]))
print("Nesterov (mu) :", float(list(islice(nesterov_sc(grad_1d, [x0], L, mu), 300))[-1][0]))
The minimum is x⋆=0 and heavy ball cycles among three points (0.6465, −1.8024, 2.1159): a period-3 cycle with deviation from x⋆ of order 2, not disappearing regardless of iterations. Nesterov and GD end at 0 (exact in floating point, reaching the x<1 segment where f′ is linear). This experimentally shows ρ(Tλ)<1 for every λ is insufficient.
Now Nesterov’s bound and nonmonotonicity on least-squares regression with more variables than data (convex, not strongly convex), and comparison with the worst-case chain:
[ ]The 2LR²/(k+1)² bound and Nesterov nonmonotonicityBrowser
import matplotlib.pyplot as plt
rng = np.random.default_rng(0)
A = rng.normal(size=(30, 60)); b = rng.normal(size=30) # 30 ecuaciones, 60 incógnitas
f = lambda x: 0.5 * np.sum((A @ x - b) ** 2)
grad = lambda x: A.T @ (A @ x - b)
L = np.linalg.eigvalsh(A.T @ A)[-1]
x0 = np.zeros(60)
xstar = np.linalg.lstsq(A, b, rcond=None)[0] # f* = 0: el sistema es compatible
R2 = np.sum((x0 - xstar) ** 2)
K = 300
fg = np.array([f(x) for x in islice(gd(grad, x0, 1 / L), K + 1)])
fn = np.array([f(x) for x in islice(nesterov_convex(grad, x0, L), K + 1)])
k = np.arange(1, K + 1)
print(f"L = {L:.1f}, ||x0 - x*||^2 = {R2:.2f}")
print(f"max_k f(x_k) / [2 L R^2/(k+1)^2] = {np.max(fn[1:] / (2 * L * R2 / (k + 1) ** 2)):.3f} (el teorema dice <= 1)")
print("iteraciones en que f sube: GD", int(np.sum(fg[1:] > fg[:-1])), " Nesterov", int(np.sum(fn[1:] > fn[:-1])))
for kk in (50, 100, 200, 300):
print(f"k = {kk:3d} GD {fg[kk]:.2e} Nesterov {fn[kk]:.2e}")
plt.semilogy(fg, label="GD (1/L)", color="tab:orange")
plt.semilogy(fn, label="Nesterov", color="tab:green")
plt.semilogy(k, 2 * L * R2 / (k + 1) ** 2, "--", color="gray", label="cota 2LR²/(k+1)²")
plt.xlabel("iteración k"); plt.ylabel("f(x_k) − f*"); plt.legend(); plt.show()
The output: the bound holds with slack (maximum ratio 0.14), since this quadratic is not worst-case. Nesterov increases f on 128 of 300 iterations, GD on none. Through k=200 Nesterov is far ahead (at k=100, 2.7⋅10−7 versus 4.9⋅10−4), but by k=300 the advantage nearly vanishes: the preceding section’s oscillation, and a reminder that this finite-dimensional problem is strongly convex on the relevant subspace, so GD eventually converges linearly. Bound 1/k2 is only a worst case. Contrast the worst-case function, with no escape:
[ ]Nesterov's chain: nobody crosses the floorBrowser
def cadena(n, mu, L):
"""f(x) = ½ xᵀHx − cx₁ con H = c·A + mu·I, A tridiagonal (2, -1) y c = (L - mu)/4."""
c = (L - mu) / 4
A = 2 * np.eye(n) - np.eye(n, k=1) - np.eye(n, k=-1)
H = c * A + mu * np.eye(n)
e1 = np.zeros(n); e1[0] = c
xs = np.linalg.solve(H, e1)
return H, e1, (lambda x: 0.5 * x @ H @ x - e1 @ x), xs
K = 20
n = 2 * K + 1 # n = 2k + 1 en el teorema
H, b1, fc, xs = cadena(n, 0.0, 1.0)
gc = lambda x: H @ x - b1
fstar, R2c = fc(xs), xs @ xs
mejor = [] # minimizar f en las k primeras coordenadas
for kk in range(K + 1):
x = np.zeros(n)
if kk:
x[:kk] = np.linalg.solve(H[:kk, :kk], b1[:kk])
mejor.append(fc(x) - fstar)
fg = [fc(x) - fstar for x in islice(gd(gc, np.zeros(n), 1.0), K + 1)]
fn = [fc(x) - fstar for x in islice(nesterov_convex(gc, np.zeros(n), 1.0), K + 1)]
print(" k mejor posible Nesterov GD")
for kk in (5, 10, 20):
print(f"{kk:4d} {mejor[kk]:.4e} {fn[kk]:.4e} {fg[kk]:.4e}")
print("ningún método baja del suelo:", all(min(fg[kk], fn[kk]) >= mejor[kk] - 1e-15 for kk in range(K + 1)))
cota = 3 * R2c / (32 * (K + 1) ** 2) # vale en k = K, porque n = 2K + 1
print(f"en k = {K} = (n - 1)/2: cota 3LR²/(32(k+1)²) = {cota:.4e}, mejor posible / cota = {mejor[K] / cota:.3f}")
“Best possible” is minimum f on the first-k-coordinate subspace, unbeatable by the theorem. Nesterov is about a factor 3 away (at k=20, 8.8⋅10−3 versus 3.0⋅10−3) and GD a factor 6. At k=20=(n−1)/2 the best value exceeds the bound by 4 %, showing how tight 3/32 is (the exact calculation uses 6(n+1)n(2n+1), not upper bound 3n+1). Evaluate the bound only at k=20: for smaller k, with this same function of 41 variables, 3LR2/(32(k+1)2) exceeds the best value (at k=10, 1.05⋅10−2 versus 8.4⋅10−3), because R2 belongs to the long chain; the theorem uses a 2k+1-variable chain for each k.
Finally restart. Regularized logistic regression f(w)=m1∑iln(1+e−yizi⊤w)+2λ∥w∥2 is strongly convex with μ=λ and L≤4m1λmax(Z⊤Z)+λ. Measure iterations for f−f⋆≤10−9, with f⋆ computed by Newton.
[ ]Adaptive restart in logistic regressionBrowser
def nesterov_restart(f, grad, x0, L, scheme="function"):
"""Nesterov convexo con reinicio adaptativo (O'Donoghue y Candès, 2015)."""
x = np.array(x0, dtype=float)
y, t = x.copy(), 1.0
yield x
while True:
g = grad(y)
x_new = y - g / L
t_new = (1 + sqrt(1 + 4 * t * t)) / 2
if scheme == "function":
reset = f(x_new) > f(x) # f ha subido
else:
reset = g @ (x_new - x) > 0 # el paso va contra el descenso
if reset:
y, t = x_new.copy(), 1.0 # momentum a cero
else:
y = x_new + (t - 1) / t_new * (x_new - x)
t = t_new
x = x_new
yield x
rng = np.random.default_rng(1)
m, d = 400, 40
Z = rng.normal(size=(m, d)) @ np.diag(np.geomspace(1, 0.1, d)) + 0.5 * rng.normal(size=(m, 1))
w_true = rng.normal(size=d)
lab = np.where(Z @ w_true + 0.5 * rng.normal(size=m) > 0, 1.0, -1.0)
lam = 1e-2
def f_log(w):
return np.mean(np.logaddexp(0, -lab * (Z @ w))) + 0.5 * lam * w @ w
def grad_log(w):
p = 0.5 * (1 - np.tanh(lab * (Z @ w) / 2)) # sigmoide(-s), estable
return -(Z.T @ (lab * p)) / m + lam * w
L = np.linalg.eigvalsh(Z.T @ Z / m)[-1] / 4 + lam
mu = lam
print(f"L = {L:.3f}, mu = {mu}, kappa = L/mu = {L / mu:.0f}")
w = np.zeros(d)
for _ in range(50): # Newton: w*
p = 0.5 * (1 - np.tanh(lab * (Z @ w) / 2))
Hs = Z.T @ ((p * (1 - p))[:, None] * Z) / m + lam * np.eye(d)
w = w - np.linalg.solve(Hs, grad_log(w))
fstar = f_log(w)
def iters_gap(method, tol=1e-9, kmax=20000):
for k, x in enumerate(method):
if f_log(x) - fstar <= tol:
return k
if k >= kmax:
return None
x0 = np.zeros(d)
res = {
"GD (paso 1/L)": gd(grad_log, x0, 1 / L),
"Nesterov convexo": nesterov_convex(grad_log, x0, L),
"Nesterov + reinicio por función": nesterov_restart(f_log, grad_log, x0, L, "function"),
"Nesterov + reinicio por gradiente": nesterov_restart(f_log, grad_log, x0, L, "gradient"),
"Nesterov con mu (momentum constante)": nesterov_sc(grad_log, x0, L, mu),
}
for nombre, met in res.items():
print(f"{nombre:38s} {iters_gap(met)}")
Both restarts, not using μ, take around 185 iterations: about 7.6 times fewer than GD (1401) and 3.7 fewer than Nesterov without restart (692), close to constant momentum which knows μ (137). The problem has κ≈240 and 240≈15.5. This matches theory above without knowing curvature.
The professional version: PyTorch momentum
torch.optim.SGD(params, lr, momentum, dampening, nesterov) implements these methods with three conventions that differ from book formulas. Its rule is buf ← momentum·buf + (1 − dampening)·grad and p ← p − lr·buf, with buf = grad on the first step. This is velocity form, with v rescaled by η: with β = momentum, η = lr and dampening = 0, it is exactly Polyak heavy ball. The steady-state effective step is η/(1−β), as unrolling showed. With dampening = momentum the buffer is a moving average and Polyak’s η is lr·(1 − momentum), except on the first step. With nesterov=True it steps on grad + momentum·buf, and the saved parameter is not xk but extrapolated pointyk: gradient is evaluated at the parameter’s location without a second model copy. The guaranteed iterate is xk+1=yk−η∇f(yk). The next cell checks a quadratic with three eigenvalues (CPU, float64, 25 steps).
[ ]PyTorch versus heavy ball and Nesterov: equivalences exactasLocal GPU
import numpy as np, torch
from itertools import islice
torch.set_default_dtype(torch.float64)
lam = torch.tensor([1.0, 10.0, 100.0])
x0 = torch.tensor([1.0, 1.0, 1.0])
def torch_path(steps=25, **opt):
w = x0.clone().requires_grad_(True)
sgd = torch.optim.SGD([w], **opt)
pts = [w.detach().clone().numpy()]
for _ in range(steps):
sgd.zero_grad()
(0.5 * (lam * w * w).sum()).backward()
sgd.step()
pts.append(w.detach().clone().numpy())
return np.array(pts)
grad = lambda x: lam.numpy() * x
x0n = x0.numpy()
def heavy_ball(grad, x0, eta, beta, x_prev=None):
x = np.array(x0, float)
x_prev = x if x_prev is None else x_prev
while True:
yield x
x, x_prev = x - eta * grad(x) + beta * (x - x_prev), x
def nesterov_const(grad, x0, eta, beta):
x_prev = x = np.array(x0, float)
while True:
y = x + beta * (x - x_prev)
yield y, x # y: lo que guarda PyTorch; x: el iterado de la teoría
x, x_prev = y - eta * grad(y), x
lr, beta = 0.005, 0.9
P = torch_path(lr=lr, momentum=beta)
H = np.array(list(islice(heavy_ball(grad, x0n, lr, beta), 26)))
print("momentum de PyTorch frente a Polyak (eta = lr): ", np.abs(P - H).max())
Pd = torch_path(lr=lr, momentum=beta, dampening=beta)
Hd = np.array(list(islice(heavy_ball(grad, x0n, lr * (1 - beta), beta, x_prev=x0n + lr * grad(x0n)), 26)))
print("con dampening = beta: Polyak con eta = lr (1 - beta): ", np.abs(Pd - Hd).max())
Pn = torch_path(lr=lr, momentum=beta, nesterov=True)
pares = list(islice(nesterov_const(grad, x0n, lr, beta), 26))
Y = np.array([p[0] for p in pares]); X = np.array([p[1] for p in pares])
print("nesterov=True frente a los puntos extrapolados y_k: ", np.abs(Pn - Y).max())
print("x_{k+1} = theta_k - lr grad(theta_k) frente a Nesterov: ", np.abs((Pn - lr * lam.numpy() * Pn)[:-1] - X[1:]).max())
# paso efectivo con gradiente constante: lr/(1 - beta)
w = torch.zeros(1, requires_grad=True)
sgd = torch.optim.SGD([w], lr=0.1, momentum=0.9)
for _ in range(200):
sgd.zero_grad(); (w * 1.0).sum().backward()
w0 = w.item(); sgd.step()
print("desplazamiento por paso con gradiente 1 (lr = 0.1, momentum = 0.9):", round(w0 - w.item(), 6))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
The first three numbers are order 10−15: exact equivalences, not approximations. The last is 1.0, namely η/(1−β)=0.1/0.1 per unit gradient: momentum 0.9 multiplies effective step by 10, so lower lr when enabling it if you want the same trajectory.
What you need
Option
Note
Train a network with SGD and momentum
SGD(lr, momentum=0.9)
Heavy ball with η = lr. Steady effective step is lr/(1 - momentum).
Nesterov-style momentum
SGD(..., momentum=0.9, nesterov=True)
Requires momentum > 0 and dampening = 0. Parameter is the extrapolated point.
Adaptive restarts on a smooth convex problem
Custom implementation
As in the restart cell. Large networks often use lr schedules instead (optimizer API).
Prove: Let f be quadratic with spectrum in [μ,L] and κ=L/μ>1. Prove that, for η=4/(L+μ)2 and β=((κ−1)/(κ+1))2, heavy ball has spectral radius β over the entire spectrum.
0
Work in the eigendirection of eigenvalue λ∈[μ,L], with recurrence ek+1=(1+β−ηλ)ek−βek−1.
Step 1 of 4. What is the recurrence's characteristic polynomial?
NumericGD versus Nesterov with κ = 10⁴
A μ-strongly convex L-smooth function has κ=104. Worst-case guarantees are f(xk)−f⋆≤(1−1/κ)kΦ0 for GD with η=1/L and f(xk)−f⋆≤(1−1/κ)kΦ0 for constant-momentum Nesterov, with the same Φ0. To guarantee a 108 error reduction, how many times more iterations does GD need than Nesterov?
QuizWhy Polyak fails beyond quadratics
Let f be strongly convex and L-smooth but nonquadratic, and apply heavy ball with Polyak parameters calculated from f's μ and L. Why might it fail to converge?
QuizWhat sets heavy-ball speed?
Fix β=0.64 and move η within the range where roots for every eigendirection are complex. What happens to spectral radius ρ over the spectrum?
NumericOptimal inertia for κ = 100
On a quadratic with μ=1 and L=100, what is Polyak heavy ball's optimal inertia β?
NumericThe effective PyTorch momentum step
Training works with SGD(lr=0.1) without momentum. Enable momentum=0.9 (without dampening) while retaining the same steady-state displacement per step (nearly constant gradient). What lr should you use?
NumericIterations guaranteed by Nesterov
With LR2=L∥x0−x⋆∥2=1, what is the smallest k for which bound 2LR2/(k+1)2 guarantees f(xk)−f⋆≤10−4?
QuizWhat restart does and does not do
You run Nesterov on regularized logistic regression and f(xk) oscillates near the minimum. What does gradient restart ∇f(yk)⊤(xk−xk−1)>0 do?
ProofLyapunov energy for Nesterov's ODE
Prove: Let f be convex and differentiable with minimizer x⋆, and X solve X¨+t3X˙+∇f(X)=0 with X(0)=x0 and X˙(0)=0. Prove that E(t)=t2(f(X)−f⋆)+2X+2tX˙−x⋆2 is nonincreasing and deduce f(X(t))−f⋆≤2∥x0−x⋆∥2/t2.
0
Let Z=X+2tX˙−x⋆, so E=t2(f(X)−f⋆)+2∥Z∥2.
Step 1 of 4. What is Z˙?
CodeNesterov's two variants
Implement nesterov_agd(grad, x0, L, mu=None, iters=100), returning an array of shape (iters + 1, d) containing iterates x_0, ..., x_iters. If mu is None or 0, use the section's convex variant (sequence tk, t1=1, y1=x0). If mu > 0, use constant momentum with β=(κ−1)/(κ+1). In both cases step is 1/L and gradient is evaluated at extrapolated yk (on the first step y1=x0, so x1=x0−∇f(x0)/L).
import numpy as np
def nesterov_agd(grad, x0, L, mu=None, iters=100):
"""Iterados x_0..x_iters del gradiente acelerado de Nesterov (forma de dos sucesiones)."""
x = np.array(x0, dtype=float)
xs = [x.copy()]
for _ in range(iters):
# tu código: punto extrapolado y, paso de gradiente desde y, y la actualización de t (o de beta)
x = x - grad(x) / L
xs.append(x.copy())
return np.array(xs)
Shift+Enter to run
Summary
Key idea
A moving average of gradients cancels components bouncing between valley walls and accumulates those consistently pointing one way: momentum changes κ to κ in iteration count, and Nesterov’s construction shows no first-order method can do better.
Heavy ball xk+1=xk−η∇f(xk)+β(xk−xk−1) is an exponential average of past gradients. On quadratics each eigendirection follows a 2×2 matrix with trace 1+β−ηλ and determinant β: underdamped, spectral radius β is independent of η and λ.
Polyak parameters η=4/(L+μ)2 and β=(κ+1κ−1)2 critically damp μ and L, give rate κ+1κ−1, and are optimal among all pairs. Beyond quadratics they may fail to converge (limit cycle in Lessard, Recht and Packard’s function).
Nesterov’s tridiagonal-chain lower bound says each gradient reveals one new coordinate: no first-order method beats Ω(LR2/k2) on convex functions or Ω(κln(1/ε)) iterations on strongly convex functions.
Nesterov accelerated gradient evaluates at the extrapolated point and achieves f(xk)−f⋆≤2L∥x0−x⋆∥2/(k+1)2 on smooth convex functions (Lyapunov proof), and (1−1/κ)k on strongly convex ones. It is not descent: f may rise.
It discretizes X¨+t3X˙+∇f(X)=0, with nonincreasing energy for r≥3. Friction 3/t decays, explaining oscillations in strongly convex functions.
Adaptive restart (function or gradient) resets momentum when inertia moves uphill and recovers a κ linear rate without knowing μ. In PyTorch, SGD(momentum=...) is heavy ball with η = lr, and steady effective step is lr/(1 - momentum).