Gradient descent and its difficulties¶
Many problems in science and engineering end in the same task: find the minimum of a function of many variables. Fitting a model to data is one, and so are training a neural network, finding the state of lowest energy of a physical system, and solving the large systems of linear equations that come from a differential equation. The simplest method for all of them is one loop: compute the gradient, take a small step against it, repeat. The loop is three lines of code, and using it well is a craft. This post goes through the method and then through its difficulties one at a time: the learning rate, narrow valleys, local minima, saddle points and noisy gradients. Each difficulty gets a small experiment and the remedy that practice has settled on.
The examples lean towards machine learning, where the function is the loss of a model and the variables are its weights \(\mathbf{w}\). Part 2 of the machine learning notes used gradient descent to fit a line and listed its challenges in a table, and here each row of that table gets a section. Nothing in the method is specific to learning, though, and one section solves a diffusion equation with it. The derivatives used below, the gradient and the Hessian, are the subject of the post on derivatives of vectors and matrices.
The idea¶
We want the minimum of a function \(J(\mathbf{w})\) of many variables. For a few special functions there is a formula. For all the others we search. The search can only look at the function near the place where it currently stands, and the gradient \(\nabla J(\mathbf{w})\) says which way is up from there.
Why exactly the gradient? Move a small distance \(\epsilon\) in a direction \(\mathbf{u}\) of unit length. To first order the function changes by
The product \(\nabla J^\top\mathbf{u}\) is smallest when \(\mathbf{u}\) points exactly opposite to \(\nabla J\). So among all directions, the negative gradient is the one in which the function falls fastest. Gradient descent, which is also called steepest descent, takes a step in that direction and looks again:
The learning rate \(\eta > 0\) sets the length of the step. The step is \(\eta\) times the gradient, so it is long where the slope is steep and it shrinks by itself as the slope flattens out near a minimum.
The first-order formula is also the warning. It is only an approximation, good for small \(\epsilon\). The gradient promises a descent for a short step and promises nothing about a long one. Everything that follows is about how far that promise can be pushed.
Difficulty 1: the learning rate¶
Take the simplest loss there is, \(J(\theta) = \tfrac{a}{2}\theta^2\), a parabola with curvature \(a\). Its derivative is \(a\theta\), so one step of gradient descent is
Every step multiplies \(\theta\) by the same factor, and the factor decides everything:
| \(\eta a\) | Factor \(1 - \eta a\) | Behaviour |
|---|---|---|
| between 0 and 1 | between 0 and 1 | steady approach from one side, slow when \(\eta a\) is small |
| exactly 1 | 0 | arrives in one step |
| between 1 and 2 | between \(-1\) and 0 | jumps across the minimum every step, but lands closer each time |
| exactly 2 | \(-1\) | jumps between two points for ever |
| above 2 | below \(-1\) | every jump lands further away: divergence |
So the right learning rate is set by the curvature: it must be below \(2/a\), and \(1/a\) is ideal. A sharply curved loss needs small steps and a flat one allows large steps. The trouble is that the curvature is a second derivative, and gradient descent only ever computes first derivatives. It is asked to choose a step length without the one piece of information that determines it.
A guarantee for general functions¶
The same statement holds beyond parabolas. Suppose the gradient of \(J\) cannot change faster than a constant \(L\) allows, \(\lVert\nabla J(\mathbf{a}) - \nabla J(\mathbf{b})\rVert \le L\lVert\mathbf{a} - \mathbf{b}\rVert\). Such a function is called \(L\)-smooth, and \(L\) is a bound on its curvature in every direction. Then \(J\) lies below a parabola of curvature \(L\) fitted at any point:
Put in a gradient step, \(\mathbf{b} = \mathbf{a} - \eta\nabla J(\mathbf{a})\):
For any \(\eta\) below \(2/L\) the bracket is positive, and the loss goes down at every step, whatever the function looks like otherwise. With \(\eta = 1/L\) the decrease is at least \(\tfrac{1}{2L}\lVert\nabla J\rVert^2\). This is called the descent lemma, and it is the reason gradient descent works at all: with a small enough step, it cannot go up. What it does not say is how fast the method arrives, or where.
Choosing it in practice¶
Nobody knows \(L\) for a real model. Three approaches are common.
- Search on a logarithmic grid. Try \(\eta = 1, 0.3, 0.1, 0.03, \dots\) for a few hundred steps each and keep the largest value for which the loss falls steadily. Only the order of magnitude matters.
- Backtracking line search. Start each step with an optimistic \(\eta\). If the loss has not fallen by a fair share of what the gradient promised, that is, if \(J(\mathbf{w} - \eta\mathbf{g}) > J(\mathbf{w}) - c\,\eta\lVert\mathbf{g}\rVert^2\) with \(\mathbf{g} = \nabla J(\mathbf{w})\) and a small constant such as \(c = 10^{-4}\), halve \(\eta\) and try again. The test is called the Armijo condition. This finds a safe step automatically at the price of a few extra evaluations of the loss, and it is standard where the loss is cheap and exact. The step is long far from the minimum and shortens by itself close to it. The Wolfe conditions add a second test, on the slope at the new point, which rules out steps that are too short.
- Schedules. Start with a large rate and reduce it during training, in steps, as \(1/k\), or along a cosine. Large steps cover distance early, and small steps settle the result late.
Difficulty 2: narrow valleys¶
In more than one dimension a function has a curvature in every direction, and they are not equal. Near a minimum \(\mathbf{w}^*\) every smooth function looks like a quadratic bowl,
where \(\mathbf{H}\) is the Hessian, the matrix of second derivatives. Its eigenvectors are the axes of the bowl and its eigenvalues \(\lambda_i\) are the curvatures along them. Gradient descent treats each axis like the one-dimensional example: along axis \(i\) the error is multiplied by \(1 - \eta\lambda_i\) at every step.
There is only one \(\eta\) for all the axes. The steepest axis, with \(\lambda_{\max}\), forces \(\eta < 2/\lambda_{\max}\). With such a small step the flattest axis, with \(\lambda_{\min}\), has a factor of nearly one and barely moves. The quantity that measures the conflict is the condition number
The best compromise is \(\eta = 2/(\lambda_{\min} + \lambda_{\max})\). It makes the two extreme axes equally slow, and the error then shrinks by
per step. To reduce the error by a factor \(1/\varepsilon\) takes about \(\tfrac{\kappa}{2}\ln(1/\varepsilon)\) steps. The number of steps grows in proportion to the condition number.
The picture shows where the steps go. On a round bowl the negative gradient points straight at the minimum. On a stretched one it points mostly across the valley, towards the nearest wall, and only slightly along it. The path bounces between the walls and creeps along the floor. A condition number of 25 is mild. For a real model it can be many thousands.
There are three ways out, in order of increasing ambition.
Change the coordinates. If the valley is narrow only because the variables have different units, rescale them. In linear regression, standardising the features can turn a condition number of 16 into exactly 1, as part 2 shows. This is called preconditioning, and when it applies it is the cheapest cure by far.
Remember the past. That is momentum, and it comes next.
Measure the curvature. That is Newton's method, further down.
Momentum¶
Look at the zigzag again. Across the valley the gradient changes sign at every step. Along the valley it always has the same sign. Averaging the gradients of the last few steps would cancel the first and keep the second. Momentum does this with a running sum, the velocity \(\mathbf{v}\):
The physical picture is a heavy ball rolling on the surface with friction. \(\beta\) between 0 and 1 says how much of the old velocity survives a step, and 0.9 is the usual default. With \(\beta = 0\) this is plain gradient descent. In a direction where the gradient is constant, the velocity builds up to \(1/(1 - \beta)\) times a single step, ten times for \(\beta = 0.9\).
The picture can be made exact. Write gradient descent as \((\mathbf{w}_{k+1} - \mathbf{w}_k)/\eta = -\nabla J(\mathbf{w}_k)\) and read the learning rate as a time step. In the limit of small steps this becomes a differential equation, the gradient flow:
It describes a particle without mass in a thick fluid, whose velocity is at every moment equal to the force \(-\nabla J\) that acts on it. Gradient descent is Euler's method for this equation. Its limit on the learning rate is the stability limit of Euler's method, and a narrow valley is what numerical analysis calls a stiff equation.
Now give the particle a mass \(m\) and keep a friction \(\gamma\). Newton's second law says
A particle with mass does not stop when the force vanishes. It keeps moving, and that carries it through flat regions and along the floor of a valley. Without the friction it would never settle: it would swing around the minimum for ever. Discretise the equation with a time step \(\Delta t\), updating the velocity first and then the position with the new velocity, and call \(\mathbf{v}\) the distance covered in one step. The result is
This is the momentum rule, with
So the learning rate is small for a heavy ball, and \(\beta\) measures the friction. \(\beta = 0\) is friction so strong that nothing of the old velocity survives. \(\beta = 1\) is no friction at all, and the ball never comes to rest. One more thing follows from the picture. A ball that is placed at rest exactly on a stationary point, a saddle for instance, feels no force and stays there. Momentum only helps once the ball is moving.
For a quadratic bowl the best \(\eta\) and \(\beta\) can be worked out, and with them the error shrinks per step by about
instead of \((\kappa - 1)/(\kappa + 1)\). The number of steps grows with the square root of the condition number. For \(\kappa = 100\) that is the difference between a factor of 0.98 and one of 0.82 per step.
| Method | Settings | Steps to come within \(10^{-6}\) |
|---|---|---|
| Gradient descent | best fixed \(\eta\) = 0.0198 | 761 |
| Momentum | best \(\eta\) = 0.0331, \(\beta\) = 0.669 | 92 |
| Nesterov's method | \(\eta\) = 0.01, \(\beta\) = 0.818 | 172 |
| Adam | \(\eta\) = 0.1, default averages | 259 |
| Conjugate gradient | none | 2 |
| Newton's method | none | 1 |
Two remarks on the table. The settings of the first three methods use the exact curvatures of the valley, which are known here and never in practice. The last two rows need no settings at all. The conjugate gradient method and Newton's method each have a section further down. And the left panel shows that momentum is not gentle: it overshoots the walls by a wide margin before it settles. With too much momentum, or too large a rate, it diverges like any other method.
Nesterov's variant changes one detail. It evaluates the gradient not where the ball is but where the velocity is about to carry it:
Looking ahead lets it brake before it overshoots. Its importance is theoretical as much as practical: for convex functions in general, and not only for quadratics, it reaches the best rate that any method using only gradients can have.
Difficulty 3: local minima¶
Everything so far assumed a single valley. A convex function has one, and gradient descent with a suitable learning rate finds its floor from any start. A non-convex function can have many valleys of different depths. Gradient descent is a local method. It goes downhill from where it starts and stops at the first floor it meets. Which one that is depends on the starting point and on nothing else.
In two dimensions this can be watched as it happens. The animation below starts gradient descent from 121 points on a surface with three minima of different depth. Every start slides into the valley it happens to stand in. 52 of them end in the minimum on the left, 37 in the deepest one at the bottom, and 32 in the shallowest one on the right. The set of starts that lead to one minimum is called its basin of attraction. Fewer than a third of the starts find the global minimum.
The remedies are modest. Start from several points, random ones or a grid as in the animation, and keep the best result. Use momentum, which rolls through shallow dips. Use the noise of stochastic gradients, which shakes the iterate out of narrow ones. None of these is a guarantee. For the loss of a neural network, which has millions of parameters, nobody finds the global minimum or can even check whether a given minimum is global. What is found and reported is a good local minimum, and much of the competition between optimisers is about finding better ones, faster.
This sounds worse than it is. For large networks, experience and some theory both suggest that most of the minima that training reaches are about equally good, and that the real obstacle in many dimensions is a different one.
Difficulty 4: saddle points and plateaus¶
A point where the gradient is zero is called a stationary point. It does not have to be a minimum. The Hessian tells the cases apart by the signs of its eigenvalues. All positive: the surface curves up in every direction, a minimum. All negative: a maximum. Some of each: a saddle point, a minimum along some directions and a maximum along others, like a mountain pass.
In one dimension a stationary point is almost always a minimum or a maximum. In a million dimensions, a minimum needs a million eigenvalues to be positive at once, while a saddle needs only one to be negative. Saddle points are therefore far more numerous than minima in high-dimensional losses.
A small example has everything in it:
It has two minima, at \((\pm 1, 0)\) with \(f = -\tfrac14\), and a saddle point at the origin with \(f = 0\), where the Hessian has the eigenvalues \(-1\) and \(1\).
Two things are worth taking from the figure. First, gradient descent does not usually get stuck in a saddle point for ever. Only the starts exactly on the line \(x = 0\) end there, and any deviation grows. Second, it grows slowly. Near the saddle the gradient is nearly zero, so the steps are tiny. The distance from the line is multiplied by \(1 + \eta = 1.1\) at each step, so a start that is a hundred times closer needs \(\ln 100 / \ln 1.1 \approx 48\) steps more. In the right panel the fall begins near step 44, 92 and 141. A long stretch in which the loss does not move is not proof of a minimum.
A plateau is the same difficulty without the saddle: a region where the surface is almost flat, the gradient is tiny, and progress nearly stops. The flat tails of a sigmoid function produce such regions in neural networks. Momentum helps in both cases, because the velocity carries the iterate across, and so does the noise of stochastic gradients, which supplies the deviation that a saddle needs. The adaptive methods below help on plateaus for another reason: they lengthen the step where the gradient is small.
Difficulty 5: the cost and the noise of a gradient¶
In machine learning the loss is an average over \(N\) training examples,
One exact gradient reads the whole data set. With a million examples, that is a million small gradients for a single step. Most of the work is redundant, because the examples resemble each other and a small sample already points in roughly the right direction.
Stochastic gradient descent, SGD, uses that. At each step it draws a random mini-batch \(B\) of examples and steps along the average of their gradients:
The mini-batch gradient is an unbiased estimate of the true one: right on average, wrong in detail. Its error falls as \(1/\sqrt{|B|}\), so a batch a hundred times larger is only ten times more accurate, and that is why small batches pay. One pass through the data, called an epoch, gives \(N/|B|\) steps instead of one. The extreme case of one example per step is called online SGD.
| Examples per step | Learning rate | After 1 pass | Average over passes 21 to 30 |
|---|---|---|---|
| all 200 | 0.1 | 4.5 | 0.020 |
| 16 | 0.1 | 0.28 | 0.00022 |
| 1 | 0.1 | 0.0013 | 0.015 |
| 1 | 0.1, decaying | 0.0014 | 0.0000018 |
The numbers are the loss minus its minimum. After one pass through the data, the method with one example per step has taken 200 steps and is three thousand times closer than the full-batch method, which has taken one. That is the case for SGD. The third row is the case against a constant learning rate: after 30 passes it is no better than after one, because every noisy step pushes the iterate away from the minimum as far as the previous one pulled it in. The iterate ends up in a cloud around the minimum whose size grows with \(\eta\) and shrinks with the batch size.
The cure is in the last row. Let the learning rate fall, here as \(\eta_k = 0.1/(1 + 0.01k)\). The classical conditions for convergence, due to Robbins and Monro, are
The first says that the steps must add up to any distance, so that the minimum can be reached from anywhere. The second says that they must shrink fast enough for the noise to average out. A rate proportional to \(1/k\) satisfies both.
The noise is not only a nuisance. It is what moves SGD off saddle points and out of narrow local minima, as the two previous sections said, and for neural networks it is widely believed to steer training towards wide, flat minima, which tend to predict better on new data.
Adaptive methods¶
Momentum deals with narrow valleys by remembering gradients. A second family gives every weight its own learning rate, set from the size of the gradients that weight has seen.
AdaGrad accumulates the squares of all past gradients, coordinate by coordinate, and divides the step by the square root of the sum:
with \(\mathbf{g}_k = \nabla J(\mathbf{w}_k)\) and all operations taken element by element. Weights with large gradients get short steps and weights with small or rare gradients get long ones. This is a crude diagonal preconditioner, built from first derivatives alone. Its weakness is that the sum only grows, so the steps shrink for ever and training stalls.
RMSProp replaces the sum by a running average, \(\mathbf{s}_{k+1} = \rho\,\mathbf{s}_k + (1 - \rho)\,\mathbf{g}_k^2\), which forgets old gradients and keeps the steps alive.
Adam combines RMSProp with momentum. It keeps a running average of the gradient, \(\mathbf{m}\), and one of its square, \(\mathbf{s}\):
The hats correct a bias: both averages start at zero and would be too small during the first steps. The defaults \(\beta_1 = 0.9\), \(\beta_2 = 0.999\) and \(\epsilon = 10^{-8}\) are rarely changed, and \(\eta = 10^{-3}\) is the usual starting point for neural networks.
The ratio \(\hat{\mathbf{m}}/\sqrt{\hat{\mathbf{s}}}\) is roughly the gradient divided by its own typical size, so each weight moves by about \(\eta\) per step whether its gradient is of the order of \(10^{-6}\) or \(10^{6}\). That is why Adam works with little tuning on badly scaled problems, and why it crosses plateaus. In the momentum figure, Adam reaches the minimum in 259 steps without having been told anything about the valley, against 761 for gradient descent with its best rate. The same property is its weakness: close to the minimum it still takes steps of about \(\eta\), overshoots and comes back, which is the scalloped curve in that figure. A decaying learning rate is used with Adam for the same reason as with SGD.
Using the curvature: Newton's method¶
Every difficulty of the learning rate comes from not knowing the curvature. Newton's method computes it. Fit a quadratic to the function at the current point, using the gradient and the Hessian, and jump to the minimum of that quadratic:
There is no learning rate. Each direction is divided by its own curvature, so a narrow valley is as easy as a round bowl. For a quadratic the fit is exact and one step reaches the minimum, which is the last row of the table above. For other functions the method converges extremely fast once it is close.
It is not the default for three reasons. The Hessian has \(D^2\) entries and solving with it costs of the order of \(D^3\) operations per step, which is out of reach beyond some thousands of parameters. Far from a minimum the quadratic fit can be poor and the step wild, so a line search is needed. And Newton's method looks for a point where the gradient is zero, of any kind: on a non-convex function it is attracted to saddle points and maxima as readily as to minima.
Quasi-Newton methods keep most of the benefit at a fraction of the cost. BFGS builds an approximation to the inverse Hessian from the changes of the gradient between steps, and L-BFGS stores only the last few of those changes, so that memory and time per step stay proportional to \(D\). With a line search, L-BFGS is the standard choice for smooth problems of moderate size where the full gradient is affordable, such as logistic regression. For the large, noisy problems of deep learning, SGD with momentum and Adam remain the tools.
Conjugate gradient: when the function is a quadratic¶
One special case has a method of its own, because it is everywhere in scientific computing. Take a quadratic function,
with a symmetric matrix \(\mathbf{A}\) whose eigenvalues are all positive. Its gradient is \(\nabla J = \mathbf{A}\mathbf{x} - \mathbf{b}\), so its minimum is the point where
Minimising this function and solving this system of linear equations are the same problem. So gradient descent is also a way to solve linear systems, and it brings its difficulties with it. The Hessian is \(\mathbf{A}\) itself, and the number of steps grows with the condition number of \(\mathbf{A}\). The negative gradient has a name here, the residual \(\mathbf{r} = \mathbf{b} - \mathbf{A}\mathbf{x}\): what is still missing from the equation.
A quadratic has one advantage. The best step along any direction \(\mathbf{p}\) can be worked out exactly, with no learning rate to choose:
Gradient descent with this best step at every iteration still zigzags, as the left panel below shows. Every step is the best possible along its own direction, and the next step undoes part of it. The length of the step was never the real problem. The direction is.
The conjugate gradient method changes the direction. It does not step along the residual. It steps along the residual plus a share of the previous direction:
With this \(\beta\) every new direction is conjugate to all the earlier ones, which means \(\mathbf{p}_i^\top\mathbf{A}\,\mathbf{p}_j = 0\). Conjugate directions are the ones that would be perpendicular if the bowl were stretched until it was round. The consequence is that a step along a new direction spoils nothing of what the earlier steps achieved. In \(D\) dimensions there are only \(D\) such directions, so the method arrives after at most \(D\) steps: two steps for a bowl in two dimensions, whatever its condition number.
The whole algorithm, from a first guess \(\mathbf{x}_0\) with \(\mathbf{r}_0 = \mathbf{b} - \mathbf{A}\mathbf{x}_0\) and \(\mathbf{p}_0 = \mathbf{r}_0\):
This is momentum again. The previous direction is the previous step divided by its length, so the update can be written as a gradient step plus a multiple of the last step, exactly the form of the heavy ball. The difference is that the two numbers, \(\alpha_k\) and \(\beta_k\), are not tuned. They are computed afresh at every step from the residuals. In the worst case the error shrinks by the factor \((\sqrt\kappa - 1)/(\sqrt\kappa + 1)\) per step, the rate of momentum with its best settings, and the method gets there without being told the curvatures.
Where such systems come from¶
A typical source is a partial differential equation. Take the diffusion equation for a field \(u(x, y, t)\), such as a temperature,
On a grid with spacing \(h\), the second derivatives become differences between a point and its four neighbours. An implicit time step, which is stable for any step length \(\Delta t\), evaluates those differences at the new time. The new value at every grid point then depends on the new values of its neighbours:
This is one linear equation for each grid point, \(\mathbf{A}\mathbf{u}^{n+1} = \mathbf{u}^{n}\), to be solved at every time step. The matrix is symmetric, all its eigenvalues are positive, and each row has only five entries that are not zero. A grid of \(1000 \times 1000\) points gives a million unknowns. Stored as a full table, \(\mathbf{A}\) would have \(10^{12}\) entries, and inverting it is out of the question. The conjugate gradient method never needs the table. It only needs the product of \(\mathbf{A}\) with a vector, which is five multiplications per grid point.
The experiment in the right panel is one such time step on a grid of \(31 \times 31\) points, a square of side 10 with \(D = 1\) and \(u = 0\) on the boundary, started from a warm spot. The table gives the number of steps until the residual has fallen by a factor of \(10^{8}\):
| Time step \(\Delta t\) | Condition number | Gradient descent, best fixed rate | Gradient descent, best step every time | Conjugate gradient |
|---|---|---|---|---|
| 0.1 | 8.0 | 72 | 43 | 18 |
| 1 | 61 | 542 | 489 | 57 |
| 10 | 242 | 2155 | 2109 | 80 |
A longer time step makes the system harder, because it moves the matrix further from the identity. The work of gradient descent grows in proportion to the condition number. That of the conjugate gradient method grows far more slowly, and it stays well below the 841 steps that the theory guarantees.
I used this method in an older project, diffusion-equation: a Fortran code for the two-dimensional diffusion equation with a diffusion coefficient that varies from place to place. It takes implicit time steps and solves the linear system of each step by conjugate gradient. The repository also has notes on the discretisation and on the algorithm.
In code the method is as short as momentum:
import numpy as np
def conjugate_gradient(A, b, tol=1e-8, max_steps=1000):
"""Solve A x = b for a symmetric A with positive eigenvalues."""
x = np.zeros_like(b)
r = b - A @ x # the residual, which is minus the gradient
p = r.copy() # the first direction is the gradient direction
rho = r @ r
for k in range(1, max_steps + 1):
q = A @ p # the only product with A in the step
alpha = rho / (p @ q) # the best step along p
x = x + alpha * p
r = r - alpha * q
rho_new = r @ r
if np.sqrt(rho_new) < tol * np.linalg.norm(b):
return x, k
p = r + (rho_new / rho) * p
rho = rho_new
return x, max_steps
A = np.diag([1.0, 100.0]) # the valley of the momentum figure
x, steps = conjugate_gradient(A, np.array([4.0, 40.0]))
print(x, steps) # [4. 0.4] 2
Beyond quadratics¶
Three remarks place the method among the others.
- Preconditioning. For a badly conditioned system the method is combined with a preconditioner, a rough approximation of \(\mathbf{A}\) that is easy to invert. This is the idea of rescaling the variables again, applied inside the iteration.
- Functions that are not quadratic. The nonlinear conjugate gradient methods of Fletcher and Reeves and of Polak and Ribière keep the rule for the direction, put the negative gradient in the place of the residual, and find the step by a line search. They need no Hessian and only a few vectors of memory.
- Inside Newton's method. A Newton step is the solution of the linear system \(\mathbf{H}\,\boldsymbol{\delta} = -\nabla J\). For a large problem that system can be solved approximately by a few conjugate gradient steps, which need products of the Hessian with a vector and never the Hessian itself.
The method is not used to train neural networks, for a reason that the section on noise explains. Conjugacy is a delicate property. It depends on exact gradients and exact steps, and the noise of a mini-batch destroys it.
Optimisation and root finding¶
Finding the minimum of a function and finding the zero of a function are not the same problem, but they are closely linked, and each can be turned into the other.
From optimisation to root finding. At a minimum of a smooth function the gradient is zero, so minimising \(J(\mathbf{w})\) leads to the equation \(\nabla J(\mathbf{w}) = \mathbf{0}\). That is a root-finding problem: \(D\) equations in \(D\) unknowns. The methods correspond as well. Write \(\mathbf{g}(\mathbf{w})\) for the function whose zero is wanted, here \(\mathbf{g} = \nabla J\):
| Optimisation | Root finding for \(\mathbf{g}(\mathbf{w}) = \mathbf{0}\) |
|---|---|
| gradient descent, \(\mathbf{w} \leftarrow \mathbf{w} - \eta\,\nabla J\) | fixed-point iteration, \(\mathbf{w} \leftarrow \mathbf{w} - \eta\,\mathbf{g}\) |
| conjugate gradient on the quadratic \(\tfrac12\mathbf{x}^\top\mathbf{A}\mathbf{x} - \mathbf{b}^\top\mathbf{x}\) | the same method, as a solver for the linear equations \(\mathbf{A}\mathbf{x} = \mathbf{b}\), that is, for \(\mathbf{g}(\mathbf{x}) = \mathbf{A}\mathbf{x} - \mathbf{b} = \mathbf{0}\) |
| Newton's method, \(\mathbf{w} \leftarrow \mathbf{w} - \mathbf{H}^{-1}\nabla J\) | the Newton–Raphson method, with the Jacobian of \(\mathbf{g}\) in the place of \(\mathbf{H}\) |
| quasi-Newton methods such as BFGS | the secant method and Broyden's method |
The conjugate gradient method is neither Newton's method nor a quasi-Newton method. It uses only gradients, it never builds a matrix, and it keeps a few vectors, so by its cost it belongs with momentum. It is related to the quasi-Newton family all the same. On a quadratic, BFGS that starts with no knowledge of the curvature and takes the best step along each direction makes exactly the steps of conjugate gradient. A quasi-Newton method can be seen as conjugate gradient that spends memory on remembering the curvature, which is what keeps it working when the function is not a quadratic.
From root finding to optimisation. To solve \(\mathbf{g}(\mathbf{x}) = \mathbf{0}\), minimise \(\tfrac12\lVert\mathbf{g}(\mathbf{x})\rVert^2\). This function is never negative, and it is zero exactly at the roots.
Three things keep the two problems apart.
- A zero of the gradient is not always a minimum. The gradient also vanishes at maxima and at saddle points. A root finder cannot tell these apart, and that is why Newton's method is attracted to saddle points. An optimiser has one more piece of information, the value of \(J\) itself, and it can check that every step went downhill.
- Not every system of equations comes from a function to minimise. A function \(\mathbf{g}\) is the gradient of some \(J\) only if its Jacobian is symmetric. The linear case shows it: solving \(\mathbf{A}\mathbf{x} = \mathbf{b}\) is the minimisation of \(\tfrac12\mathbf{x}^\top\mathbf{A}\mathbf{x} - \mathbf{b}^\top\mathbf{x}\) only when \(\mathbf{A}\) is symmetric with positive eigenvalues, the condition of the previous section.
- Squaring has a price. The function \(\tfrac12\lVert\mathbf{g}\rVert^2\) can have local minima that are not roots, and its condition number is the square of that of the original problem, so descent on it is slow.
Gradient descent is therefore an optimisation method that ends at a root of the gradient. What it adds to a root finder is the guarantee, for a small enough step, that it only ever moves downhill.
When to stop, and how to tell that something is wrong¶
Gradient descent never announces that it has arrived. Three stopping rules are in use. Stop when the norm of the gradient is below a tolerance. Stop when the loss has changed by less than a tolerance over the last steps. Or, in machine learning, stop when the error on validation data has stopped improving, which is called early stopping and also acts against overfitting.
The curve of the loss against the step number is the main instrument for diagnosis:
| The loss | Likely cause | Try |
|---|---|---|
grows, or becomes nan |
learning rate too large | divide \(\eta\) by 10 |
| oscillates without falling | learning rate close to the limit | reduce \(\eta\), add momentum |
| falls, but very slowly and smoothly | learning rate too small, or a narrow valley | raise \(\eta\), rescale the inputs, add momentum |
| is flat for a long time, then drops | a saddle point or a plateau | wait, add momentum, use an adaptive method |
| falls quickly, then jitters around a level | noise floor of SGD | reduce \(\eta\) over time, enlarge the batch |
| does not fall at all from the first step | a wrong gradient | check the gradient numerically |
The last row is more common than one would like. A derivative worked out by hand, or a sign error in the code, gives a "gradient" that does not point uphill. The check is to compare it with a finite difference, as described in the post on derivatives.
The optimisers in code¶
All of them are a few lines of NumPy. Each takes a function that returns the gradient:
import numpy as np
def gradient_descent(grad, w0, eta, n_steps):
w = np.array(w0, dtype=float)
for _ in range(n_steps):
w = w - eta * grad(w)
return w
def momentum(grad, w0, eta, beta, n_steps):
w = np.array(w0, dtype=float)
v = np.zeros_like(w)
for _ in range(n_steps):
v = beta * v - eta * grad(w)
w = w + v
return w
def adam(grad, w0, eta, n_steps, beta1=0.9, beta2=0.999, eps=1e-8):
w = np.array(w0, dtype=float)
m = np.zeros_like(w)
s = np.zeros_like(w)
for k in range(1, n_steps + 1):
g = grad(w)
m = beta1 * m + (1 - beta1) * g
s = beta2 * s + (1 - beta2) * g**2
m_hat = m / (1 - beta1**k) # both averages start at zero: correct the bias
s_hat = s / (1 - beta2**k)
w = w - eta * m_hat / (np.sqrt(s_hat) + eps)
return w
# The valley of the figure: curvatures 1 and 100.
kappa = 100.0
h = np.array([1.0, kappa])
grad = lambda w: h * w
start = [4.0, 0.4]
root = np.sqrt(kappa)
eta_m, beta_m = 4 / (1 + root) ** 2, ((root - 1) / (root + 1)) ** 2 # best for this valley
# Distance to the minimum after 100 steps.
print(np.linalg.norm(gradient_descent(grad, start, 2 / (1 + kappa), 100))) # 0.54
print(np.linalg.norm(momentum(grad, start, eta_m, beta_m, 100))) # 2.0e-07
print(np.linalg.norm(adam(grad, start, 0.1, 100))) # 0.021
The versions that draw the figures, which also return every iterate, are in scripts/ml_gradient_descent.py in this site's repository.
Summary¶
| Method | What it adds | What it cures | What it costs |
|---|---|---|---|
| Gradient descent | nothing | one gradient per step, one number to tune | |
| Line search, schedules | a step length that changes | a badly chosen learning rate | extra evaluations, or more numbers to tune |
| Rescaling the variables | better coordinates | narrow valleys caused by units | nothing |
| Momentum, Nesterov | memory of past gradients | narrow valleys, shallow dips, plateaus | one more vector, one more number to tune |
| Mini-batches, SGD | a sample instead of the data set | the cost of a gradient, saddle points | noise, which needs a decaying rate |
| AdaGrad, RMSProp, Adam | a learning rate per weight | bad scaling, plateaus | two more vectors, oscillation near the minimum |
| Newton, quasi-Newton | the curvature | the learning rate itself, any narrow valley | \(D^2\) memory and \(D^3\) time, or an approximation |
| Conjugate gradient | directions that do not undo each other | narrow valleys, with nothing to tune | a quadratic function, or a line search, and exact gradients |
One idea runs through the whole table. The gradient says in which direction to go and not how far, and every method after the first is a way of estimating the missing distance: from trial steps, from the history of the gradients, or from the second derivatives themselves.
Further reading¶
Short articles:
- The Predictive Science Lab's course on scientific machine learning has chapters on gradient descent, with a line search, on momentum, derived from the motion of a particle with friction, and on stochastic gradient descent. All three come with code in JAX.
- G. Goh, "Why momentum really works", Distill (2017). An interactive explanation of the quadratic analysis used here. doi:10.23915/distill.00006
- S. Ruder, "An overview of gradient descent optimization algorithms" (2016). All the adaptive methods side by side. arXiv:1609.04747
Books and surveys:
- S. Boyd and L. Vandenberghe, Convex Optimization (Cambridge University Press, 2004), chapter 9. Gradient descent, line search and Newton's method with proofs, free to download.
- J. Nocedal and S. J. Wright, Numerical Optimization (2nd edition, Springer, 2006). The reference for line search and quasi-Newton methods.
- J. R. Shewchuk, An Introduction to the Conjugate Gradient Method Without the Agonizing Pain (1994). The standard gentle derivation, with pictures of the conjugate directions.
- L. Bottou, F. E. Curtis and J. Nocedal, "Optimization methods for large-scale machine learning", SIAM Review 60, 223–311 (2018). Why stochastic methods win when data are large. doi:10.1137/16M1080173
Original papers:
- M. R. Hestenes and E. Stiefel, "Methods of conjugate gradients for solving linear systems", Journal of Research of the National Bureau of Standards 49, 409–436 (1952). doi:10.6028/jres.049.044
- H. Robbins and S. Monro, "A stochastic approximation method", Annals of Mathematical Statistics 22, 400–407 (1951). doi:10.1214/aoms/1177729586
- B. T. Polyak, "Some methods of speeding up the convergence of iteration methods", USSR Computational Mathematics and Mathematical Physics 4, 1–17 (1964). The heavy ball. doi:10.1016/0041-5553(64)90137-5
- I. Sutskever, J. Martens, G. Dahl and G. Hinton, "On the importance of initialization and momentum in deep learning", Proceedings of the 30th International Conference on Machine Learning, PMLR 28(3), 1139–1147 (2013). Momentum and Nesterov's variant in the form used here. proceedings.mlr.press/v28/sutskever13
- D. P. Kingma and J. Ba, "Adam: a method for stochastic optimization" (2014). arXiv:1412.6980
- Y. N. Dauphin and others, "Identifying and attacking the saddle point problem in high-dimensional non-convex optimization" (2014). arXiv:1406.2572