Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Gradient descent and nonlinear conjugate gradients

ProblemMinimise a smooth function of many variables using its gradient
Devised byGradient descent: Augustin-Louis Cauchy (1847). Conjugate gradients: Magnus Hestenes and Eduard Stiefel (1952, for linear systems); for nonlinear functions, Roger Fletcher and Colin Reeves (1964), Elijah Polak and Gerard Ribière (1969), Boris Polyak (1969), Yu-Hong Dai and Ya-Xiang Yuan (1999)
AccuracyGradient descent: linear convergence, with rate at best for condition number . Conjugate gradients: about , and exact in steps on a quadratic with exact line searches
CostOne gradient per iteration (gradient descent), or one line search (conjugate gradients); memory
Read firstBackground: what a minimum looks like, One-dimensional minimisation and line searches
APIGradientDescent, NonlinearConjugateGradient, ConjugateGradientBeta

Overview

The gradient points in the direction in which increases fastest, so is the direction of steepest descent. Gradient descent simply steps along it, again and again. It is the simplest optimisation method there is, and in its stochastic form it trains almost every neural network. But it is slow on ill-conditioned problems, where changes much faster in some directions than in others: the steps zigzag across a narrow valley instead of running along it.

Conjugate gradient methods remove the zigzag by choosing each new direction to be conjugate to the previous ones, so that progress made along one direction is not undone along the next. They cost little more than gradient descent per iteration, store only a few vectors, and converge far faster. They are the method of choice for very large smooth problems when memory is short.

Where it is used

When there are millions of variables, only gradients are affordable.

  • Training neural networks. Variants of gradient descent (momentum, Adam) fit the parameters of deep networks.
  • Large-scale inverse problems. Conjugate gradients on tomography, seismic imaging and data assimilation in weather forecasting.
  • Linear systems. Linear conjugate gradients, the quadratic special case, is the standard iterative solver for symmetric positive definite systems.

History

Augustin-Louis Cauchy proposed the method of steepest descent in 1847, to solve the systems of equations arising in astronomy by minimising a sum of squares. For a century it was the only general method, and its slow convergence was analysed by Leonid Kantorovich (1945), who bounded its rate in terms of the condition number.

Magnus Hestenes and Eduard Stiefel, working independently and then together at the Institute for Numerical Analysis in Los Angeles, published the conjugate gradient method for symmetric positive definite linear systems in 1952; for the quadratic it is a minimiser that terminates in at most steps. Roger Fletcher and Colin Reeves (1964) extended it to general functions by replacing the exact formulas with line searches. Elijah Polak and Gerard Ribière, and independently Boris Polyak (1969), proposed a variant that restarts itself when it stops making progress, and Michael Powell (1984) and Jean Charles Gilbert and Jorge Nocedal (1992) analysed its convergence and introduced the safeguarded “PR+” version used here.

The idea

Gradient descent

The gradient points in the direction in which increases fastest, so its negative is the direction of steepest descent. Gradient descent takes a step in that direction, of a length set by a learning rate (or step size) :

Everything depends on . The behaviour is clearest on the simplest function with a minimum, a quadratic.

Analysis on a quadratic. Let with symmetric positive definite. Its minimum is at , its gradient is , and its Hessian (the matrix of second derivatives) is . The iteration becomes

Write in the basis of eigenvectors of , with eigenvalues . Along eigenvector the matrix acts as multiplication by , so each step multiplies that component of by . The components evolve independently:

  • component shrinks if and only if , that is ;
  • all components shrink if and only if , the condition for the largest eigenvalue;
  • the slowest component sets the overall rate, .

A small is safe but leaves close to 1, so the component along the smallest eigenvalue barely moves. A large handles that component well but makes close to , so the component along the largest eigenvalue overshoots and oscillates. The best fixed step balances the two extremes, , which gives and the rate

The ratio of the largest to the smallest curvature is the condition number. When is large the rate is about , very close to 1, and the number of iterations needed to reduce the error by a fixed factor is proportional to . For , with and , the best step is :

Figure 5.3. Gradient descent with various steps.

A step of 0.205 exceeds and diverges; a step of 0.02 is safe but ten times slower than 0.18.

General functions. For a general smooth , the role of the largest eigenvalue is played by a bound on the curvature, the Lipschitz constant of . A second-order Taylor bound gives

so any step is guaranteed to decrease , by at least . Choosing well requires knowing , which is why practical methods choose the step by a line search instead.

The zigzag. Even with the best step, the path is inefficient. The gradient is perpendicular to the contour line through the current point. In an elongated valley the contours are long thin ellipses, and the perpendicular to them points mostly across the valley, not along it towards the minimum. The iterates bounce from side to side:

Figure 5.4. Gradient descent and conjugate gradients.

Nonlinear conjugate gradients

The zigzag happens because each step partly undoes the work of earlier steps: after minimising along one direction, the next step moves off that minimum again. Conjugate gradient methods choose directions that do not interfere with each other. Each new search direction is built from the new gradient and the previous direction,

starting from . The step comes from a line search. The scalar adds a memory of the previous direction, and the art is in choosing it.

Conjugacy. On a quadratic with Hessian , two directions are called conjugate if . Here is why that is the right notion of non-interference. Suppose we have minimised along , so the slope along it, , is zero. Moving a distance along another direction changes the gradient by , and so changes the slope along by . If the directions are conjugate this is zero: the point is still at the minimum along . The minimisation along each direction never needs repeating. An -dimensional space has room for only mutually conjugate directions, so the minimum of an -dimensional quadratic is reached in at most steps: two steps in the figure.

Choosing . For a quadratic with exact line searches, is chosen to make the directions conjugate, and remarkably this needs only the current and previous gradients. Write and . Several formulas give the same value on a quadratic but behave differently on general functions:

nameproperty
Fletcher-Reevesglobal convergence theory, but can stall with tiny steps
Polak-Ribière (PR+)restarts itself when progress stalls; the usual default
Hestenes-Stiefelthe original linear formula
Dai-Yuandescent with any Wolfe line search

General functions. On a non-quadratic function the Hessian changes from point to point and conjugacy holds only approximately. The method is therefore restarted with a steepest descent step () every iterations, or whenever fails to be a descent direction. Near a minimum is nearly quadratic, and the convergence rate approaches that of linear conjugate gradients, about per iteration. The number of iterations for a fixed reduction is proportional to instead of : for , of the order of a hundred iterations instead of ten thousand.

Algorithm

Gradient descent. Input: , its gradient, a starting point and a learning rate . Repeat:

  1. evaluate the gradient ;
  2. set ; if bounds are set, move any coordinate that has left the box back to the nearest bound (projection);
  3. evaluate , and stop when it differs from the previous value by less than the tolerance, or when the iteration limit is reached.

Each iteration costs one gradient and one function evaluation.

Nonlinear conjugate gradients. Input: , its gradient and a starting point .

  1. Evaluate and set .
  2. Line search. Find along by a strong Wolfe line search with . The first trial step is scaled from the step accepted at the previous iteration, since successive steps tend to be of similar size. Set .
  3. Test. Evaluate . If its largest component in magnitude is below the tolerance, stop.
  4. New direction. Compute by the chosen formula and set . Use instead (a restart with the steepest descent direction) every iterations, or if would not be a descent direction. Go to 2.

Besides the line search, an iteration costs only a few vector operations, , and the method stores four vectors. That is what makes it usable for very large .

Implementation

            let mut new_parameters: Vec<f64> = result.parameters.iter().zip(gradient.iter()).map(|(p, g)| p - self.learning_rate * g).collect();
            if let Some(bounds) = bounds.as_ref() {
                new_parameters = new_parameters.iter().enumerate().map(|(i, p)| {
                    let (lower_bound, upper_bound) = bounds[i];
                    p.max(lower_bound).min(upper_bound)
                }).collect();
            }
            let beta = match self.beta {
                ConjugateGradientBeta::FletcherReeves => new_gg / gg,
                ConjugateGradientBeta::PolakRibierePlus => (dot(&p.gradient, &y) / gg).max(0.0),
                ConjugateGradientBeta::HestenesStiefel => dot(&p.gradient, &y) / dy,
                ConjugateGradientBeta::DaiYuan => new_gg / dy,
            };
            (x, f, g) = (p.x, p.value, p.gradient);
            since_restart += 1;
            let beta = if since_restart >= n || !beta.is_finite() {
                since_restart = 0;
                0.0
            } else {
                beta
            };
            d.iter_mut().zip(&g).for_each(|(di, gi)| *di = -gi + beta * *di);
  • GradientDescent stops when one step changes by less than the tolerance (default ). That test does not look at the gradient: with a small learning rate, changes little per step even far from the minimum, so check the result. With bounds, each step is projected onto the box.
  • NonlinearConjugateGradient stops on the gradient norm (default ) and does not support bounds.
  • On the Rosenbrock function and an ill-conditioned quadratic the methods compare as follows (more methods in the next entry): gradient descent needs over 14 000 iterations from , conjugate gradients about 36.

In practice

//! Gradient descent and nonlinear conjugate gradients.
//!
//! Run with `cargo run -p lib_jsl_optimization --example optimization_gradient`.

use lib_jsl_optimization::conjugate_gradient::{ConjugateGradientBeta, NonlinearConjugateGradient};
use lib_jsl_optimization::gradient_descent::GradientDescent;
use lib_jsl_optimization::optimization_traits::{GradientBasedMinimizationEngine, GradientFunction, MinimizationControls, ObjectiveFunction};

/// Least squares for a straight line through four points: f(a, b) = Σ (a + b xᵢ − yᵢ)².
struct LineFit;
const DATA: [(f64, f64); 4] = [(0.0, 1.1), (1.0, 2.9), (2.0, 5.2), (3.0, 6.8)];
impl ObjectiveFunction for LineFit {
    fn evaluate(&self, p: &[f64]) -> f64 {
        DATA.iter().map(|(x, y)| (p[0] + p[1] * x - y).powi(2)).sum()
    }
}
impl GradientFunction for LineFit {
    fn evaluate(&self, p: &[f64]) -> Vec<f64> {
        let r: Vec<f64> = DATA.iter().map(|(x, y)| p[0] + p[1] * x - y).collect();
        vec![2.0 * r.iter().sum::<f64>(), 2.0 * r.iter().zip(&DATA).map(|(ri, (x, _))| ri * x).sum::<f64>()]
    }
}

fn main() {
    // Gradient descent with a fixed learning rate: it must be below 2 / L, where L is the
    // largest eigenvalue of the Hessian (here about 30.2).
    let mut gd = GradientDescent::new(0.03);
    gd.set_max_iterations(Some(10_000));
    gd.set_tolerance(Some(1e-14));
    let r = gd.gradient_based_minimize(&LineFit, &LineFit, vec![0.0, 0.0]).unwrap();
    println!("gradient descent: a = {:.6}, b = {:.6} in {} iterations", r.parameters[0], r.parameters[1], r.iterations);

    // Conjugate gradients need no learning rate: each step is chosen by a line search.
    for beta in [ConjugateGradientBeta::FletcherReeves, ConjugateGradientBeta::PolakRibierePlus] {
        let r = NonlinearConjugateGradient::new(beta).gradient_based_minimize(&LineFit, &LineFit, vec![0.0, 0.0]).unwrap();
        println!("CG {beta:?}: a = {:.6}, b = {:.6} in {} iterations", r.parameters[0], r.parameters[1], r.iterations);
    }
}

Strengths

  • memory and cost per iteration, so they scale to millions of variables.
  • Conjugate gradients need no parameter tuning and converge like rather than .

Weaknesses

  • Gradient descent is very slow on ill-conditioned problems and needs a well-chosen step.
  • Conjugate gradients need accurate line searches, and are usually beaten by L-BFGS, which uses the same memory more effectively.

Exercises

  1. For , show that gradient descent with step multiplies each eigencomponent by , and that the best fixed step is .
  2. Show that gradient descent with exact line searches takes successive steps at right angles.
  3. Show that on a quadratic, with exact line searches, the Fletcher-Reeves and Polak-Ribière formulas give the same .
  4. Minimise for with conjugate gradients and gradient descent. How do the iteration counts grow with (and so with )?
  5. Replace the fixed learning rate with a backtracking (Armijo) line search, and compare on the Rosenbrock function.
Hints and answers
  1. The gradient is , so each step gives , which multiplies the component along the eigenvector with eigenvalue by . The worst factor over is smallest when , i.e. , giving the rate .
  2. The exact line search along makes , i.e. .
  3. Fletcher-Reeves is ; Polak-Ribière is . On a quadratic with exact line searches the gradients are mutually orthogonal, so and the two coincide.
  4. Gradient descent’s iteration count grows in proportion to , conjugate gradients’ in proportion to (and never beyond in exact arithmetic).
  5. Expect the Armijo version to be far more robust than a badly chosen fixed rate but still slow on Rosenbrock’s curved valley, needing thousands of iterations.

Further reading

  • A. Cauchy, “Méthode générale pour la résolution des systèmes d’équations simultanées”, Comptes Rendus de l’Académie des Sciences 25 (1847) 536–538.
  • M. R. Hestenes and E. Stiefel, “Methods of conjugate gradients for solving linear systems”, Journal of Research of the National Bureau of Standards 49 (1952) 409–436.
  • R. Fletcher and C. M. Reeves, “Function minimization by conjugate gradients”, The Computer Journal 7 (1964) 149–154.
  • W. W. Hager and H. Zhang, “A survey of nonlinear conjugate gradient methods”, Pacific Journal of Optimization 2 (2006) 35–58.
  • J. R. Shewchuk, “An introduction to the conjugate gradient method without the agonizing pain”, Carnegie Mellon University, 1994.