5.10 Gradient descent, momentum and Newton's method
To minimise a function, repeatedly step against its gradient. On a quadratic the error after each step is multiplied by the matrix I minus eta times the Hessian, so the speed is set by the Hessian's eigenvalues and the condition number of 3.5, and the path zig-zags across narrow valleys. Momentum improves the rate from (k-1)/(k+1) to (sqrt k - 1)/(sqrt k + 1), stochastic gradients trade exactness for cost and leave a noise floor proportional to the step, Newton's method divides by the Hessian and converges quadratically near a minimum, and in high dimensions most critical points are saddles.
Taught in 375/376Apostol, not taughtBeyond the courseMATH 375, the lectures on the gradient and the total derivative, and Lecture 24 (Hessian, eigenvalues, saddle points)MATH 376, Homework 7 #3 and Worksheet 19 #2 (Newton's method as a contraction)Cauchy, Méthode générale pour la résolution des systèmes d'équations simultanées (1847)Robbins and Monro, A stochastic approximation method (1951)Polyak, Some methods of speeding up the convergence of iteration methods (1964)Boyd and Vandenberghe, Convex Optimization, ch. 9Nocedal and Wright, Numerical Optimization, ch. 3 and 6Goodfellow, Bengio and Courville, Deep Learning, ch. 4 and 8
You are standing somewhere on a hillside in thick fog and want to get to the bottom. You cannot see the valley, but you can feel which way is steepest underfoot. So you step downhill, feel again, and step again. That is gradient descent, and by 5.2 the gradient is exactly the instrument that feels the steepest direction. Almost every large model in machine learning is trained this way. Whether the walk reaches the bottom, how fast, and what goes wrong (overshooting, zig-zagging, getting stuck at a saddle) is decided by the second derivative: the Hessian of 5.6, its eigenvalues from 3.1, and the condition number of 3.5. This chapter proves what can be proved and shows the rest by computation.
Before you start
5.2: the gradient is the direction of steepest ascent. 5.6: the Hessian, positive definiteness and eigenvalues. 3.5: the condition number. 4.2: contractions and fixed points. 5.8: convex functions and the gradient inequality.
Quick checkAt a point a with ∇f(a)=O, in which direction does f decrease fastest, per unit of distance?
The directional derivative in a unit direction u is ∇f(a)⋅u, smallest (equal to −∥∇f(a)∥) for u=−∇f(a)/∥∇f(a)∥. In the perpendicular direction f does not change to first order.Review: steepest ascent
Quick checkA symmetric matrix A has eigenvalues 1 and 100. What are its operator norm and condition number?
For a symmetric positive definite matrix the singular values are the eigenvalues, so ∥A∥=σ1=100 and κ=σ1/σn=100/1=100. The level curves of 21xTAx are ellipses with axis ratio 100=10.Review: condition number
Quick checkA map T of Rn satisfies ∥T(x)−T(y)∥≤0.9∥x−y∥ for all x,y. What do you know about the iteration xk+1=T(xk)?
This is a contraction of the complete space Rn, so the Banach fixed point theorem applies. Gradient descent is exactly such an iteration, with T(x)=x−η∇f(x).Review: the Banach fixed point theorem
The picture: a ball rolling down a valley
The function is 21(x2+25y2), a long narrow valley (the ellipses). Drag the start, then try these things in order. (1) Move the step-size slider: at t=ηL=1 the steep coordinate is cancelled in a single step and the path runs straight along the valley floor; for t between 1 and 2 the path zig-zags across the valley, more and more as t approaches 2; above 2 it diverges. (2) Choose the best step, t≈1.92 here, and see that even then the path still zig-zags and crawls along the valley floor: the error in the long direction shrinks only by (κ−1)/(κ+1)=24/26 per step. (3) Turn up the momentum β: the orange path damps the zig-zag and runs down the valley much faster. (4) Choose κ=100, then the Rosenbrock banana, where plain descent crawls round a curved valley. (5) Choose the saddle and watch the path approach the saddle point and escape slowly along the downhill direction.
The idea, in words
At a point x the gradient is the best linear summary of f (5.3): f(x+s)≈f(x)+∇f(x)⋅s. To lower f we want ∇f(x)⋅s as negative as possible for a step of given length, and by Cauchy–Schwarz that is s=−η∇f(x). The linear model, however, is only trusted for small steps. How small? The quadratic term of the Taylor formula (5.6) says: as small as the curvature allows. Too long a step along a direction of high curvature overshoots the valley floor and lands higher up the other wall; too short a step along a direction of low curvature barely moves. The Hessian’s largest eigenvalue L limits the step; its smallest, μ, limits the speed; and the ratio κ=L/μ is the whole story on a quadratic.
Where this came from· Cauchy's note of 1847
The method of steepest descent is usually traced to a three-page note by Augustin-Louis Cauchy, “Méthode générale pour la résolution des systèmes d’équations simultanées”, read to the Paris Academy of Sciences in October 1847. His motive was astronomical: to find the orbit of a heavenly body one has to solve simultaneous algebraic equations for the orbital elements, and eliminating the unknowns one at a time is hopeless by hand. He proposed to turn the system into the minimisation of a non-negative function of the unknowns (the sum of the squares of the equations is the natural choice) and to change the unknowns step by step in the direction in which that function decreases fastest, then repeat. It is the iteration xk+1=xk−ηk∇f(xk) of this chapter. The same iteration, with the gradient computed by backpropagation (3.8), trains neural networks today.
Definitions
Definition A
Gradient descent
To minimise a differentiable scalar field f on Rn, choose a start x0 and a number η>0 and iterate xk+1=xk−η∇f(xk). This is gradient descent. Its fixed points are exactly the critical points of f (∇f=O), and the next sections ask when the iterates converge to one, and how fast.
In one lineThe iteration xk+1=xk−η∇f(xk), which moves from the current point against the gradient by a step proportional to its length.
Why it existsIt is the simplest rule that uses first-order information only and is guaranteed, for a small enough step, to lower the function at every step.
Definition A
Learning rate
The positive number η multiplying the gradient is the learning rate (also step size). It may be fixed or change with the step number k.
In one lineThe step-size multiplier η in gradient descent; in machine learning it is the most important hyperparameter.
Why it existsIt decides between crawling and exploding: the theory below says the useful range is below 2/L, where L is the largest Hessian eigenvalue.
Definition A
Loss function
For a model with parameters w∈Rn and data (xi,yi)i=1N, a loss function is a field ℓ(w)=N1∑i=1Nℓi(w), the average of the loss ℓi on each example. For least squares, ℓi(w)=21(w⋅xi−yi)2.
In one lineThe scalar field ℓ(w) of the parameters w of a model that measures how badly the model fits the data; training means minimising it.
Why it existsIt turns 'fit the data' into the optimisation problem this chapter solves; for least squares it is 2.10's sum of squared errors.
One step lowers the function: the descent lemma
Lemma Bstandard (Nesterov, Introductory Lectures on Convex Optimization, 1.2.3)
Descent lemma
Let f be continuously differentiable on Rn with ∥∇f(x)−∇f(y)∥≤L∥x−y∥ for all x,y (we say f is L-smooth; for a C2 field this holds when all Hessian eigenvalues lie in [−L,L], by the mean value inequality of 5.7 applied to ∇f). Then f(y)≤f(x)+∇f(x)⋅(y−x)+2L∥y−x∥2. If y=x−η∇f(x) with 0<η≤L1 then f(y)≤f(x)−2η∥∇f(x)∥2.
In one lineIf ∇f is L-Lipschitz, then f(y)≤f(x)+∇f(x)⋅(y−x)+2L∥y−x∥2; consequently the step y=x−η∇f(x) with η≤L1 gives f(y)≤f(x)−2η∥∇f(x)∥2.
Why it is trueIt is the guarantee that gradient descent makes progress, and it says how much: the decrease is at least half the step times the squared gradient.
ProofNesterov 1.2.3
The idea: Write the change in f along the segment as an integral of the directional derivative, subtract the linear part, and bound the difference of gradients by the Lipschitz constant times the distance.
f(y)−f(x)=∫01∇f(x+t(y−x))⋅(y−x)dt.
Put g(t)=f(x+t(y−x)). By the path theorem of 5.3, g′(t)=∇f(x+t(y−x))⋅(y−x), continuous; fundamental theorem of calculus (1.5).
The integrand is at most Lt∥y−x∥2, and ∫01Ltdt=2L. This is the first inequality.
Cauchy–Schwarz on each integrand and the Lipschitz bound: ∥∇f(x+t(y−x))−∇f(x)∥≤Lt∥y−x∥.
f(y)≤f(x)−2η∥∇f(x)∥2.
Put y−x=−η∇f(x): the linear term is −η∥∇f∥2 and the quadratic term is 2Lη2∥∇f∥2. So f(y)≤f(x)−η(1−2Lη)∥∇f(x)∥2, and 1−2Lη≥21 when η≤L1. ■
Gradient descent on a quadratic: the eigenvalues decide
A quadratic is the model of every smooth function near a minimum (the second-order Taylor formula of 5.6), so this case matters.
Theorem Bstandard (Boyd and Vandenberghe 9.3; Nocedal and Wright 3.3)
Gradient descent on a quadratic
Let A be symmetric positive definite with eigenvalues 0<μ=λ1≤⋯≤λn=L and f(x)=21xTAx−bTx, with unique minimiser x∗=A−1b (∇f(x)=Ax−b). For gradient descent with step η, xk−x∗=(I−ηA)k(x0−x∗). (a) The iteration converges to x∗ for every x0 if and only if 0<η<2/L. (b) Then ∥xk−x∗∥≤ρk∥x0−x∗∥ with ρ(η)=max(∣1−ημ∣,∣1−ηL∣), and this rate is attained. (c) ρ is smallest at η∗=L+μ2, where ρ∗=L+μL−μ=κ+1κ−1.
In one lineFor f(x)=21xTAx−bTx with A symmetric positive definite with eigenvalues in [μ,L], gradient descent converges to x∗=A−1b for every start if and only if 0<η<2/L; the error is multiplied by max(∣1−ημ∣,∣1−ηL∣) per step, which is smallest, equal to κ+1κ−1 with κ=L/μ, at η=L+μ2.
Why it is trueIt turns the speed of the algorithm into a number computed from the Hessian's extreme eigenvalues, and shows that it is the condition number of 3.5, not the size of the problem, that decides.
ProofBoyd and Vandenberghe 9.3
The idea: Subtract the fixed point from the update to get a linear recursion for the error. Diagonalise A with the spectral theorem: each coordinate of the error in the eigenbasis is multiplied by 1 minus eta times its eigenvalue at every step, so the slowest coordinate sets the rate. Choose eta to balance the two extreme coordinates.
ek+1=(I−ηA)ek for ek=xk−x∗, hence ek=(I−ηA)ke0.
∇f(x∗)=Ax∗−b=O, so xk+1−x∗=xk−x∗−η(Axk−b)=xk−x∗−ηA(xk−x∗).
In the eigenbasis, coordinate i of the error is multiplied by (1−ηλi) at each step: ci(k)=(1−ηλi)kci(0).
Spectral theorem (3.1): A=QΛQT with Q orthogonal. Then I−ηA=Q(I−ηΛ)QT, and Q does not change lengths.
Every coordinate tends to 0 for every start if and only if ∣1−ηλi∣<1 for all i, that is 0<η<2/L. This is (a).
A geometric sequence rk tends to 0 if and only if ∣r∣<1. The condition ∣1−ηλi∣<1 is 0<ηλi<2. It must hold for the largest eigenvalue L; then it holds for all smaller ones.
So ∥ek∥≤ρk∥e0∥ with ρ=max(∣1−ημ∣,∣1−ηL∣), attained for a suitable start. This is (b).
∥ek∥2=∑i(1−ηλi)2k(ci(0))2≤maxi∣1−ηλi∣2k∥e0∥2, with equality when e0 is an eigenvector for the worst eigenvalue. The function λ↦∣1−ηλ∣ is convex on [μ,L], so its maximum is at an end.
η∗=L+μ2 and then ρ∗=1−L+μ2μ=L+μL−μ. ■
As η grows from 0, ∣1−ημ∣=1−ημ decreases and ∣1−ηL∣=ηL−1 (once η>1/L) increases; the maximum of the two is smallest where they are equal: 1−ημ=ηL−1.
Why· Why the path zig-zags (the picture behind the proof)
At the best step η∗ the error coordinate along the eigenvector for μ is multiplied by 1−η∗μ=+κ+1κ−1: it shrinks slowly and keeps its sign. The coordinate along the eigenvector for L is multiplied by 1−η∗L=−κ+1κ−1: it shrinks equally slowly but flips sign at every step. So the path moves steadily along the valley while bouncing from one wall to the other, and the same number κ+1κ−1, close to 1 when κ is large, limits both. Any larger step would make the bouncing grow; any smaller step would slow the long direction. This is the blue path in the picture above.
Proof workshopGive the reason for each line: gradient descent on a quadraticBoyd and Vandenberghe 9.3
Each line of the proof is shown in order. Choose the reason that justifies it, then press Check.
ek+1=(I−ηA)ek where ek=xk−x∗.
In an orthonormal eigenbasis, coordinate i is multiplied by 1−ηλi at each step.
Convergence for all starts if and only if ∣1−ηλi∣<1 for every i, that is 0<η<2/L.
The error shrinks like ρk with ρ=max(∣1−ημ∣,∣1−ηL∣).
The best step solves 1−ημ=ηL−1, giving η∗=L+μ2 and ρ∗=κ+1κ−1.
Worked example new (hand computation of the picture above)
Run gradient descent on f(x,y)=21(x2+10y2) from (4,1) with η=0.15, and find the stable range of η and the best step.
Solution.
Gradient and eigenvalues.∇f=(x,10y) and the Hessian is diag(1,10), so μ=1, L=10, κ=10. The matrix is diagonal, so its eigenvalues are the diagonal entries.
One step.xk+1=(1−η)xk=0.85xk and yk+1=(1−10η)yk=−0.5yk. From (4,1): (3.4,−0.5), then (2.89,0.25), then (2.4565,−0.125). Each coordinate has its own multiplier; the y-multiplier is negative, so y flips sign every step: the zig-zag.
Stable range. Both multipliers must have absolute value below 1: ∣1−η∣<1 and ∣1−10η∣<1, so 0<η<0.2=2/L. Theorem (a).
Best step.η∗=10+12=112≈0.1818, with rate ρ∗=10+110−1=119≈0.818. Both coordinates then shrink by 0.818 per step in absolute value: x by +119 and y by −119.
Compare with η=0.15. The multipliers are 0.85 and −0.5, so ρ=0.85, slower than 0.818 because the x direction now limits. For η<η∗ the long direction (small eigenvalue) is the slow one.
Answer. Stable for 0<η<0.2; the best step is 112 with rate 119. After k steps at η=0.15 the error is about 0.85k of the start.
Your answerFor gradient descent on f=21(x2+10y2), what is the largest learning rate η for which the iteration converges from every start?
The condition is η<2/L.
The Hessian is diag(1,10) with largest eigenvalue L=10, and the iteration converges if and only if η<2/L=0.2 (at η=0.2 the y-coordinate only flips sign forever).
Your answerA quadratic has Hessian eigenvalues 1 and 100. What is the best convergence factor per step (κ−1)/(κ+1) of gradient descent with a fixed step? (Give a decimal.)
κ=100, so ρ∗=10199≈0.9802. Each step removes only about 2% of the error.
Your answerWith the factor ρ=99/101 per step, about how many steps shrink the error by a factor of 106? (Give a decimal.)
We need ρk≤10−6, so k≥ln(101/99)ln106=0.02000113.8155≈690.8; the simulation in the lab below stops at step 691. For large κ, lnκ−1κ+1≈κ2, so the count is about 2κlnε1: proportional to the condition number.
Worked example new (links the normal equations of 2.10 to this chapter)
Least squares by gradient descent. Fit w to minimise 21∥Xw−y∥2 for X=101011 and y=(1,2,2). Find the best step and the first iterate from w0=O.
Solution.
The Hessian is XTX.∇21∥Xw−y∥2=XT(Xw−y) (3.8), so the Hessian is A=XTX=[2112]. The loss is a quadratic with this matrix.
Eigenvalues.μ=1 (eigenvector (1,−1)) and L=3 (eigenvector (1,1)), so κ=3. Trace 4, determinant 3.
The minimiser. The normal equations Aw=XTy=(3,4) give w∗=(32,35). 2.10; solve the 2×2 system.
Best step and rate.η∗=3+12=21, ρ∗=3+13−1=21. The theorem.
First iterate.w1=w0−η∗XT(Xw0−y)=O+21(3,4)=(1.5,2). The error is w1−w∗=(65,31), which is (I−21A)(−32,−35)=(65,31). ✓ Check with the error recursion.
Answer.η∗=21, rate 21 per step (the error halves each time), w1=(1.5,2), heading for (32,35). In a realistic problem with a million columns XTX is never formed or inverted; the product XT(Xw−y) costs two matrix–vector products.
Same idea elsewhere· The conditioning of 3.5, squared
The Hessian of least squares is XTX, whose condition number is κ(X)2 (its eigenvalues are the squares of the singular values of X, 3.4). A data matrix with κ(X)=10 gives κ=100 and a rate 10199; with κ(X)=1000 the rate is 1−2×10−6, hopeless. This is why features are standardised (columns scaled to the same size) before training: it reduces κ(X) and so speeds up gradient descent by orders of magnitude, and it is also why the normal equations lose precision (3.5, 2.10).
Corollary Bstandard; ties 4.2 and 5.7 to this chapter
Gradient descent is a contraction
Suppose f∈C2(Rn) and every eigenvalue of the Hessian lies in [μ,L] at every point, μ>0. Then for 0<η<2/L the map T(x)=x−η∇f(x) satisfies ∥T(x)−T(y)∥≤ρ∥x−y∥, ρ=max(∣1−ημ∣,∣1−ηL∣)<1. Hence T has exactly one fixed point x∗ (the point with ∇f(x∗)=O, the minimiser) and the iterates satisfy ∥xk−x∗∥≤1−ρρk∥x1−x0∥.
In one lineIf f is C2 with μI⪯Hf(x)⪯LI everywhere on Rn and 0<η<2/L, then T(x)=x−η∇f(x) is a contraction with constant ρ=max(∣1−ημ∣,∣1−ηL∣)<1, so gradient descent converges to the unique minimiser x∗ and ∥xk−x∗∥≤1−ρρk∥x1−x0∥.
Why it is trueIt proves convergence for every smooth strongly convex function, and not only quadratics, by the fixed-point theorem of 4.2, and gives a computable error bound.
Proof4.2 and 5.7
The idea: The Jacobian of T is I minus eta times the Hessian, a symmetric matrix with eigenvalues between 1 minus eta L and 1 minus eta mu; its operator norm is at most rho. The mean value inequality for fields turns that into the Lipschitz bound, and the Banach fixed point theorem finishes.
DT(x)=I−ηHf(x).
D(∇f)=Hf, the Hessian (5.6).
∥DT(x)∥≤ρ for every x.
For a symmetric matrix the operator norm is the largest absolute eigenvalue (3.5). The eigenvalues of I−ηH are 1−ηλ with λ∈[μ,L], and ∣1−ηλ∣≤ρ for all such λ.
∥T(x)−T(y)∥≤ρ∥x−y∥, and ρ<1 because 0<η<2/L.
Mean value inequality for fields (5.7) on the convex set Rn.
T has a unique fixed point x∗, the iterates converge to it, and the bound holds.
Banach fixed point theorem (4.2) in the complete space Rn, with its a priori error bound d(xk,x∗)≤1−ρρkd(x1,x0). A fixed point of T satisfies η∇f(x∗)=O. ■
Exact line search, and why the zig-zag is built in
If at each step we choose ηk to minimise f along the line xk−ηgk (an exact line search, where gk=∇f(xk)), then dηdf(xk−ηgk)=−∇f(xk+1)⋅gk=0: each new gradient is perpendicular to the previous one, gk+1⊥gk. In two variables the path must turn through a right angle at every step. On a long narrow valley, this forces the zig-zag, however clever the step. For a quadratic with the worst start the error in the norm eTAe is multiplied by at most κ+1κ−1 per step, and by exactly that for the worst start (the Kantorovich inequality). It is the same number as the rate of the best fixed step, which the lab below measures.
Quick checkGradient descent on f=21(x2+100y2) uses η=0.025. What happens?
Smallness is relative to the curvature. The stability limit is 2/L with L=100, i.e. 0.02. At η=0.025 the y-coordinate is multiplied by −1.5 each step, so it grows without bound while flipping sign. Meanwhile x is multiplied by 0.975 and shrinks.
Quick checkWhich describes the zig-zag of gradient descent in a narrow valley?
At the best fixed step the multiplier along the steepest direction is −κ+1κ−1: exactly the same size as along the valley but with the opposite sign. The oscillation is the method working as designed, and the only cures are to change the geometry (precondition, momentum, or Newton's method).
Convex functions: progress without a second derivative
Theorem Bstandard (Nesterov, Introductory Lectures 2.1.5; Boyd and Vandenberghe 9.3)
Gradient descent on a convex smooth function
Let f be convex and differentiable on Rn with L-Lipschitz gradient and a minimiser x∗. Gradient descent xi+1=xi−L1∇f(xi) satisfies f(xk)−f(x∗)≤2kL∥x0−x∗∥2 for k≥1.
In one lineIf f is convex and L-smooth with a minimiser x∗, then gradient descent with η=1/L satisfies f(xk)−f(x∗)≤2kL∥x0−x∗∥2.
Why it is trueIt guarantees convergence for any convex smooth problem with no assumption on the smallest eigenvalue: the price is a slower rate (inversely proportional to the number of steps) than the geometric rate on a strongly convex problem.
ProofNesterov 2.1.5
The idea: Track the squared distance to the minimiser. The gradient inequality (convexity) says the gradient points away from the minimiser by at least the function gap; the descent lemma says the function gap controls the squared gradient. Together they make the distance decrease and sum up to a telescoping bound.
∥xi+1−x∗∥2=∥xi−x∗∥2−2ηgi⋅(xi−x∗)+η2∥gi∥2.
Expand ∥xi−ηgi−x∗∥2 with gi=∇f(xi) and η=1/L.
∥xi+1−x∗∥2≤∥xi−x∗∥2−2η(f(xi)−f(x∗))+η2∥gi∥2.
Gradient inequality for convex f (5.8) with y=x∗: f(x∗)≥f(xi)+gi⋅(x∗−xi), that is gi⋅(xi−x∗)≥f(xi)−f(x∗).
∥xi+1−x∗∥2≤∥xi−x∗∥2−2η(f(xi+1)−f(x∗)).
Descent lemma with η=1/L: f(xi+1)≤f(xi)−2η∥gi∥2, so η2∥gi∥2≤2η(f(xi)−f(xi+1)).
2ηi=1∑k(f(xi)−f(x∗))≤∥x0−x∗∥2.
Add the inequalities for i=0,…,k−1: the squared distances telescope, and ∥xk−x∗∥2≥0.
k(f(xk)−f(x∗))≤2η∥x0−x∗∥2.
By the descent lemma f(xi) is non-increasing, so every term is at least f(xk)−f(x∗). Divide by 2ηk=2k/L. ■
Proof workshopRebuild the proof that gradient descent on a convex smooth function has error at most L times the squared distance over 2kNesterov 2.1.5
Tap the lines in the order a proof would write them. Each line can only use what is already above it.
Expand the square of the updated point minus the minimiser.
The gradient inequality: the function lies above its tangent plane, evaluated at the minimiser.
The expansion of the squared distance has to come first; this bounds its middle term.
A step of length one over L lowers the function by at least a half of the step times the squared gradient.
This bounds the last term of the expansion, so the expansion comes first.
Combine the two bounds: the terms in f of x i cancel.
It needs both of the previous two bounds.
The squared distances telescope; every term of the sum is at least the last one.
The one-step inequality must be known before summing it.
Python labGradient descent on an ill-conditioned quadratic: the zig-zag, the rate, and momentum
import numpy as npimport matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltkappa = 100.0A = np.diag([1.0, kappa]); x0 = np.array([100.0, 1.0]) # f(x) = x^T A x / 2, minimum at the origindef run(step, beta=0.0, n=800): x, xp, err = x0.copy(), x0.copy(), [] for _ in range(n): err.append(np.linalg.norm(x)) x, xp = x - step * (A @ x) + beta * (x - xp), x # heavy-ball step (beta = 0 is plain descent) return np.array(err)L, mu = kappa, 1.0plain = run(2 / (L + mu)) # best fixed stepmom = run(4 / (np.sqrt(L) + np.sqrt(mu)) ** 2, beta=((np.sqrt(kappa) - 1) / (np.sqrt(kappa) + 1)) ** 2)rate = lambda e, a, b: (e[b] / e[a]) ** (1 / (b - a))print("plain: measured rate", round(rate(plain, 300, 400), 4), " theory (k-1)/(k+1) =", round(99 / 101, 4))print("momentum: measured rate", round(rate(mom, 100, 150), 4), " theory (sqrt(k)-1)/(sqrt(k)+1) =", round(9 / 11, 4))for name, e in (("plain", plain), ("momentum", mom)): print(name, "steps to shrink the error by 1e-6:", int(np.argmax(e < 1e-6 * e[0])))print("step 2.02/L, error after 400 steps:", round(run(2.02 / L, n=400)[-1], 1), "(diverges)")plt.semilogy(plain, label="plain descent"); plt.semilogy(mom, label="momentum")plt.xlabel("step"); plt.ylabel("distance to minimum"); plt.legend()
Try this.Run it. Plain descent with the best step has measured rate 0.9802 = 99/101 and needs 691 steps to shrink the error a million times; momentum has measured rate 0.8246, close to the theoretical 9/11 = 0.8182 (the extra is a polynomial factor at the edge of the stable region), and needs 83 steps. Step 2.02/L is slightly above the limit 2/L and the error grows. Change kappa to 10 and then to 1000: the plain step count scales like kappa (69, 691 and 6908 steps: about 6.9 kappa, which is (kappa/2) ln 10^6), and the momentum count like the square root of kappa (26, 83 and 264 steps). Print the first few x values of plain descent to see the y-coordinate flipping sign, and change x0 to (1, 1) to see how the start affects the transient but not the rate.
Momentum
Definition A
Momentum
Momentum (Polyak’s heavy ball) replaces gradient descent by xk+1=xk−η∇f(xk)+β(xk−xk−1) with 0≤β<1. Equivalently the ‘velocity’ vk=xk−xk−1 satisfies vk+1=βvk−η∇f(xk) and xk+1=xk+vk+1: a ball with friction rolling in the landscape.
In one lineThe modification xk+1=xk−η∇f(xk)+β(xk−xk−1) that adds a fraction β of the previous step to the gradient step (the heavy-ball method of Polyak).
Why it existsIt lets the iterate build up speed along a valley floor, where the gradients keep pointing the same way, and cancels the sideways bouncing, where the gradients alternate; on quadratics it improves the rate from κ to κ steps.
Theorem BPolyak 1964; Goh, Why Momentum Really Works (2017)
Momentum on a quadratic
Let f(x)=21xTAx−bTx with the eigenvalues of A in [μ,L]. With η=(L+μ)24 and β=(κ+1κ−1)2 the heavy-ball errors satisfy ∥ek∥≤C(1+k)(κ+1κ−1)k.
In one lineFor a quadratic with eigenvalues in [μ,L], the heavy-ball method with η=(L+μ)24 and β=(κ+1κ−1)2 makes the error decay at the rate κ+1κ−1 (up to a factor polynomial in k).
Why it is trueIt shows that the right amount of memory turns the condition number κ into κ in the iteration count: for κ=104, about 100 times fewer steps.
ProofPolyak 1964; Goh 2017
The idea: Diagonalise as before. In each eigen-direction the error obeys a two-term linear recurrence whose characteristic roots are complex, of the same absolute value square root of beta, whenever one plus beta minus eta times the eigenvalue is at most two root beta in absolute value. The chosen eta and beta make this hold exactly across the whole range of eigenvalues.
For eigenvalue λ: ck+1=(1+β−ηλ)ck−βck−1.
Subtract the minimiser from the update and use ∇f(x)=A(x−x∗): ek+1=ek−ηAek+β(ek−ek−1). In an orthonormal eigenbasis of A (spectral theorem) coordinate i evolves independently.
The roots are z=2τ±τ2−4β with τ=1+β−ηλ.
A two-term recurrence ck+1=τck−βck−1 has solutions built from the roots of z2−τz+β=0.
Both roots have absolute value exactly β, so ∣ck∣≤C(1+k)(β)k (the factor 1+k appears only when the roots coincide).
If ∣τ∣≤2β the square root is imaginary (or zero) and ∣z∣2=4τ2+(4β−τ2)=β.
So the condition ∣τ∣≤2β holds for every eigenvalue in [μ,L], with β=κ+1κ−1. ■
Write s=κ. Then β=(s+1)2(s−1)2, ηL=(s+1)24s2 and ημ=(s+1)24. So τ=1+β−ηλ ranges over [1+β−ηL,1+β−ημ]=[−s+12(s−1),s+12(s−1)]=[−2β,2β] as λ runs over [μ,L].The recipe for η and β was designed to make the two ends of the eigenvalue range land exactly on the edge of the oscillating region.
Worked example
Compare plain descent and momentum for κ=100.
Solution.
Plain descent.ρ∗=10199=0.9802; steps for a factor 10−6: ln(101/99)ln106≈691. Theorem on quadratics.
Momentum parameters.κ=10, so β=(119)2=12181=0.669 and, for μ=1, L=100, η=(10+1)24=1214=0.0331. Formulas of the theorem.
Rate.κ+1κ−1=119=0.8182; the ideal count is ln(11/9)ln106≈69 steps. Same formula as plain descent with κ in place of κ.
In practice. The lab above measures a rate of 0.8246 and 83 steps (the factor 1+k and the transient add some). The bound has a polynomial factor in front.
Answer. About 690 steps against about 70 to 85: a factor of 8 to 10, which is κ. For κ=104 the gap is a factor of 100.
Your answerFor a quadratic with κ=100, what is the per-step convergence rate (κ−1)/(κ+1) of optimally tuned momentum?
100=10, so the rate is 10+110−1=119≈0.818, against 10199≈0.980 for plain descent.
Quick checkIn the heavy-ball method, what happens as the momentum β approaches 1 with the step size fixed?
The velocity is multiplied by β at each step, so with β near 1 there is almost no friction: the iterate swings past the minimum and back many times. The optimal β=(κ+1κ−1)2 is close to 1 only when κ is large, matching the amount of damping the problem needs.
Beyond the course: for understanding· Nesterov's acceleration, and conjugate gradients
Yurii Nesterov (1983) modified the method by evaluating the gradient at a point ahead of the current one, xk+β(xk−xk−1), instead of at xk. For smooth convex functions (no strong convexity) this improves the bound O(1/k) above to O(1/k2), which is optimal among first-order methods; for strongly convex functions it gives a rate of order 1−1/κ per step without needing a quadratic. On quadratics the method of conjugate gradients (MATH 340) reaches the same rate by choosing the step and the momentum at each iteration from the data, with no tuning, and finds the exact minimiser in at most n steps in exact arithmetic.
Stochastic gradient descent
A loss in machine learning is an average over data, ℓ(w)=N1∑i=1Nℓi(w), with N in the millions. Its gradient is the average of N per-example gradients, and computing it costs N backward passes. The idea of stochastic gradient descent is to use the gradient of one randomly chosen term.
Definition A
Stochastic gradient descent
Let ℓ=N1∑ℓi. Stochastic gradient descent (SGD) is wk+1=wk−ηk∇ℓik(wk) where ik is chosen uniformly at random from {1,…,N} at each step. Because each index has probability N1, the average of the step over the random choice is −ηk∇ℓ(wk): the stochastic gradient is an unbiased estimate of the true gradient. A minibatch of B examples uses the average of B such gradients.
In one lineThe iteration wk+1=wk−ηk∇ℓik(wk) in which ik is an example chosen at random; each step costs one example instead of N.
Why it existsIts step is, on average, the true gradient step, but costs N times less, which is what makes training on huge datasets possible.
Where this came from· Robbins and Monro, 1951
Herbert Robbins and Sutton Monro published “A stochastic approximation method” in the Annals of Mathematical Statistics in 1951. Their problem was not machine learning. To find the level x at which an unknown response function M(x) equals a target value α one can only run experiments, and every experiment returns M(x) plus random noise. They proposed to adjust the level after each experiment by a step proportional to the observed discrepancy, with step sizes ak shrinking so that the sum of the ak is infinite (the search can travel anywhere) and the sum of the ak2 is finite (the noise is eventually averaged out), for example ak=1/k, and proved convergence in probability. Stochastic gradient descent is the Robbins–Monro scheme with the response function replaced by a gradient. The two conditions on the step sizes are still the textbook ones.
Theorem Bstandard; the one-dimensional model of Robbins and Monro (1951)
Noise floor of stochastic gradient descent
Let a1,…,aN be numbers with mean aˉ and variance σ2=N1∑(ai−aˉ)2, ℓi(w)=21(w−ai)2, so ℓ(w)=N1∑ℓi(w) is minimised at aˉ. Run wk+1=wk−η(wk−aik) with ik drawn uniformly and independently. Then with ek=wk−aˉ: (a) E[ek+1]=(1−η)E[ek]; (b) E[ek+12]=(1−η)2E[ek2]+η2σ2, so for 0<η<2, E[ek2]→2−ηησ2. (c) With ηk=k+11 and w0 arbitrary, wk is the average of the first k sampled values ai0,…,aik−1, and E[ek2]=σ2/k.
In one lineFor the loss N1∑21(w−ai)2, whose minimiser is the mean aˉ, SGD with a fixed step η∈(0,2) has E[wk]−aˉ→0 but E[(wk−aˉ)2]→2−ηησ2, where σ2 is the variance of the ai; with steps ηk=k+11 the iterate is the running average and the error tends to 0.
Why it is trueIt shows the central trade-off of stochastic methods in one formula: the noise floor is proportional to the learning rate, so a constant step cannot converge exactly, and decreasing steps are needed.
Proofstandard
The idea: Write the error update as a contraction of the old error plus a fresh zero-mean noise term. The noise is independent of the old error, so the variances add.
ek+1=(1−η)ek+ηξk with ξk=aik−aˉ, which has average 0 and average square σ2 and is independent of ek.
wk+1−aˉ=(1−η)(wk−aˉ)+η(aik−aˉ).
E[ek+1]=(1−η)E[ek].
Take averages: E[ξk]=0. This is (a).
E[ek+12]=(1−η)2E[ek2]+η2σ2. This is (b)‘s recursion.
Square the update: ek+12=(1−η)2ek2+2η(1−η)ekξk+η2ξk2. The cross term has average E[ek]E[ξk]=0 by independence.
E[ek2]→η(2−η)η2σ2=2−ηησ2.
The recursion vk+1=γvk+c with γ=(1−η)2<1 converges to the fixed point v=1−γc. Here 1−γ=1−(1−η)2=η(2−η).
This gives (c).
With ηk=k+11: wk+1=k+1kwk+k+11aik, which is the running average (induction). The average of k independent samples has variance σ2/k. ■
Worked example
A loss has per-example optima ai with variance σ2=4. What noise floor does SGD with η=0.1 have, and what does a minibatch of B=10 do?
Solution.
Single example.E[e2]→2−ηησ2=1.90.1⋅4=0.2105, so the typical error is 0.2105=0.459. The theorem. The iterate fluctuates around aˉ with this standard deviation even though the step is small.
Minibatch of 10. The average of 10 independent terms has variance σ2/10=0.4, so the floor becomes 1.90.1⋅0.4=0.0211, ten times lower. Replace σ2 by σ2/B in the recursion.
Halve the step.η=0.05 halves the floor (to ≈0.103) but also halves the speed of forgetting the start, which is (1−η)k. The trade-off of the theorem.
Answer.0.2105; with minibatch 10, 0.0211. The learning-rate schedules used in practice (large first, then decayed, e.g. ηk∝1/k) are the Robbins–Monro conditions in disguise: large steps to forget the start quickly, small steps at the end to average the noise out.
Your answerSGD on N1∑21(w−ai)2 with σ2=4 and η=0.1: what is the long-run E[(wk−aˉ)2]? (Give a decimal.)
2−ηησ2=1.90.4≈0.2105.
Quick checkWhy does SGD with a constant learning rate not converge exactly to the minimiser?
The stochastic gradient is unbiased, so the average step is right. But at the minimiser ∇ℓ=O while the individual ∇ℓi are not, so each step adds a random kick of size η× (spread of the ∇ℓi). The theorem computes the resulting spread: ησ2/(2−η), proportional to η for small η.
Newton’s method in many variables
Gradient descent uses a linear model of f and has to guess how far to trust it. If we also use the second derivative, we can ask for the minimum of the quadratic model.
Definition A
Newton's method
For a root-finding problem F(x)=O with F:Rn→Rn and Jacobian matrix JF, Newton’s method is xk+1=xk−JF(xk)−1F(xk), that is, solve the linear system JF(xk)s=−F(xk) and set xk+1=xk+s: replace F by its linearization (5.3) and solve exactly. To minimise f take F=∇f, so JF=Hf, the Hessian (5.6). In one variable this is the Newton iteration of 4.2.
In one lineThe iteration xk+1=xk−Hf(xk)−1∇f(xk) for minimising f, which is Newton's method for solving the system ∇f=O, and jumps to the minimum of the second-order Taylor model at each step.
Why it existsIt corrects the step in each direction by the curvature in that direction, so it does not care how badly conditioned the problem is, and near a minimum it converges quadratically.
Why· Two ways to see the same step
(1) Linearise the gradient.∇f(x+s)≈∇f(x)+Hf(x)s; setting it to O gives s=−Hf(x)−1∇f(x). (2) Minimise the quadratic model. The second-order Taylor formula (5.6) says f(x+s)≈f(x)+∇f(x)⋅s+21sTHf(x)s; if Hf(x) is positive definite, this is a quadratic in s with a unique minimiser, found where its gradient ∇f+Hfs is O: the same s. On a quadratic function the model is the function, so Newton’s method finds the minimum in one step, from any start, whatever the condition number: x−A−1(Ax−b)=A−1b.
Theorem Bstandard (Nocedal and Wright 3.5; Kantorovich); 376 HW7 #3 for one variable
Quadratic convergence of Newton's method
Let F:Rn→Rn be C1 near a root x∗, with JF(x∗) invertible, β0=∥JF(x∗)−1∥, and ∥JF(x)−JF(y)∥≤M∥x−y∥ for x,y in a ball around x∗ containing the iterates. If ∥x0−x∗∥≤r:=2β0M1, then every iterate is defined, and ∥xk+1−x∗∥≤β0M∥xk−x∗∥2≤21∥xk−x∗∥.
In one lineIf F(x∗)=O, JF(x∗) is invertible with ∥JF(x∗)−1∥≤β0 and JF is M-Lipschitz near x∗, then for ∥x0−x∗∥≤2β0M1 the Newton iterates satisfy ∥xk+1−x∗∥≤β0M∥xk−x∗∥2: the number of correct digits doubles at each step.
Why it is trueIt explains the speed seen in practice (five or six steps to machine precision) and says exactly what 'close enough to start' means, in terms of the curvature of F and the invertibility of its Jacobian.
ProofNocedal and Wright 3.5
The idea: Subtract the root from the Newton update and rewrite the right side as the inverse Jacobian applied to the remainder of the linear approximation. The remainder is at most M over two times the squared error, and the Jacobian is invertible with norm at most twice its norm at the root, close to the root.
The matrix J(xk) is invertible: ∥(I+E)v∥≥∥v∥−21∥v∥=21∥v∥, so I+E is one-to-one, hence invertible, and ∥(I+E)−1∥≤2. Therefore ∥J(xk)−1∥≤2β0.
Put e=xk−x∗ with ∥e∥≤r. ∥J(xk)−J(x∗)∥≤M∥e∥≤2β01. Then J(xk)=J(x∗)(I+E) with E=J(x∗)−1(J(xk)−J(x∗)) and ∥E∥≤β0⋅2β01=21.
xk+1−x∗=J(xk)−1R with R=F(x∗)−F(xk)−J(xk)(x∗−xk).
xk+1−x∗=xk−x∗−J(xk)−1F(xk)=J(xk)−1[J(xk)(xk−x∗)−F(xk)] and F(x∗)=O, so the bracket equals +[F(x∗)−F(xk)−J(xk)(x∗−xk)].
∥R∥≤2M∥e∥2.
Fundamental theorem of calculus along the segment (5.3): F(x∗)−F(xk)=∫01J(xk+t(x∗−xk))(x∗−xk)dt. So R=∫01[J(xk+t(x∗−xk))−J(xk)](x∗−xk)dt, and the Lipschitz bound gives ∥R∥≤∫01Mt∥e∥2dt=2M∥e∥2.
∥xk+1−x∗∥≤β0M∥e∥2≤21∥e∥.
Multiply the bounds: 2β0⋅2M∥e∥2=β0M∥e∥2. And β0M∥e∥≤β0Mr=21. Induction keeps xk+1 inside the ball. ■
Worked example MATH 376 HW7 #3 and Worksheet 19 #2 (one variable)
Heron's method for 2 is Newton's method for x2−2=0. Show that the error is squared at each step, and run four steps from x0=1.5.
Solution.
The Newton map. For f(x)=x2−2: N(x)=x−2xx2−2=21(x+x2). One-variable Newton: subtract f/f′. The fixed point is 2.
The error identity.N(x)−2=2xx2−22x+2=2x(x−2)2. Put everything over the common denominator 2x; the numerator is a perfect square.
Read it. With ek=xk−2: ek+1=2xkek2≈0.354ek2 once xk≈2. The error is squared, times the constant 2f′f′′=221 at the root. This is the theorem above with β0=221 and M=2.
Run it.x0=1.5 has e0=0.0858. Then x1=1.416667 (e1=2.5×10−3), x2=1.41421569 (e2=2.1×10−6), x3=1.41421356237469 (e3=1.6×10−12), and x4 is 2 to machine precision. Check one step: 0.08582/3=0.00245. The number of correct digits goes 1,2,5,11,16: roughly doubling.
Answer.ek+1=ek2/(2xk); four steps give 2 to full double precision.
Worked example new (the standard test problem)
Newton's method on the Rosenbrock function f(x,y)=(1−x)2+100(y−x2)2 from (−1.2,1).
Solution.
Gradient and Hessian.∇f=(−2(1−x)−400x(y−x2),200(y−x2)) and Hf=[2−400(y−x2)+800x2−400x−400x200]. Direct differentiation; at the minimum (1,1), H=[802−400−400200] with eigenvalues 0.4 and 1001.6, so κ≈2500.
First step. At (−1.2,1): f=24.2, ∇f=(−215.6,−88), H=[1330480480200]. Solving Hs=−∇f gives s=(0.0247,0.3807) and x1=(−1.1753,1.3807), f=4.73. Solve a 2×2 linear system.
Second step. From x1 Newton jumps to (0.7631,−3.1750) with f=1412: the function went up. Far from the minimum the quadratic model is a poor guide, and Newton’s method only aims for a critical point, not for descent.
Then convergence.x3=(0.7634,0.5828), f=0.056; x4=(0.99999,0.944); x5=(0.999996,0.999991) with f=1.9×10−11; x6=(1,1) to machine precision. Once close, the error is squared at each step: 0.056→0.31→10−11→10−20 in f.
Compare. Plain gradient descent with a step near the stability limit (η=10−3; the largest Hessian eigenvalue is 1506 at the start, so 2/L=0.0013) has f=0.0038 after 5000 steps and 1.9×10−8 after 20000. The valley is curved and narrow (κ≈2500 at the minimum), and the step is limited by the steepest wall.
Answer. Newton converges in 6 steps against tens of thousands for gradient descent, but its path is erratic (step 2 lands at f=1412). Practical implementations add a line search or a trust region (they cut the step when the function rises) and fall back on a descent direction when the Hessian is not positive definite.
Watch out· Newton's method is attracted to every critical point, saddles and maxima included
For f(x)=−x2 (a maximum at 0), Newton gives x−−2−2x=x−x=0 in one step: it lands exactly on the maximum. For f=x2−y2 it jumps to the saddle at the origin. It is solving ∇f=O, which has no preference between minima, maxima and saddles. Gradient descent, in contrast, is repelled from maxima and almost never settles at saddles.
Same idea elsewhere· Cost: why neural networks do not use Newton's method
Newton needs the Hessian, n2 numbers, and a solve with it, about n3 operations. A network with n=106 weights has a Hessian with 1012 entries, which in 4-byte floats is 4 terabytes. Quasi-Newton methods (BFGS and its low-memory form L-BFGS) build an approximation of H−1 from the last few gradients and are used for smaller problems; for deep networks, ‘diagonal’ rescalings of the gradient (Adam, Kingma and Ba, 2014) approximate the idea cheaply, dividing each coordinate’s step by a running estimate of its gradient size.
Quick checkNewton's method is applied to f(x)=−x2+3 starting at x0=5. Where does it go?
f′=−2x, f′′=−2, so the Newton step is x−−2−2x=0. Newton solves f′=0 and does not care whether the solution is a minimum or a maximum. This is why it is combined with safeguards that check that the Hessian is positive definite.
Training a small neural network
A neural network is a composition of differentiable maps, so by the chain rule of 5.4 its loss is a differentiable field of the weights, and its gradient is computed by backpropagation (3.8): the computational graph is traversed backwards, multiplying Jacobians. Everything in this chapter applies. As a concrete case, a tiny network with 2 inputs, 3 tanh hidden units and 1 linear output (13 parameters) learns XOR: the four inputs (0,0),(0,1),(1,0),(1,1) with targets −1,+1,+1,−1. No linear model can do this (the points are not linearly separable), but a hidden layer can.
Python labTrain a 2-3-1 network on XOR with backpropagation and gradient descent
import numpy as npX = np.array([[0., 0.], [0., 1.], [1., 0.], [1., 1.]]); y = np.array([-1., 1., 1., -1.]) # XORdef loss_grads(P): W1, b1, w2, b2 = P h = np.tanh(X @ W1 + b1); out = h @ w2 + b2; d_out = (out - y) / len(y) d_pre = np.outer(d_out, w2) * (1 - h ** 2) # backpropagation (3.8): chain rule from the loss backwards return 0.5 * np.mean((out - y) ** 2), out, [X.T @ d_pre, d_pre.sum(0), h.T @ d_out, d_out.sum(keepdims=True)]def init(seed, H=3): rng = np.random.default_rng(seed) return [rng.normal(0, 1, (2, H)), np.zeros(H), rng.normal(0, 1, H), np.zeros(1)]P = init(1); G = loss_grads(P)[2]; worst = 0.0for p, g in zip(P, G): # gradient check by central differences, one parameter at a time for i in np.ndindex(p.shape): old = p[i]; p[i] = old + 1e-6; up = loss_grads(P)[0]; p[i] = old - 1e-6; dn = loss_grads(P)[0]; p[i] = old worst = max(worst, abs((up - dn) / 2e-6 - g[i]))print("backprop vs central differences, largest error over the 13 parameters:", f"{worst:.1e}")def train(seed, eta=0.1, steps=3000, H=3, show=False): P = init(seed, H) for k in range(steps + 1): loss, out, G = loss_grads(P) if show and k in (0, 10, 100, 200, 300, 400, 500, 1000, 3000): print(f"{k:5d} loss {loss:.3e} |grad| {np.sqrt(sum(np.sum(g**2) for g in G)):.3e}") for p, g in zip(P, G): p -= eta * g return loss, outtrain(1, show=True)print("final loss for seeds 0..9:", [f"{train(s)[0]:.0e}" for s in range(10)])loss, out = train(2); print("seed 2 stalls at loss", round(loss, 3), "with outputs", out.round(2))
Try this.Run it. The gradient check at the top compares the backpropagation gradient with central differences for all 13 parameters and agrees to about 1e-10: backpropagation is the chain rule applied to the whole network. The loss then falls slowly for about 200 steps (a plateau where the gradient is small), drops fast, and ends below 1e-20: the network represents XOR exactly. The last line shows a failure: for seed 2 the same code is still at loss 0.25 after 3000 steps, with two of the four outputs at 0. Training a non-convex loss depends on the starting point. Try eta = 1.0: eight of the ten seeds still converge (and seed 2 now escapes its stall), but seeds 0 and 7 give nan (the step is above the stability limit 2/L near their start). Try H = 2 and H = 8 hidden units and count how many of the ten seeds succeed.
Saddle points in high dimension
Critical points of a smooth function (5.6) are classified by the signs of the Hessian’s eigenvalues. A strict local minimum needs all n of them positive. For a loss with a million parameters this is an extremely demanding requirement, and a critical point with both positive and negative eigenvalues is a saddle.
Proposition Bstandard (the exact solution of the linear case)
Gradient descent near a saddle
Let f(x,y)=21(ax2−γy2) with a,γ>0 and η<2/a. Gradient descent gives xk+1=(1−ηa)xk and yk+1=(1+ηγ)yk. So xk→0 and yk=(1+ηγ)ky0, which grows without bound unless y0=0. The number of steps to grow from ∣y0∣ to 1 is ln(1+ηγ)ln(1/∣y0∣)≈ηγln(1/∣y0∣).
In one lineFor f=21(ax2−γy2) with a,γ>0, gradient descent with step η has yk=(1+ηγ)ky0: it leaves the saddle exponentially fast but with a time of order ηγ1ln∣y0∣1, which is long when the negative curvature γ is small.
Why it is trueIt shows why training stalls near saddles: where the downhill curvature is small the gradient is tiny and escape takes many steps, though it always happens unless the start is exactly on the stable direction.
Proofstandard
The idea: The gradient is (a x, minus gamma y), so each coordinate is multiplied by a constant at every step. The second constant exceeds one.
xk+1=(1−ηa)xk and yk+1=(1+ηγ)yk.
∇f=(ax,−γy), so the update xk+1=xk−ηaxk and yk+1=yk+ηγyk.
xk→0 and ∣yk∣=(1+ηγ)k∣y0∣→∞ if y0=0.
Geometric sequences: ∣1−ηa∣<1 for 0<η<2/a, while 1+ηγ>1.
k=ln(1+ηγ)ln(1/∣y0∣).
Solve (1+ηγ)k∣y0∣=1 for k, and use ln(1+u)≈u for small u. ■
Worked example
A saddle with weak negative curvature: f=21(x2−0.01y2), η=0.1, start at y0=10−6. How long does descent take to leave?
Solution.
Setup.a=1, γ=0.01, ηγ=0.001, so yk=(1.001)ky0. The proposition.
Steps to reach ∣y∣=1.k=ln1.001ln106=0.000999513.8155≈13,822. Solve (1.001)k⋅10−6=1.
Meaning. The iterate sits within 10−6 of the saddle for most of those steps, where the gradient is about 10−8: the loss curve looks flat, as if training had converged. The gradient norm in y is γ∣yk∣, tiny until the very end.
Answer. About 13,800 steps; with a tenfold stronger curvature (γ=0.1) it would take about 1380.
Your answerIn the saddle example (ηγ=0.001, y0=10−6), about how many steps does gradient descent take for ∣y∣ to grow from 10−6 to 1? (Give a decimal.)
(1.001)k=106 gives k=ln106/ln1.001≈13,822.
Beyond the course: for understanding· Why saddles dominate in high dimension (a heuristic), and what is known
Suppose that at a critical point each of the n Hessian eigenvalues were independently positive or negative with equal chance. Then the chance that all are positive is 2−n: for n=1000, about 10−301. So most critical points would be saddles, and the few minima would be extraordinarily rare. Real Hessians are not like this (their eigenvalues are strongly correlated), but the experience with large networks is consistent with it: the main obstacle in practice is long plateaus near saddles, and the local minima that gradient methods find tend to have loss close to the best known. A theorem in the same direction (proved with the stable manifold theorem, so beyond this book): gradient descent with a small fixed step from a random start almost surely avoids saddles that have at least one strictly negative eigenvalue. The minibatch noise of SGD helps further: the random kicks push the iterate off the unstable ridge sooner than the deterministic computation above.
Quick checkAt a critical point of a loss with 106 parameters, the Hessian has 999,999 positive eigenvalues and one eigenvalue equal to −0.001. What is it, and what does gradient descent do near it?
A local minimum needs all eigenvalues non-negative (5.6). One negative eigenvalue makes it a saddle. The escape direction grows like (1+0.001η)k, which is slow because the curvature is small, so the loss curve plateaus, as in the saddle example.
Where it is used
Used inside maths· Inside maths: fixed points, ODEs and eigenvalue algorithms
Gradient descent is the fixed-point iteration of 4.2 for T(x)=x−η∇f(x), and the contraction corollary above is a direct application of the Banach theorem; the same fixed-point idea proves existence for ODEs by Picard’s iteration (7.1). Its continuous-time limit, x′(t)=−∇f(x(t)) (the gradient flow), is an ordinary differential equation, along which f decreases: dtdf(x(t))=−∥∇f∥2 by the path theorem. Newton’s method is the multivariable form of the iteration whose local contraction was proved in 4.2, and its convergence proof above uses exactly the mean value and invertibility arguments of 5.7. With exact line search on a quadratic, steepest descent is the template that conjugate gradients improves on.
Used in the real world· AI: training a model, in numbers
A language model with n=109 parameters is trained by minibatch SGD or Adam on trillions of tokens. Each step computes a gradient of 109 numbers by backpropagation, at a cost comparable to a few forward passes (3.8). The learning rate is typically chosen by trial, then warmed up from near 0 over the first thousand steps (to avoid the instability when the gradient is large and the step is above 2/L of the starting region) and decayed afterwards (the Robbins–Monro conditions: large steps to travel, small steps to average out the noise). A linear regression with 106 features and 107 rows has XTX with 1012 entries; gradient descent never forms it, and costs two products with X per step (2×1013 operations) instead of the 1018 of solving the normal equations. If the features are not standardised, κ(X) can be 103, making κ(XTX)=106 and the rate 1−2×10−6: half a million steps per e-fold of error. Standardising can bring κ(X) down to 10, so κ=100 and about 350 steps give a thousandfold reduction of the error.
Traps
Watch out· A small learning rate is only small relative to the curvature
The stability limit is 2/L, where L is the largest Hessian eigenvalue. A learning rate of 0.1 is safe for L=1 and explosive for L=100. If the loss goes to ∞ or nan in the first steps, cut the rate by a factor of 10.
Watch out· Zig-zag is not a bug
Plain gradient descent on a narrow valley must zig-zag (consecutive exact line-search gradients are perpendicular, and at the best fixed step the steep coordinate flips sign every step). Do not conclude the gradient is wrong. Cures: momentum, preconditioning (rescaling the variables to reduce κ), or second-order information.
Watch out· A flat loss curve is not convergence
Near a saddle (or in a very flat valley) the gradient is tiny and the loss barely moves for thousands of steps, then drops suddenly. Check the gradient norm and the Hessian spectrum before stopping.
Watch out· SGD with a constant rate has a noise floor
The loss curve of SGD fluctuates around a level proportional to the learning rate. It does not mean the model has stopped improving: lowering the rate lowers the floor (the schedule of Robbins and Monro).
Watch out· The loss can go up
Gradient descent with a small enough step lowers f at every step (descent lemma). Newton’s method does not (the Rosenbrock example went from 4.7 to 1412), SGD does not, and momentum does not. The ‘decrease every step’ check belongs only to the first.
Watch out· Convex and non-convex are different problems
For a convex function, any local minimum is global and gradient descent finds it. A neural network’s loss is not convex, and the final loss depends on the starting weights (the lab: seed 2 is stuck at 0.25 while nine other seeds reach 10−29).
Problems
check
For f(x,y)=21(2x2+8y2), what are L, μ, κ, the stable range of η, and the best step?
Solution
The Hessian is diag(2,8), so μ=2, L=8, κ=4. Gradient descent converges iff 0<η<2/L=0.25. The best step is η∗=L+μ2=102=0.2, with rate κ+1κ−1=53 (check: ∣1−0.2⋅2∣=0.6 and ∣1−0.2⋅8∣=0.6).
check
Do one step of gradient descent with η=0.1 on f(x,y)=x2+5y2 from (3,1).
Solution
∇f=(2x,10y)=(6,10), so the new point is (3−0.6,1−1.0)=(2.4,0). The y-coordinate was killed in one step because 1−0.1⋅10=0 (the Hessian is diag(2,10) and η=1/L). f fell from 32+5=14 to 5.76.
check
Newton’s method for f(x)=x4 is x↦x−12x24x3=32x. Is the convergence quadratic? Why or why not?
Solution
The iterates xk=(32)kx0 converge only linearly (the error is multiplied by 32 each time). The quadratic convergence theorem needs an invertible Hessian at the minimiser, and f′′(0)=0 here: the hypothesis fails.
check
True or false: gradient descent with exact line search on a quadratic in two variables moves along perpendicular directions in consecutive steps. Why?
Solution
True. The exact step minimises ϕ(η)=f(xk−ηgk), so ϕ′(ηk)=−∇f(xk+1)⋅gk=0: the new gradient is perpendicular to the old one. (This holds for any smooth f, not only quadratics.)
usenew (least squares by gradient descent)
For f(w)=21∥Xw−y∥2 with XTX=[5335], find the best fixed learning rate and the number of steps to reduce the error by a factor 10−3.
Solution
The eigenvalues of XTX are 2 and 8, so μ=2, L=8, κ=4. The best step is η∗=102=0.2 with rate ρ∗=53=0.6. We need 0.6k≤10−3: k≥ln(1/0.6)ln1000=0.51086.908=13.5, so 14 steps.
usenew (momentum numbers)
For μ=1 and L=400, give the optimal heavy-ball parameters and the rate, and compare the predicted number of steps with plain descent for a factor 10−6.
Solution
κ=400, κ=20. β=(2119)2=0.8186, η=(20+1)24=4414=0.00907 (with L+μ=21), rate 2119=0.9048. Steps: ln(21/19)ln106=0.100113.82≈138. Plain descent: rate 401399, steps ln(401/399)13.82=0.00500013.82≈2763. The ratio is about 20=κ.
usenew (SGD)
An SGD run with η=0.05 on a one-parameter least-squares loss has per-example variance σ2=9. Find the long-run variance of the iterate, and the batch size that brings it below 0.01.
Solution
Floor =2−ηησ2=1.950.45=0.2308. With batch size B: 2−ηησ2/B=B0.2308<0.01 needs B>23.1, so B=24.
usenew (Newton in two variables)
Do one Newton step for f(x,y)=x2+xy+2y2−3x from (0,0) and verify that it lands on the minimiser.
Solution
∇f=(2x+y−3,x+4y), which at the origin is (−3,0). H=[2114] (constant, positive definite: trace 6, determinant 7). Solve Hs=(3,0): from the second row s1=−4s2; the first gives −8s2+s2=3, s2=−73, s1=712. So the new point is (712,−73). Check: ∇f=(724−73−3,712−712)=(0,0). ✓ A quadratic is solved in one step.
prove
Prove that gradient descent with η≤1/L on an L-smooth function satisfies ∑k=0K−1∥∇f(xk)∥2≤η2(f(x0)−fmin) if f is bounded below by fmin, so that mink∥∇f(xk)∥→0 at the rate K−1/2 (no convexity needed).
Solution
Plan. Sum the descent lemma over the steps.
By the descent lemma, f(xk+1)≤f(xk)−2η∥∇f(xk)∥2. Summing from k=0 to K−1 telescopes: f(xK)≤f(x0)−2η∑k=0K−1∥∇f(xk)∥2. Since f(xK)≥fmin, ∑k=0K−1∥∇f(xk)∥2≤η2(f(x0)−fmin). The smallest of the K terms is at most the average, so mink∥∇f(xk)∥2≤ηK2(f(x0)−fmin). ■ For a non-convex loss this is the strongest general statement: the gradient becomes small, though the point need not be near a minimum.
provenew (unbiasedness)
Show that the minibatch gradient g=B1∑j=1B∇ℓij(w) with the ij drawn independently and uniformly from {1,…,N} has average ∇ℓ(w), and in the one-dimensional model of the SGD theorem has variance σ2/B.
Solution
Plan. Linearity of averages for the mean; independence for the variance.
For one index, the average of ∇ℓi(w) over the uniform choice is N1∑i∇ℓi(w)=∇ℓ(w), since the gradient of a sum is the sum of the gradients. A minibatch averages B such terms, so its average is ∇ℓ(w). In the model ∇ℓi(w)=w−ai, so the minibatch gradient is w−aˉB where aˉB is the average of B independent samples with variance σ2 each; the variance of an average of B independent terms is σ2/B. ■
provenew (the stability limit is sharp)
Show that for f=21λx2 with λ>0 in one variable, gradient descent converges for every start iff 0<η<2/λ, and for η=2/λ it oscillates forever without converging (unless started at 0).
Solution
Plan. The update is multiplication by a constant.
xk+1=xk−ηλxk=(1−ηλ)xk, so xk=(1−ηλ)kx0. This tends to 0 for all x0 iff ∣1−ηλ∣<1, i.e. 0<ηλ<2. At ηλ=2 the multiplier is −1 and xk=(−1)kx0 does not converge for x0=0. For ηλ>2 the multiplier is below −1 and ∣xk∣ grows. ■
provenew (Newton is affine invariant)
Let A be an invertible n×n matrix and g(z)=f(Az). Show that the Newton iterates for g started at z0 are zk=A−1xk, where xk are the Newton iterates for f started at x0=Az0, whereas gradient descent does not have this property.
Solution
Plan. Use the chain rule (5.4) for the gradient and the Hessian of g.
∇g(z)=AT∇f(Az) and Hg(z)=ATHf(Az)A. The Newton step for g at z is −Hg−1∇g=−A−1Hf−1A−TAT∇f(Az)=−A−1Hf(Az)−1∇f(Az), so Azk+1=Azk−Hf(Azk)−1∇f(Azk), which is the Newton step for f at xk=Azk. By induction xk=Azk. The gradient descent step for g is −ηAT∇f(Az), whose image under A is −ηAAT∇f, not −η∇f unless AAT=I: changing variables changes the conditioning, and gradient descent notices. ■ (Newton’s method does not care about the condition number; this is why preconditioning is an approximation to it.)
stretchnew (momentum on a one-dimensional quadratic)
For f(x)=21λx2 the heavy-ball recursion is xk+1=(1+β−ηλ)xk−βxk−1. Take β=0.5, ηλ=0.5 and compute x2,x3,x4 from x0=x1=1; then show that the rate is β when ∣1+β−ηλ∣≤2β.
Solution
Here 1+β−ηλ=1, so xk+1=xk−0.5xk−1. x2=1−0.5=0.5, x3=0.5−0.5=0, x4=0−0.25=−0.25. The condition ∣1∣≤20.5=1.414 holds, so the roots of z2−z+0.5=0 are 21±i, of absolute value 0.5=0.707=β: the sequence rotates and decays, which is the oscillation visible in the numbers (positive, zero, negative). In general for ∣τ∣≤2β the roots of z2−τz+β are complex conjugates (or equal) with product β, hence each has absolute value β; the error is a combination of zk and zˉk, so it decays like (β)k (times 1+k in the double root case).
stretchnew (the contraction view)
For f(x)=21x2+ln(1+ex) in one variable, show that gradient descent converges for η=1 using the contraction corollary, and find the contraction constant.
Solution
f′(x)=x+1+exex and f′′(x)=1+(1+ex)2ex∈[1,45] (since (1+ex)2ex≤41, with the maximum at x=0). So μ=1 and L=45, and η=1<2/L=1.6. The map T(x)=x−f′(x) has T′(x)=1−f′′(x)=−(1+ex)2ex∈[−41,0], so ∣T′∣≤41: T is a contraction with constant ρ=41=max(∣1−μ∣,∣1−L∣)=max(0,41). By Banach, gradient descent converges to the unique solution of f′(x)=0 (here x+1+exex=0, near −0.4), with error at most 3/4(1/4)k∣x1−x0∣.
Summary
Gradient descentxk+1=xk−η∇f(xk) follows the steepest descent direction of 5.2. For an L-smooth function a step η≤1/L lowers f by at least 2η∥∇f∥2 (descent lemma).
On a quadratic the error is multiplied by I−ηA: it converges iff 0<η<2/L, with rate max(∣1−ημ∣,∣1−ηL∣), best at η=L+μ2 where the rate is κ+1κ−1. The condition number κ of 3.5 sets the number of steps (about 2κlnε1), and the path zig-zags because the steep coordinate flips sign at every step. For least squares κ=κ(X)2.
For any C2 function with Hessian eigenvalues in [μ,L], x↦x−η∇f(x) is a contraction (Banach, 4.2). For convex smooth f, f(xk)−f∗≤2kL∥x0−x∗∥2.
Momentumxk+1=xk−η∇f(xk)+β(xk−xk−1) with the tuned η,β improves the rate to κ+1κ−1: κ steps instead of κ.
Stochastic gradient descent uses one example (or a minibatch) per step; the step is unbiased, the iterate has a noise floor proportional to ησ2/B, and steps must decrease (∑ηk=∞, ∑ηk2<∞; Robbins and Monro, 1951) to converge exactly.
Newton’s methodx−H−1∇f minimises the quadratic model, solves quadratics in one step, is invariant to conditioning, and converges quadratically near a minimiser with invertible Hessian; but it costs n2 memory and n3 time, is not monotone, and is attracted to saddles and maxima.
Training a network is gradient descent on a non-convex loss with the gradient from backpropagation (3.8): results depend on the start (one seed in ten failed in the lab).
In high dimension, saddle points are far more numerous than minima; near a saddle with weak negative curvature γ, descent leaves after about ηγln(1/∣y0∣) steps, so a flat loss curve is not proof of convergence.
Watch and read
The same ideas explained by someone else. Use these when an explanation here does not land.
MATH 340 / CS 532: Gradient descent, line search, conjugate gradients, Newton and quasi-Newton methods (BFGS) are the first chapters of numerical optimisation. The rate (κ-1)/(κ+1) of this chapter is the one that conjugate gradients improves to (√κ-1)/(√κ+1), the same as momentum.
MATH 521 / 541: Gradient descent as the fixed-point iteration x to x - η∇f(x) connects to the contraction principle of 4.2, and its continuous-time limit x' = -∇f(x) is a gradient flow, an ODE of the kind studied in Unit 7.
AI and machine learning: Every neural network is trained by a stochastic variant of this chapter: minibatch SGD with momentum, or Adam, which rescales each coordinate of the gradient. The learning rate is the most important hyperparameter, and its stability limit is 2/L for the largest Hessian eigenvalue L.
Statistics: Least squares can be solved by the normal equations (2.10) or by gradient descent; the second is what is done when the data matrix has a million columns. The condition number of X^T X is the square of that of X (3.5), which is why standardising the features speeds up training.