Loss surfaces and gradient descent
Before this lesson: partial derivatives and the gradient (calculus 02); vectors and dot products (linear algebra 01). Eigenvalues appear only as a preview. Time: about 55 minutes, plus the notebook.
Why this matters #
Every optimizer used to train neural networks is gradient descent with extra parts: SGD uses a noisy gradient from a minibatch (lesson 05), momentum adds memory of past steps (lesson 04), and Adam rescales each coordinate (lesson 06). So the basic behaviour of gradient descent explains a lot of what you see in practice. A loss that explodes in the first steps usually means a learning rate above the stability limit. A loss that falls quickly and then crawls usually means a narrow valley (an ill-conditioned problem, lesson 02). Standardizing input features before training linear models works because it makes the valley rounder.
1. Predict first #
2. The picture #
Loss surfaces and level sets #
An optimization problem asks for a point that makes a function as small as possible:
is the objective. In machine learning it is the loss , the average error of a model with parameters on the training data. We write and in general statements and and when we talk about training.
With two variables you can draw as a surface over the plane: the loss surface. A contour plot shows the same information from above. Each curve is a level set , the set of points with the same height . Where the curves are close together the surface is steep; where they are far apart it is flat.
- A minimizer satisfies for all . The value is the optimal value. This is a global minimum.
- A local minimum is a point that is lowest only in a small neighbourhood. A function can have several local minima with different heights.
- A stationary point (or critical point) has . Minima, maxima and saddle points are stationary points. At a saddle point the surface goes up in some directions and down in others.
The gradient points uphill, across the contours #
The gradient is the vector of partial derivatives. For a unit vector , the directional derivative is the slope of when you walk from in the direction . Since , where is the angle between and :
- the slope is largest, , when points along ();
- the slope is most negative, , when points along ;
- the slope is zero when is perpendicular to . These are the directions along the level set, where the height does not change.
Drag the violet point and the small grey handle . The violet curve is the level set through the point, the orange arrow is and the blue arrow is , the direction gradient descent takes. Notice that the gradient always crosses the level set at a right angle, so in the narrow valley it points mostly across the valley, not toward the minimum (the black star). Turn and watch : it is largest along and zero along the level set.
Gradient descent #
Gradient descent (GD) starts at a point and repeats
The positive number is the step size, called the learning rate in machine learning. Each step moves downhill, perpendicular to the current contour line. The step is long where the surface is steep (large gradient) and short where it is flat.
One variable: four regimes #
Take the simplest loss, a parabola with curvature . Then and one step gives
and so, after steps,
Everything depends on the single number :
| What the iterates do | ||
|---|---|---|
| between 0 and 1 | between 0 and 1 | shrink toward 0, always on the same side: monotone convergence |
| exactly 1 | 0 | reach the minimum in one step |
| between 1 and 2 | between and 0 | jump over 0 every step, but still shrinks: oscillating convergence |
| exactly 2 | jump between and forever | |
| above 2 | below | jump over 0 and grow every step: divergence |
So gradient descent on this parabola converges exactly when . A step that is too large does not fail at once. First it overshoots and oscillates (for ); it diverges only after the overshoot becomes larger than the distance it started from.
Predict, then play. Set with the slider, choose your prediction, then press Play. The blue arrows are the gradient-descent steps on the parabola; the chart on the right shows against . Try , , , and .
On you use a step with . What do the iterates do?
. The minus sign makes the iterates jump over the minimum; the factor makes them shrink. The limit for divergence is , not : at the step lands exactly on the minimum.
Two variables: one step size for two curvatures #
Now take . Its contours are ellipses, ten times steeper in the direction: a narrow valley along the axis. The gradient is , so gradient descent works on each coordinate separately:
These are two copies of the 1D problem, with and , but one must serve both:
- The steep coordinate needs , or it diverges.
- With just below , the factor for is close to : jumps from one wall of the valley to the other. This is the zig-zag.
- With such a small , the factor for is : progress along the valley floor is slow. This is the crawl.
The best compromise makes the two factors equally bad: gives , and then both factors have size . Even with this best fixed step, the error shrinks by only per step: about 69 steps to reduce it by a factor , against 1 step when both curvatures are equal (a round bowl with ).
The ratio of the largest to the smallest curvature, here , is the condition number . Lesson 02 defines it for any function and shows that it controls the speed of gradient descent.
Drag the blue start point and change the step. The slider gives in units of , where is the largest curvature (here ). The blue path is gradient descent; the chart shows on a log scale, with the theory bound dashed. Use the Try buttons: "too small" crawls, "best" uses , "just above " diverges in the steep direction. Then raise , and switch to the rotated quadratic: the valley no longer follows an axis, and the picture is the same.
Gradient descent runs on . Which coordinate sets the largest step size that does not diverge, and what is that step?
Each coordinate is a 1D problem with factor . It converges only if , and the strictest limit comes from the largest curvature, . The value is the best fixed step, not the largest stable one.
A first nonconvex surface #
Real losses are not quadratic. The double well has two minimizers, and , and a saddle point at between them. Gradient descent goes downhill from where it starts, so the start point decides which minimum it reaches. A start with ends at ; a start with ends at . A start exactly on the line slides down to the saddle point and stops there, because the gradient has no -component on that line. This start is a very special case; any tiny change of moves the path to one of the minima. Lesson 11 studies saddle points in high dimension.
Try it in the trajectory figure above: choose double well and drag the start across the line .
3. Definitions and main results #
Why is the steepest descent direction #
Theorem 1 (steepest ascent and descent). Let be differentiable at with . Among all unit vectors , the directional derivative is largest for and smallest for .
Proof.
- The directional derivative in direction is (chain rule, calculus 02).
- By the Cauchy–Schwarz inequality, .
- So . Equality on the right holds only when is a positive multiple of , and on the left only when is a negative multiple.
Theorem 2 (the gradient is perpendicular to the level set). Let be a differentiable curve inside the level set , with . Then .
Proof. for all . Differentiate with the chain rule: . Set .
So the gradient is perpendicular to every tangent direction of the level set. In 2D the level set is a curve, and the gradient is the normal of that curve.
A small enough step always goes down #
Theorem 3 (descent for small steps). Let be differentiable at with . Then for every small enough .
Proof.
- Write and . Then .
- By the chain rule, .
- A function with negative derivative at 0 is smaller than just to the right of 0: by the definition of the derivative, , so the quotient is negative for all small .
The theorem says "small enough", but not how small. For a quadratic we can compute the exact range; lesson 02 gives a range for any -smooth function: .
Fixed points are stationary points. If gradient descent converges, , and is continuous, then taking the limit in gives , so . The limit is a stationary point: a minimum, or (rarely) a saddle point as in the double well.
Gradient descent on quadratics #
Theorem 4 (1D quadratic). For with , gradient descent gives . It converges to 0 from every start if and only if .
Proof. The formula follows from by induction. A geometric sequence with goes to 0 if and only if . Here means , that is, .
Theorem 5 (separable 2D quadratic). Let with . Gradient descent converges from every start if and only if . The fixed step that makes the slower of the two factors as small as possible is , and then both factors have size .
Proof.
- The gradient is , so each coordinate follows Theorem 4 with its own . Both converge if and only if and . Since , the second condition is the binding one.
- The speed is set by the slower coordinate, .
- For both factors fall as grows, and for both rise. So the best lies in . There falls and rises, and their maximum is smallest where they are equal: , so .
- Insert this : .
For , : the limit is , the best step is , and the factor is . Lesson 03 proves the same for any quadratic , with replaced by the smallest and largest eigenvalues of .
On the double well , gradient descent with a small step starts at . Where does it end?
Each step goes downhill. The gradient's first component is , which is positive for , so decreases toward : the path never crosses the line . Nonconvexity does not stop convergence; it means the answer depends on the start.
Stopping rules #
Gradient descent never stops by itself. Common rules:
- Gradient norm: stop when .
- Small change: stop when (relative change) or when is small.
- Budget: stop after a maximum number of steps (or time). In deep learning this is the usual rule, combined with a validation loss.
Why the gradient norm is the most direct test. A minimizer of a differentiable function must have , so measures how far is from satisfying this condition. It does not need , which you usually do not know. A small change of or only says that progress is slow, and progress can be slow far from the minimum: with a tiny step, or on a flat plateau, or along the floor of a narrow valley. For example, on with from , one step changes by only 0.2%. A relative-change rule with stops at once, while the gradient norm is 10.
The gradient norm has a limit too: on a very flat function it can be small far from the minimizer. Lesson 02 shows that for a -strongly convex , , so a small gradient does guarantee a small gap when is not tiny. Always also keep a maximum number of steps.
You run gradient descent with a step that is much too small. Which stopping rule is most likely to stop it far from the minimizer?
With a tiny step, changes very little per step everywhere, so a change-based rule fires at once. The gradient norm does not depend on the step size: it is small only near a stationary point.
Answers to section 1. (1) , so : it converges, and the sign changes every step. (2) No. At the factor for is : jumps between and forever, and gradient descent no longer converges. (3) Neither. The gradient is perpendicular to the contour line. In a narrow valley this means it points mostly across the valley, up the wall, and not toward the minimum. The descent direction points mostly down to the valley floor.
4. Worked example #
Run gradient descent by hand on from . The minimizer is with , and . The gradient is , so and .
(a) Step ().
The steep coordinate is solved in one step (). The flat coordinate shrinks by per step: , . After that, only the slow factor is left.
(b) Step (close to the limit 0.2).
Then . Next, and
changed sign twice (factor ): the zig-zag. shrinks by per step.
(c) Step (above the limit). and . The loss went up. The factor for is , so grows by 10% each step: , .
How many steps? The error shrinks at least by the slower factor per step, so a reduction by needs about steps:
| factors , | steps for | ||
|---|---|---|---|
| 0.01 | 0.99, 0.9 | 0.99 | about 1,370 |
| 0.1 | 0.9, 0 | 0.9 | 131 |
| 0.18 | 0.82, | 0.82 | 70 |
| , | 69 | ||
| 0.2 | 0.8, | 1 | never |
The code in section 5 counts the steps exactly (it gets 1,364 for , because it starts from , not from a point on the slow axis).
Click the chart or move the slider to pick . The blue curve is the loss after 50 steps, , for every step size, from the same start . It is flat for tiny , has its lowest point near the best step (grey dashed line), and then rises sharply at the stability limit (yellow line). The small contour plot shows the chosen run. Switch : the cliff moves with , and the good region gets narrower as grows.
5. In code #
NumPy checks the worked example and counts the steps.
import numpy as np
lam = np.array([1.0, 10.0]) # f(x) = 1/2 (x1^2 + 10 x2^2), minimizer x* = 0
f = lambda x: 0.5 * np.sum(lam * x**2)
grad = lambda x: lam * x
def gd(x0, eta, steps):
xs = [np.array(x0, dtype=float)]
for _ in range(steps):
xs.append(xs[-1] - eta * grad(xs[-1]))
return np.array(xs)
x0 = [2.0, 1.0]
for eta in (0.1, 0.18, 0.21):
xs = gd(x0, eta, 2)
print(eta, xs[1].round(4), xs[2].round(4), [round(float(f(x)), 4) for x in xs])
# 0.1 [1.8 0. ] [1.62 0. ] [7.0, 1.62, 1.3122]
# 0.18 [ 1.64 -0.8 ] [1.3448 0.64 ] [7.0, 4.5448, 2.9522]
# 0.21 [ 1.58 -1.1 ] [1.2482 1.21 ] [7.0, 7.2982, 8.0995]
def steps_to(eta, tol=1e-6, kmax=5000):
"""Steps until ||x_k|| <= tol * ||x_0||, or None if that never happens."""
x = np.array(x0); n0 = np.linalg.norm(x)
for k in range(kmax):
if np.linalg.norm(x) <= tol * n0:
return k
if np.linalg.norm(x) > 1e6: # diverged
return None
x = x - eta * grad(x)
return None
print([steps_to(eta) for eta in (0.01, 0.1, 0.18, 2 / 11, 0.2, 0.21)])
# [1364, 131, 70, 69, None, None]
print(2 / lam.max(), abs(1 - 0.2 * lam)) # stability limit and the two factors at eta = 0.2
# 0.2 [0.8 1. ]
The notebook adds a gradient check by finite differences, the four 1D regimes, a numerical search for the largest stable step, and gradient descent on a real regression dataset.
6. Where it shows up #
- Training neural networks. Every training step of SGD, momentum or Adam is a gradient step on the loss, with a gradient from backpropagation (calculus 06). The learning rate is usually the most important hyperparameter to tune.
- Divergence and loss spikes. Near a minimum, the loss behaves like a quadratic whose largest curvature is the largest Hessian eigenvalue. A step above about makes the loss oscillate and grow, as in the worked example (c). Lessons 07 and 11 connect this to warmup and to the "edge of stability".
- Linear and logistic regression. Their losses are convex, so gradient descent reaches the global minimum. Unscaled features (one in metres, one in millimetres) make a narrow valley and slow gradient descent down; standardizing them is the standard fix (lesson 02).
- ML for science. Gradient-based optimization fits physical models to data: the parameters of an ODE model, the initial state in weather data assimilation (4D-Var), or the material model in full-waveform inversion. The gradient comes from automatic differentiation or an adjoint method, and the same step-size questions appear.
7. Common mistakes #
- Drawing the gradient along the valley. The gradient is perpendicular to the contour line. In a narrow valley it points mostly across the valley, not toward the minimum.
- "A larger learning rate is always faster." Only up to . Close to the limit the steep direction zig-zags, and above it gradient descent diverges.
- " means divergence." Between 1 and 2 the iterates overshoot but still converge. Divergence starts at .
- "The loss went up once, so the step is too large." On a quadratic with a stable step, decreases every step. But with noisy minibatch gradients (lesson 05) or on nonconvex losses, single increases are normal; look at the trend.
- Stopping on a small change of the loss alone. With a small step or on a plateau, the change is small far from the minimum. Check the gradient norm and keep a step budget.
- "Gradient descent finds the global minimum." Only for convex functions (lesson 02). On a nonconvex loss it finds a stationary point that depends on the start.
8. Check yourself #
- . Which step sizes make gradient descent converge from every start? Which step
reaches the minimum in one step?
Answer
, so and . It converges for . The step gives factor 0: one step. - Compute one gradient-descent step with on from .
Answer
at . The step gives . The value goes from to . - At the point of the level set , give a vector perpendicular to the level
set and a vector tangent to it.
Answer
With , is perpendicular. A tangent vector is perpendicular to it, for example or : . - On , what is the largest stable step, the best fixed step, and the
factor per step with the best step?
Answer
Largest stable: . Best: . Factor: , so about steps for a reduction by . - Gradient descent converges to a point . Must be a minimizer?
Answer
No. If is continuous, is a stationary point, . It can be a saddle point, for example on the double well when the start has . For a convex , every stationary point is a global minimizer (lesson 02).
Write the gradient-descent update.
, where is the learning rate (step size).
Why is the steepest descent direction?
For a unit vector , the slope is by Cauchy–Schwarz, with equality only for .
Why is the gradient perpendicular to the level set?
Along a curve inside , is constant, so : the gradient is perpendicular to every tangent direction.
Gradient descent on : give .
.
For which step sizes does gradient descent converge on ?
. For the iterates oscillate around 0 but still converge.
On , what is the largest stable step and the best fixed step?
Stable for . Best fixed step , with factor per step.
What causes the zig-zag of gradient descent in a narrow valley?
The step must be small enough for the steepest direction; there the factor is close to , so the iterate jumps between the walls, while the flat direction shrinks slowly.
Why is the gradient norm a better stopping test than a small change in ?
is the condition a minimizer must satisfy, and it does not depend on the step size. A small change in only means slow progress, which can happen far from the minimum.
Gradient descent converges to , and is continuous. What do you know about ?
: it is a stationary point (a minimum, or possibly a saddle point).
9. Interview angle #
- "What happens if the learning rate is too large?" — The loss oscillates and then explodes. On a quadratic, the error along the steepest direction is multiplied by , which is below once .
- "Why does gradient descent zig-zag?" — The gradient is perpendicular to the contours, so in a narrow valley it points across the valley. The step that is safe for the steep wall is too small for the flat floor.
- "Why do we standardize features?" — It makes the contours of a linear model's loss rounder (a smaller condition number), so one learning rate fits all directions (lesson 02).
- "Does gradient descent find the global minimum?" — For a convex function, yes (with a suitable step). For a neural network it finds a stationary point, usually a good local minimum; the start and the step size matter.
10. Practice #
The notebook for this lesson runs in Colab. It has four exercises, each with a check cell and a folded solution:
- Write the gradients of and of least squares, and check them with a finite-difference gradient check.
- Write gradient descent that returns the whole path, and test the four 1D regimes.
- Find the largest stable step numerically by bisection and compare it with .
- Gradient descent with a gradient-norm stopping rule on the diabetes regression data, with raw and with standardized features: count the steps.
11. Watch and read #
- Gabriel Goh, Why Momentum Really Works, Distill (2017): the first section, "First Steps: Gradient Descent", has an interactive version of the narrow valley.
- Stanford CS231n, Optimization: stochastic gradient descent: loss surfaces of linear classifiers and the gradient check.
- Boyd and Vandenberghe, Convex Optimization, free PDF: §9.2 (descent methods) and §9.3 (gradient descent, with the stopping rule on ).
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.