Gradient descent and the curse of conditioning

Gradient descent and the curse of conditioning
Page content

Gradient descent is a loop of a few lines and it always goes downhill. On most problems worth solving it is also painfully slow, and the reason has a name: the condition number.

This is the first post in a series on nonlinear optimisation (NLP, nonlinear programming). A long time ago I wrote about BFGS and went straight to the clever method without showing what it cures. This time I start with the disease :).

Momentum, line search, Newton, conjugate gradient and L-BFGS are all fixes for something on this page, so I want to be exact about what goes wrong.

The method is from 1847. In a three page note, Méthode générale pour la résolution des systèmes d’équations simultanées (the link is Richard Pulskamp’s English translation), Cauchy turns a system of equations into a single function $u$ that is never negative and then walks against its partial derivatives, because “it will suffice to make the function u decrease indefinitely, until it vanishes”. He had orbits in mind: six unknown elements and more equations than unknowns. In C it looks like this:

for (int k = 0; k < iterations; k++) {
	gradient(x, g);                 // g = grad f(x)
	for (int i = 0; i < n; i++)
		x[i] -= step * g[i];
}

Two questions: how big can step be, and how fast does this converge? On a quadratic both have exact answers.

One eigenvalue at a time

Take

$$ f(x) = \frac{1}{2} x^T A x - b^T x $$

with $A$ symmetric and positive definite. The gradient is $Ax - b$, and the minimum $x^\star$ is where it vanishes. Call the error $e_k = x_k - x^\star$. One step of size $\alpha$ does this to it:

$$ e_{k+1} = e_k - \alpha A e_k = (I - \alpha A) e_k $$

Now write the error in the basis of eigenvectors of $A$. In that basis $I - \alpha A$ is diagonal, so the components do not talk to each other. The component along the eigenvector with eigenvalue $\lambda_i$ gets multiplied by $1 - \alpha \lambda_i$ at every iteration, and that is all that ever happens to it. Gradient descent on a quadratic is $n$ separate geometric sequences.

Everything else follows from this.

Stability. Every factor has to be below 1 in absolute value. The largest eigenvalue is the dangerous one: $|1 - \alpha \lambda_{\max}| < 1$ means $\alpha < 2 / \lambda_{\max}$. Past that limit the steepest direction is multiplied by something below $-1$, so it flips sign and grows at every step.

The best fixed step. The speed is set by the worst factor, and the worst factor is always at one of the two ends of the spectrum. A small step barely moves the flat direction ($\lambda_{\min}$). A large one makes the steep direction ($\lambda_{\max}$) overshoot. The best compromise is the step where the two are equally bad, $1 - \alpha \lambda_{\min} = -(1 - \alpha \lambda_{\max})$, and that gives

$$ \alpha^\star = \frac{2}{\lambda_{\min} + \lambda_{\max}}, \quad \rho = \frac{\lambda_{\max} - \lambda_{\min}}{\lambda_{\max} + \lambda_{\min}} = \frac{\kappa - 1}{\kappa + 1}, \quad \kappa = \frac{\lambda_{\max}}{\lambda_{\min}} $$

$\kappa$ is the condition number of $A$ and $\rho$ is the factor by which the error shrinks per iteration, at best. Look at what $\rho$ does not depend on: the dimension, the starting point, the size of the eigenvalues. Only their ratio matters.

One more correct decimal digit costs $\ln 10 / (-\ln \rho)$ iterations, which is about $1.15 \kappa$ when $\kappa$ is large:

$\kappa$ $\rho$ iterations per digit
10 0.818 11.5
1000 0.998 1151
$10^6$ 0.999998 1151293

A million is not an exotic number. Take a perfectly round bowl in two variables and measure one variable in metres and the other in millimetres: the two curvatures now differ by a factor of $10^6$, and six digits of accuracy cost seven million iterations.

The zig-zag is the same statement

In two dimensions you can see all of this. The level sets of a quadratic are ellipses, their axes are the eigenvectors, and the lengths of the axes go like $1 / \sqrt{\lambda_i}$. So the valley is $\sqrt{\kappa}$ times longer than it is wide. I scaled the demo so that $\lambda_{\max} = 1$ and $\lambda_{\min} = 1 / \kappa$, which keeps the stability limit at a step of 2 whatever $\kappa$ is.

Click or drag on the picture to move the start. Raise the condition number, press "Best step", then push the step past 2.

The gradient is perpendicular to the level set, and in a narrow valley that means it points at the opposite wall, not at the minimum. So the path bounces from wall to wall while it drifts slowly along the floor.

The bounce is the factor $1 - \alpha \lambda_{\max}$ being negative: the steep coordinate changes sign at every step. The drift is the factor $1 - \alpha \lambda_{\min}$ being just under 1. The green line in the demo prints both. At the best step they are equal and opposite, $-0.818$ and $0.818$ for $\kappa = 10$, so the zig-zag and the crawl die at the same rate. The picture contains nothing more than those two numbers:

// in valley coordinates the two components never mix
flat  *= 1 - step * lambdaMin;
steep *= 1 - step * lambdaMax;

Past a step of 2 the steep factor drops below $-1$ and every bounce is bigger than the one before. And look where the best step is: $2 \kappa / (\kappa + 1)$, which is 1.98 for $\kappa = 100$. The best step sits a hair below the cliff. In practice you do not know $\lambda_{\min}$ anyway, so you take something safe like $1 / \lambda_{\max}$, the factor becomes $1 - 1 / \kappa$ and you pay about twice the iterations in the table.

The rotation slider turns the whole picture and changes nothing else. Gradient descent does not care how the valley is oriented relative to the axes. Keep that in mind, some of the cheap fixes do care.

The curse in one plot

Here is the error against the iteration number for three condition numbers at once. The problem has 30 dimensions, with eigenvalues spread evenly (on a log scale) between $1 / \kappa$ and 1. The vertical axis is logarithmic, so a geometric sequence is a straight line, and the dashed lines are the predicted $\rho^k$.

Stretch the iteration axis until the slowest curve starts to move, then try a step 2% above the best one.

Each solid curve starts with a quick drop. Those are the directions in the middle of the spectrum, their factors are small and they are gone in a few iterations. After that only the two extreme directions are left and the curve runs parallel to its dashed line for as long as you care to wait. This is why gradient descent looks great for the first few iterations and then seems to stop.

With a step 2% too big the curve for $\kappa = 10$ still goes down, while the other two turn around and climb. The margin between the best step and divergence is a fraction $1 / \kappa$ of the step. A badly conditioned problem is slow, and it also leaves you no room for error on the step.

Exact line search does not rescue you

The obvious reaction: a fixed step is dumb, pick the best possible step at every iteration. Cauchy says so in the same note: minimise along the ray, which is an equation in a single unknown. On a quadratic that equation has a closed form solution, $\alpha_k = \frac{g_k^T g_k}{g_k^T A g_k}$ with $g_k$ the current gradient. The old literature calls this the optimum gradient method.

Tick “Exact line search” in the first demo. It can no longer diverge, and with the sliders at their defaults it clearly beats the fixed step: the error after 30 iterations goes from $2.4 \cdot 10^{-3}$ to $1.5 \cdot 10^{-8}$. Now press “Worst start”. The zig-zag is back, with exact right angles this time, and the error after 30 iterations is $2.4 \cdot 10^{-3}$ again. In two dimensions what the line search gains depends on where you start, and on the dashed lines it gains nothing.

That worst case is a theorem. With exact line search on a quadratic, $f(x_{k+1}) - f(x^\star) \le \rho^2 (f(x_k) - f(x^\star))$, with the very same $\rho$ (Theorem 3.3 in Nocedal and Wright; the standard proof uses the Kantorovich inequality). The natural error here is $\sqrt{f - f^\star}$, so that is again a factor $\rho$ per step. The bound is attained on the dashed lines, where the eigen-coordinates of the start are proportional to $(1 / \lambda_{\min}, 1 / \lambda_{\max})$. The line search then picks exactly $2 / (\lambda_{\min} + \lambda_{\max})$ at every iteration and the error shrinks by exactly $\rho$. You can check it by hand in three lines.

In more dimensions you could hope to be lucky most of the time. Tick the box in the second demo: the curves fall with almost the same slope as before. Forsythe and Motzkin saw why in experiments: the error ends up as a combination of just the two eigenvectors of the smallest and the largest eigenvalue, alternating with period 2. They proved it for three dimensions, and Akaike (1959) proved it in general, by rephrasing the iteration as a transformation of probability distributions. I know the story from Afanasjew, Eiermann, Ernst and Güttel (2008), who sketch his proof. So whatever the dimension, steepest descent ends up zig-zagging in one plane, the plane of the first demo. The slope it settles on depends on the start and is never worse than $\rho$. In my plot it saves about 1% of the iterations.

So choosing the length of the step better, even perfectly, bought almost nothing. The direction is the problem.

Away from quadratics

Near a minimum every smooth function looks like a quadratic whose matrix is the Hessian $H$ at that minimum. So close to the solution everything above applies with $A = H$, and the condition number of the Hessian decides how fast you finish. Far from the minimum the Hessian changes from place to place, the stability limit and the local $\kappa$ change with it, and it may not even be positive definite.

The standard cruel example is the function Rosenbrock (1960) introduced in “An automatic method for finding the greatest or least value of a function”, a paper about a search method of his own:

$$ f(x, y) = (1 - x)^2 + 100 (y - x^2)^2 $$

The minimum is at $(1, 1)$, at the bottom of a valley that follows the parabola $y = x^2$. The Hessian there has eigenvalues of about 1001.6 and 0.4, so $\kappa \approx 2508$: almost 2900 iterations per digit with the best possible step. On top of that the valley is curved, so the flat direction keeps turning.

Changing the variables

The condition number is not a property of the problem. It is a property of the problem in the coordinates you happened to write it in. Substitute $x = P y$ and run gradient descent on $y$: the Hessian becomes $P^T A P$, and written back in the original variables a step is

$$ x_{k+1} = x_k - \alpha M \nabla f(x_k), \quad M = P P^T $$

This is preconditioning. A good $P$ stretches the coordinates until the valley is round.

The cheapest $P$ is diagonal: rescale every variable on its own. That fixes the metres and millimetres problem completely. It can only fix valleys that are lined up with the axes though, and this is where the rotation slider comes back. At the minimum of Rosenbrock’s function, scaling each variable by the square root of its diagonal Hessian entry only takes $\kappa$ from 2508 to about 1602, because that valley runs diagonally.

The perfect choice is $M = A^{-1}$. Then $P^T A P = I$, $\kappa = 1$, the level sets are circles and a step of 1 lands on the minimum in one iteration. In the original variables that step is $x_{k+1} = x_k - H^{-1} \nabla f(x_k)$, which is Newton’s method. Newton is gradient descent with the perfect preconditioner, recomputed at every point.

Click anywhere to move the start. Drag "Iterations" from 1 all the way up and watch which path gets to the minimum.

Gradient descent (the cream path) drops to the valley floor in a handful of iterations and then crawls. With a step of 0.001 and the start at $(-1.2, 1)$ it is still at $f = 0.45$ after 1000 iterations, and it needs about 21000 to get $f$ below $10^{-8}$. Raise the step above 0.002 and it never settles, because $2 / \lambda_{\max}$ at the minimum is 0.002.

Newton (green) arrives in 21 iterations from the same start. The Newton path here has two safeguards, a shifted Hessian where it is not positive definite and a step that is halved until $f$ goes down. Without them it gets there in 6, after a detour through a point where $f$ is above 1400.

Cauchy saw this coming. His note ends with the advice to switch to Newton’s method once the values are close, to get the remaining digits quickly. The paper that introduced gradient descent already says not to finish with it :).

What comes next

Newton is not free. It needs second derivatives, a linear solve of size $n$ at every iteration, and safeguards far from the minimum. The rest of this series is about getting part of its effect for less:

  • Momentum keeps the gradient but remembers the previous step, and replaces $\kappa$ with $\sqrt{\kappa}$ in the rate.
  • Line search is what you need when the curvature, and with it the safe step, changes from place to place.
  • Newton’s method properly, with the safeguards I waved at above.
  • Conjugate gradient picks directions that do not undo each other’s work.
  • L-BFGS builds an approximation of $H^{-1}$ out of the gradients it has already seen.

Further reading