09 / 10 Gradient descent
  1. ← Neural networks: foundations and mathematics
  2. 00 Foreword
  3. 01 The artificial neuron
  4. 02 Essential linear algebra
  5. 03 Activation functions
  6. 04 The perceptron
  7. 05 From the neuron to the multilayer network
  8. 06 Forward pass and loss functions
  9. 07 Derivatives and the chain rule
  10. 08 Backpropagation
  11. 09 Gradient descent
  12. 10 Regularisation and generalisation
Neural networks: foundations and mathematics · 09 / 10

Gradient descent

How to use the gradient to drive the score down, iteration after iteration.

In chapter 8, backpropagation handed us, in a single backward pass, the slope of the score with respect to every weight of the network. We hold the full compass. But a compass never moved anyone: knowing where to descend is not descending.

The question of this chapter is therefore very concrete: how do we turn this gradient into a step, and how long should that step be? Too short, and we never arrive. Too long, and we leap over the valley, and may even end up higher than where we started. We will see that this intuition can be proven, and that it yields a numerical rule.

Act 1: the hiker in the fog

Picture yourself in the mountains, caught in thick fog. You want to reach the valley, but you cannot see two metres ahead. Only one piece of information is within reach: the slope of the ground under your feet. The sensible strategy is obvious. You feel which way the terrain drops most steeply, you take a step that way, and you start again.

That is exactly what gradient descent does, already announced in chapter 4. Chapter 7 established that the gradient ∇L\nabla L points towards the steepest rise of the score. To go down, we therefore step in the opposite direction, −∇L-\nabla L. The update rule reads:

w  ←  w−η ∇L(w).w \;\leftarrow\; w - \eta\,\nabla L(w).

It reads: the new weight vector is the old one, minus the gradient of the score at that point, multiplied by a small positive number η\eta. This number is the learning rate from chapter 4. It sets the length of the step. Weight by weight, the same rule is written

wj  ←  wj−η ∂L∂wj,w_j \;\leftarrow\; w_j - \eta\,\frac{\partial L}{\partial w_j},

and backpropagation supplies precisely each of these partial derivatives. One descent step is therefore: a forward pass, a backward pass, then this subtraction on every weight. We repeat, and that is all.

You have already met a rule of this form. The perceptron rule, in chapter 4, was w←w+η y xw \leftarrow w + \eta\,y\,x. Same structure, a weight corrected by a step proportional to η\eta. The difference runs deep: the perceptron corrected by projection, with no slope, whereas here every correction is dictated by the derivative of the score. That is what makes it possible to train a network with differentiable activations, hidden layer included.

Act 2: the right dose of η\eta, proven on a parabola

To understand the role of η\eta with nothing hidden, let us take the simplest score that has a dip: a parabola with a single weight,

L(w)=a w2,a>0.L(w) = a\,w^2, \qquad a > 0.

Its minimum is at w=0w = 0, and its derivative is L′(w)=2a wL'(w) = 2a\,w. The number aa measures the curvature: the larger it is, the narrower and steeper the bowl.

One descent step. We apply the rule:

wt+1=wt−η⋅2a wt.w_{t+1} = w_t - \eta \cdot 2a\,w_t.

We factor out wtw_t:

wt+1=(1−2ηa) wt.w_{t+1} = (1 - 2\eta a)\,w_t.

This line says it all. At each step, the weight is multiplied by the same number r=1−2ηar = 1 - 2\eta a. After tt steps, it is therefore

wt=rt w0.w_t = r^t\,w_0.

This is a geometric sequence, and you already know how it behaves: it tends to 00 if and only if ∣r∣<1|r| < 1. We translate this condition into a condition on η\eta. The inequality −1<1−2ηa<1-1 < 1 - 2\eta a < 1 is equivalent to 0<2ηa<20 < 2\eta a < 2, that is,

0<η<1a.0 < \eta < \frac{1}{a}.

The sign of rr refines the behaviour. We get five regimes, all exact:

  • η<12a\eta < \frac{1}{2a}: 0<r<10 < r < 1. The weight glides towards 00 without ever changing sign. A well-behaved descent, and the slower the smaller η\eta is.
  • η=12a\eta = \frac{1}{2a}: r=0r = 0. The first step lands exactly at the bottom. This is the ideal step for this bowl.
  • 12a<η<1a\frac{1}{2a} < \eta < \frac{1}{a}: −1<r<0-1 < r < 0. The weight changes sign at every step: it jumps from one slope to the other, but each jump is shorter. It oscillates, and still converges.
  • η=1a\eta = \frac{1}{a}: r=−1r = -1. The weight bounces forever between w0w_0 and −w0-w_0.
  • η>1a\eta > \frac{1}{a}: r<−1r < -1. Each jump is longer than the previous one. The score blows up: the descent diverges.

Above all, keep the lesson that runs deep: the threshold depends on the curvature aa. A narrow bowl demands a small step. The same η\eta can be cautious on one score and catastrophic on another.

Set η\eta in the lab and take steps. Start around 0.10.1, then cross 0.50.5, then 11.

Gradient descent lab

Iteration : 0
Weight w = 2
Loss = 4
Regime : converges smoothly
Regime : converges smoothly

Three things to watch as you play:

  • Between 0.50.5 and 11, the trajectory zigzags from one slope to the other, but each bounce is lower than the previous one. Oscillating is not diverging.
  • At exactly η=0.5\eta = 0.5, a single step is enough. On a real score with millions of weights, this perfect step does not exist, because the curvature changes from one direction to another.
  • Beyond 11, the score climbs at every step. A learning rate that is too large does not slow learning down: it destroys it.

Act 3: the descent lemma, for any smooth score

The parabola is a textbook case. A real network has a tormented score, with no simple formula. Can we still guarantee that a step lowers the score? Yes, on one condition: the slope must not change too abruptly.

Back to the hiker. If they know the slope of the terrain cannot change all at once, that the relief has no cliff or hidden step, then the slope measured under their feet stays reliable over a certain distance. They can take a step with confidence, provided that step is no longer than the zone where the slope stays reliable.

Definition. A differentiable function ff is called β-smooth β-smooth function A differentiable function whose slope never changes faster than a constant β: the gap between two slopes is at most β times the gap between the two points. This regularity guarantees that a gradient descent step of length at most 1/β always decreases the function (descent lemma). Source: Nesterov, 2004 , with β>0\beta > 0, if its derivative never varies faster than β\beta:

∣f′(u)−f′(v)∣  ≤  β ∣u−v∣for all u,v.|f'(u) - f'(v)| \;\le\; \beta\,|u - v| \quad \text{for all } u, v.

We write the constant β\beta and not LL, so as not to confuse it with the score. On the parabola a w2a\,w^2, we have ∣f′(u)−f′(v)∣=2a ∣u−v∣|f'(u) - f'(v)| = 2a\,|u - v|: it is β\beta-smooth with β=2a\beta = 2a.

Descent lemma. If ff is β\beta-smooth, then for all xx and yy,

f(y)  ≤  f(x)+f′(x) (y−x)+β2 (y−x)2.f(y) \;\le\; f(x) + f'(x)\,(y - x) + \frac{\beta}{2}\,(y - x)^2.

It reads: the function always stays below a parabola that touches its graph at xx, with the same slope. In other words, the tangent plus a curvature margin β\beta form a ceiling that the score can never break through.

Proof. We fix xx and study the gap between this ceiling and the function:

g(y)=f(x)+f′(x) (y−x)+β2 (y−x)2−f(y).g(y) = f(x) + f'(x)\,(y - x) + \frac{\beta}{2}\,(y - x)^2 - f(y).

We must show that g(y)≥0g(y) \ge 0 everywhere. First, at y=xy = x, all the terms vanish: g(x)=0g(x) = 0. Next, we differentiate with respect to yy:

g′(y)=f′(x)+β (y−x)−f′(y).g'(y) = f'(x) + \beta\,(y - x) - f'(y).

For y≥xy \ge x, smoothness gives f′(y)−f′(x)≤β (y−x)f'(y) - f'(x) \le \beta\,(y - x), hence g′(y)≥0g'(y) \ge 0: gg increases to the right of xx. For y≤xy \le x, it gives f′(x)−f′(y)≤β (x−y)f'(x) - f'(y) \le \beta\,(x - y), hence g′(y)≤0g'(y) \le 0: gg decreases to the left of xx. A function that decreases up to xx and then increases reaches its minimum at xx. This minimum equals g(x)=0g(x) = 0, so g(y)≥0g(y) \ge 0 for every yy. □

Consequence for a descent step. We apply the lemma to the step y=x−η f′(x)y = x - \eta\,f'(x). The gap y−xy - x equals −η f′(x)-\eta\,f'(x), so

f(y)  ≤  f(x)−η f′(x)2+β η22 f′(x)2.f(y) \;\le\; f(x) - \eta\,f'(x)^2 + \frac{\beta\,\eta^2}{2}\,f'(x)^2.

We group the last two terms:

f(y)  ≤  f(x)−η(1−β η2) f′(x)2.f(y) \;\le\; f(x) - \eta\Big(1 - \frac{\beta\,\eta}{2}\Big)\,f'(x)^2.

If η≤1β\eta \le \frac{1}{\beta}, the parenthesis is at least 12\frac{1}{2}, and we get the announced guarantee:

f(y)  ≤  f(x)−η2 f′(x)2.f(y) \;\le\; f(x) - \frac{\eta}{2}\,f'(x)^2.

It reads: with a step at most equal to 1/β1/\beta, each iteration lowers the score by at least half of η\eta times the square of the slope. As long as the slope is not zero, the score goes down, without exception.

Check the consistency with act 2. On the parabola, β=2a\beta = 2a, so the guarantee holds for η≤12a\eta \le \frac{1}{2a}: this is exactly the zone of well-behaved descent, with no oscillation. More generally, the parenthesis 1−βη/21 - \beta\eta/2 stays positive as long as η<2/β=1/a\eta < 2/\beta = 1/a: this is exactly the convergence threshold found by hand. The lemma recovers the parabola, and it applies to many other scores.

What the lemma guarantees, and what it does not. Add up the guarantee over TT steps. The terms L(wt)L(w_t) telescope, and since the score never goes below its lowest level L⋆L^\star (a squared error is never negative, so L⋆≥0L^\star \ge 0), what remains is

η2∑t=0T−1∥∇L(wt)∥2  ≤  L(w0)−L⋆.\frac{\eta}{2}\sum_{t=0}^{T-1}\|\nabla L(w_t)\|^2 \;\le\; L(w_0) - L^\star.

The right-hand side is a fixed number, whereas the sum on the left grows at every step. The gradients encountered must therefore become as small as we like: the descent ends up stopping at a point where the slope is zero. But be careful about what this result says. A zero slope is not necessarily the bottom of the valley. It can be a secondary dip, a pass, a flat spot. Act 5 will go through them.

Act 4: batch, mini-batch, stochastic

So far, we have acted as if the score were a single function. In reality, it is an average over the NN training examples:

L(w)=1N∑i=1Nℓi(w),L(w) = \frac{1}{N}\sum_{i=1}^{N} \ell_i(w),

where ℓi\ell_i is the score of example ii alone. Its gradient is the average of the individual gradients, and each one costs a forward pass and a backward pass. With N=60,000N = 60{,}000 images, a single descent step would therefore require 60,00060{,}000 backpropagations. This is full-batch gradient descent: exact, but terribly slow.

The idea that unlocks everything is not to wait until we have seen everything. We randomly draw a small batch of examples, a mini-batch Mini-batch A small random subset of the training set on which the gradient is computed to take one descent step. The resulting gradient is noisy but correct on average, and far cheaper than the gradient over the whole set. Typical sizes range from a few dozen to a few hundred examples. Source: Bottou, Curtis & Nocedal, 2018 BB of size mm, and we estimate the gradient on that batch alone:

gB=1m∑i∈B∇ℓi(w).g_B = \frac{1}{m}\sum_{i \in B} \nabla \ell_i(w).

This estimate is noisy: a batch of 100100 images never looks exactly like the whole dataset. But it is right on average. Let us check this in the extreme case m=1m = 1. If we draw example ii with probability 1N\frac{1}{N}, the average of ∇ℓi\nabla \ell_i over all possible draws is

∑i=1N1N ∇ℓi(w)=∇L(w).\sum_{i=1}^{N} \frac{1}{N}\,\nabla \ell_i(w) = \nabla L(w).

The same computation, carried out on each example of a randomly drawn batch, gives the same result for any mm. We say that gBg_B is an unbiased estimator of the gradient: it is wrong at every draw, but its errors cancel out. The case m=1m = 1 is called stochastic gradient descent Stochastic gradient descent A variant of gradient descent that estimates the gradient on a single randomly drawn example (or, by extension, on a mini-batch) instead of the whole set. The estimate is noisy but unbiased: averaged over draws, it equals the true gradient. Often abbreviated SGD. Source: Robbins & Monro, 1951 , and the idea of moving forward with noisy measurements goes back to Robbins and Monro (1951). In practice, we take batches of a few dozen to a few hundred examples: enough to smooth the noise, few enough to take many steps.

A full pass over the data, batch after batch, is called an epoch Epoch One complete pass over the whole training set, mini-batch after mini-batch. With N examples and batches of size m, an epoch contains N/m descent steps. Training a network is often measured in number of epochs. . With 60,00060{,}000 examples and batches of 100100, an epoch counts 600600 steps, where full batch makes only one. The noise even has an unexpected advantage: it shakes the trajectory, which can help it leave a flat spot or a pass (Bottou, Curtis and Nocedal, 2018).

VariantExamples per stepSteps per epoch (N=60,000N = 60{,}000)Gradient
Full batchNN11exact, costly
Mini-batchmm (e.g. 100100)N/m=600N/m = 600noisy, unbiased
Stochastic11N=60,000N = 60{,}000very noisy, unbiased

Act 5: the traps of the terrain

The lemma guarantees that we stop where the slope vanishes. Here are the places where that can happen without our being at the bottom.

Local minima. A local minimum Local minimum (optimisation) A point where a function is lower than everywhere in its immediate neighbourhood, without being its lowest value overall. The slope there is zero, so gradient descent may stop at it. A convex function has no local minimum other than its global one. Source: Boyd & Vandenberghe, 2004 is a dip lower than all its close neighbours, but higher than the true bottom. The hiker who falls into one sees only climbs around and stops. There is a family of scores without this trap: convex functions, shaped like a bowl with no bump. For a differentiable convex function, the tangent always stays below the curve (Boyd and Vandenberghe, 2004): f(y)≥f(x)+f′(x) (y−x)f(y) \ge f(x) + f'(x)\,(y - x), so a point where f′(x)=0f'(x) = 0 satisfies f(y)≥f(x)f(y) \ge f(x) for every yy: it is necessarily the global minimum. Unfortunately, the score of a network with a hidden layer is not convex in general.

Saddle points. A saddle point Saddle point A point where the gradient is zero but which is neither a minimum nor a maximum: the function rises in some directions and falls in others, like a mountain pass. Classic example: w₁² − w₂² at the origin. In high dimension they are argued to be far more common than local minima, and they slow gradient descent down. Source: Dauphin et al., 2014 is a pass: a minimum in some directions, a maximum in others. The typical example is L(w1,w2)=w12−w22L(w_1, w_2) = w_1^2 - w_2^2 at the origin. The gradient is zero there, yet the score still goes down as soon as we move along w2w_2. Dauphin and his co-authors (2014) argue, with arguments from statistical physics and experiments on networks, that in very high dimension the critical points with a high score are mostly passes, not local minima. The real danger is not getting trapped, it is slowing down for a long time around them.

Plateaus. On a flat spot, the slope is tiny without being zero, and the step η ∇L\eta\,\nabla L is tiny too. We advance at an ant’s pace. This is the cousin of the vanishing gradient from chapter 8: when sigmoids saturate, their derivatives are squashed and the score becomes flat.

Ravines. Take the score from chapter 7 again, in a more pronounced version: L=w12+10 w22L = w_1^2 + 10\,w_2^2. The bowl is ten times steeper along w2w_2 than along w1w_1. According to act 2, each direction has its own threshold: η<1\eta < 1 along w1w_1, but η<0.1\eta < 0.1 along w2w_2. With a single η\eta for everyone, we are stuck. Take it large and we zigzag from one wall to the other. Take it small and we crawl along the bottom. Switch the lab to ravine mode to see it.

Gradient descent lab

Iteration : 0
Position (x, y) = (2, 1)
Loss = 14
Behavior : zigzag
Behavior : zigzag
The ravine is steep in y and flat in x: the same η makes the path zigzag across the steep axis and crawl along the flat one.

Three things to watch as you play:

  • At η=0.09\eta = 0.09, the coordinate w2w_2 is multiplied by 1−2⋅0.09⋅10=−0.81 - 2 \cdot 0.09 \cdot 10 = -0.8 at every step: it changes sign, hence the zigzag. The coordinate w1w_1, for its part, is multiplied only by 0.820.82: it advances slowly.
  • Lower η\eta: the zigzag disappears, but progress along the bottom becomes endless.
  • Go above 0.10.1: the steep direction diverges, whereas the flat direction could have handled a step ten times larger. Chapter 12 will settle this conflict by giving each direction its own memory and its own scale.

Exercises

Grab something to write with. The solutions are deliberately detailed, line by line.

Exercise 1. In chapter 8, on the toy network, we found ∂L/∂w1(2)=−0.077\partial L / \partial w^{(2)}_1 = -0.077 for a weight equal to w1(2)=0.5w^{(2)}_1 = 0.5. Take one descent step with η=0.5\eta = 0.5. Does the weight increase or decrease, and why?

Exercise 2. On L(w)=w2L(w) = w^2, starting from w0=2w_0 = 2, compute w1w_1 and w2w_2 for η=0.1\eta = 0.1, then η=0.75\eta = 0.75, then η=1.1\eta = 1.1. Say each time whether the descent converges.

Exercise 3. For the score L(w)=3 w2L(w) = 3\,w^2, give the rate that reaches the minimum in a single step, then the largest rate for which the descent still converges.

Exercise 4. On L(w)=w2L(w) = w^2, we start from w=2w = 2 with η=0.25\eta = 0.25. What does the descent lemma guarantee about the drop in the score? Compare with the actual drop.

Exercise 5. A dataset contains N=60,000N = 60{,}000 examples. How many descent steps do we take per epoch with mini-batches of 100100 examples? And with mini-batches of 3232?

In one sentence

Gradient descent takes a step −η ∇L-\eta\,\nabla L at each iteration, and the descent lemma guarantees that the score goes down as long as the step stays below 1/β1/\beta, where β\beta measures how fast the slope can change.

Quiz

Quiz
  1. 1. What does a gradient descent step do?

  2. 2. On L(w) = a w², for which rates does the descent converge?

  3. 3. What does the descent lemma guarantee for a β-smooth score and η ≤ 1/β?

  4. 4. Why is a mini-batch gradient useful even though it is noisy?

  5. 5. Why does the descent zigzag in a ravine like L = w₁² + 10 w₂²?

Towards chapter 10

We now know how to drive the score down, step by step, with a proven guarantee. But which score are we lowering? The one on the training examples, and only that one. Yet what matters is performance on examples the network has never seen. Think of a curve that must pass through ten measurement points. A degree-nine polynomial can go through all of them exactly, with a zero score, and oscillate wildly between them. It has learned the points by heart, not the trend. A large enough network can do exactly the same thing, and gradient descent will help it with all its might. Chapter 10 teaches how to descend without learning by heart: that is regularisation.

Sources

  • Cauchy, A. (1847). « Méthode générale pour la résolution des systèmes d’équations simultanées. » Comptes rendus hebdomadaires des séances de l’Académie des sciences 25, 536-538. Reprinted in the Œuvres complètes, series 1, volume 10, 399-402.
  • Robbins, H. & Monro, S. (1951). “A Stochastic Approximation Method.” The Annals of Mathematical Statistics 22(3), 400-407. DOI 10.1214/aoms/1177729586
  • Nesterov, Y. (2004). Introductory Lectures on Convex Optimization: A Basic Course. Kluwer. Lemma 1.2.3 (descent lemma).
  • Boyd, S. & Vandenberghe, L. (2004). Convex Optimization. Cambridge University Press. Section 3.1.3 (first-order condition). https://web.stanford.edu/~boyd/cvxbook/
  • Dauphin, Y. N., Pascanu, R., Gulcehre, C., Cho, K., Ganguli, S. & Bengio, Y. (2014). “Identifying and attacking the saddle point problem in high-dimensional non-convex optimization.” NeurIPS 2014. arXiv:1406.2572
  • Bottou, L., Curtis, F. E. & Nocedal, J. (2018). “Optimization Methods for Large-Scale Machine Learning.” SIAM Review 60(2), 223-311. DOI 10.1137/16M1080173
  • Goodfellow, I., Bengio, Y. & Courville, A. (2016). Deep Learning. MIT Press. Sections 4.3 (gradient-based optimization) and 8.1 to 8.3 (learning, challenges, SGD). https://www.deeplearningbook.org