Newton and quasi-Newton methods: Newton, BFGS and L-BFGS
| Problem | Minimise a smooth function of many variables, using second-order information computed (Newton) or learned from gradients (quasi-Newton) |
| Devised by | Newton’s method for minimisation: from Newton and Raphson via Thomas Simpson (1740). Quasi-Newton methods: William Davidon (1959), Roger Fletcher and Michael Powell (1963); BFGS: Charles Broyden, Roger Fletcher, Donald Goldfarb and David Shanno, independently (1970); L-BFGS: Jorge Nocedal (1980), Dong Liu and Nocedal (1989) |
| Accuracy | Newton: quadratic convergence near a minimum with positive definite Hessian. BFGS and L-BFGS: superlinear (BFGS) or fast linear (L-BFGS) convergence |
| Cost | Newton: a Hessian and an solve per iteration. BFGS: one gradient and work and memory. L-BFGS: one gradient and work and memory for stored pairs |
| Read first | Gradient descent and nonlinear conjugate gradients, Nonlinear systems: Newton’s and Broyden’s methods |
| API | NewtonRaphsonMethod, Bfgs, Lbfgs |
Overview
Gradient methods use a linear model of ; Newton’s method uses a quadratic model, built from the gradient and the Hessian, and jumps to the model’s minimum. Near a minimum this is extremely effective: the number of correct digits doubles at each step, and the ill-conditioning that cripples gradient descent is irrelevant, because the Hessian accounts for it exactly. The costs are computing the second derivatives and solving an system at every step.
Quasi-Newton methods keep most of the benefit without the Hessian. They build an approximation to it (or to its inverse) from the changes in the gradient observed along the way. BFGS is the most successful of them, and the default local minimiser in most software. L-BFGS stores only the last few gradient changes instead of an matrix, which makes it the method of choice for large problems.
Where it is used
Quasi-Newton methods are the default for smooth problems of moderate size.
- Parameter estimation. Maximum-likelihood fits in statistics, and system identification in engineering.
- Machine learning. L-BFGS trains logistic regression and many classical models, and is used for large problems in memory-limited settings.
- Design optimisation. Shape and parameter optimisation where gradients are available from adjoint or automatic differentiation.
- Computational chemistry. Geometry optimisation of molecules uses BFGS-type updates.
History
Newton’s method for minimisation is Newton’s method for the root of . Thomas Simpson (1740) first applied it to find a stationary point.
The quasi-Newton idea came from William Davidon, a physicist at Argonne National Laboratory, who in 1959 wanted to speed up a slow minimisation running on an unreliable computer. His report, “Variable metric method for minimisation”, was rejected by a journal and circulated as a technical report. Roger Fletcher and Michael Powell (1963) recognised its power, simplified it and published the DFP method, which made it famous; the original report was finally published in the first issue of the SIAM Journal on Optimisation in 1991. In 1970 four people, Broyden, Fletcher, Goldfarb and Shanno, independently derived a better update, the dual of DFP, now called BFGS. Jorge Nocedal (1980) showed how to apply BFGS with only a few stored vectors, and with Dong Liu (1989) made L-BFGS the standard method for large smooth problems.
The idea
Newton’s method
Gradient descent uses only the slope of at the current point. Newton’s method also uses its curvature. Around the current point , approximate by the first three terms of its Taylor series, a quadratic function of the displacement :
Here is the Hessian, the symmetric matrix of second partial derivatives. The idea is to jump straight to the minimum of this model. A minimum requires the gradient of with respect to to vanish:
This is a linear system for the Newton step :
The stationary point of is a minimum only if the Hessian is positive definite (the second-order condition of the background section) (the model curves upward in every direction). There is another way to read the same formula: a minimum of is a root of the system , and this is exactly Newton’s method for systems applied to it, with the Hessian as the Jacobian of the gradient.
Strengths. If is itself a quadratic, the model is exact and the method reaches the minimum in one step, whatever the condition number: the Hessian rescales the valley that made gradient descent zigzag. Near any minimum with a positive definite Hessian it converges quadratically, as in the root-finding case.
Weaknesses. Far from a minimum there is no such guarantee.
- Where the Hessian is indefinite the model has no minimum, and the step goes to a saddle point or a maximum of the model instead.
- Even where it is positive definite, the model may be a poor approximation at the distance of the step, which can overshoot and increase .
- Each iteration needs the Hessian and the solution of a linear system, work.
Practical Newton methods therefore modify the Hessian to make it positive definite and add a line
search or a trust region. The library’s NewtonRaphsonMethod is the pure method, best used close
to a minimum.
BFGS
Quasi-Newton methods keep the speed of Newton’s method without computing second derivatives. They maintain an approximation of the Hessian built up from the gradients seen so far, just as Broyden’s method builds up a Jacobian. BFGS, named after Broyden, Fletcher, Goldfarb and Shanno, is the most successful of them.
It is convenient to approximate the inverse Hessian directly, by a matrix , because then the Newton-like step needs no linear solve:
with the step length chosen by a line search.
What a step teaches. After the step we know two vectors: the displacement and the change in the gradient . For a quadratic with Hessian the gradient is , so these are related exactly by , or . We ask the new approximation to agree with this observation, the secant equation
The update. The secant equation gives conditions on a symmetric matrix with entries, so many matrices satisfy it. BFGS chooses the symmetric one closest to (in a suitably weighted norm), on the principle that the old information should be kept unless it conflicts with the new. The result is
It is easy to check that this satisfies the secant equation. The rightmost bracket applied to gives , so the whole first term vanishes, and the second gives . The update changes by a matrix of rank two, and costs operations.
Staying positive definite. If is positive definite and , then is positive definite too, and so is always a descent direction. The condition says that the slope along the step has increased, that is, the function curves upward along it. The Wolfe curvature condition guarantees exactly this, which is why BFGS is paired with a Wolfe line search.
Starting. The first approximation is , which makes the first step a gradient descent step. After that step it is rescaled by , an estimate of the inverse curvature along the step, so that later steps have about the right length.
BFGS converges superlinearly, and it corrects poor approximations of the Hessian quickly; it is remarkably robust.
L-BFGS
BFGS stores the dense matrix , which is impossible for a million variables. Limited-memory BFGS avoids storing it at all.
The observation is that the method never needs itself, only the product with the current gradient. And is nothing more than (a multiple of the identity) with updates applied, each defined by one pair of vectors . The product can therefore be computed from the stored pairs alone, by unrolling the update formula. The procedure is called the two-loop recursion: one loop runs backwards through the pairs applying the right-hand brackets of the updates, and a second runs forwards applying the left-hand ones. With pairs it costs operations.
L-BFGS keeps only the most recent pairs (typically 3 to 20) and discards older ones, so its memory is numbers instead of . Old curvature information is also the least relevant, since it was gathered far from the current point. The price is that convergence is linear instead of superlinear, but it is fast in practice, and on large problems L-BFGS is usually the fastest method that needs only gradients.
Comparison
Iterations / evaluations of to reach (each method evaluates about as often as , and Newton’s method also evaluates the Hessian at every iteration; gradient descent is limited to 20 000 iterations):
Table 5.4. Gradient methods compared on test problems.
| problem | gradient descent | CG (PR+) | CG (FR) | BFGS | L-BFGS (m = 10) | Newton |
|---|---|---|---|---|---|---|
| Rosenbrock, | 14317 / 14318 | 36 / 118 | 35 / 131 | 38 / 48 | 39 / 48 | 7 / 8 |
| Rosenbrock, | fails, | 131 / 372 | 140 / 391 | 84 / 94 | 82 / 98 | 35 / 36 |
| quadratic, , | 12756 / 12757 | 352 / 714 | 347 / 712 | 377 / 378 | 367 / 382 | 2 / 3 |
- On the Rosenbrock function, Newton’s method needs 7 iterations and BFGS 38. Gradient descent, with a fixed step of 0.002, needs over 14 000 for and fails within 20 000 for .
- On the quadratic with condition number Newton’s method is exact in one step (the second confirms it). BFGS and conjugate gradients would terminate in steps with exact line searches; with the inexact Wolfe searches used here they need a few hundred.
- L-BFGS with 10 pairs matches BFGS while storing 20 vectors instead of a matrix.
The figure in the chapter introduction shows the convergence histories on the Rosenbrock function: Newton’s quadratic convergence, after a first step that increases , and the superlinear finish of BFGS.
Algorithm
Newton’s method (NewtonRaphsonMethod). Input: , its gradient and Hessian, and a starting
point . Repeat, up to the iteration limit:
- evaluate the gradient and the Hessian ;
- solve the linear system ; a singular Hessian is an error;
- set , projected onto the bounds if any;
- stop when changes by less than the tolerance.
Each iteration costs one Hessian and an solve.
BFGS (Bfgs). Input: , its gradient and a starting point .
- Initialise. Set and evaluate .
- Direction. Compute . If rounding has made this fail to be a descent direction (), reset and use .
- Line search. Find a step by a strong Wolfe line search with , trying first. Set and move to .
- Update. Evaluate the new gradient and form , the change in the gradient. If , apply the BFGS update to ; before the very first update, rescale to . If , skip the update and keep .
- Test. Stop when the largest component of the gradient in magnitude is below the tolerance; otherwise go to 2.
Each iteration costs the line search plus arithmetic, and the method stores the matrix .
L-BFGS (Lbfgs). The same loop, with two changes.
- No matrix is stored. Step 4 appends the pair to a list, discarding the oldest when the list holds pairs.
- Step 2 computes by the two-loop recursion. Start with . Going from the newest pair to the oldest, compute and subtract from . Multiply by the scalar of the newest pair, which plays the role of . Then, going from the oldest pair to the newest, compute and add to . The result is .
Each iteration costs arithmetic and the method stores vectors.
Implementation
The Newton step:
let gradient = gradient_function.evaluate(&result.parameters);
let hessian = hessian_function.evaluate(&result.parameters);
if gradient.len() != n || hessian.len() != n || hessian.iter().any(|row| row.len() != n) {
return Err(ErrorsJSL::Misconfiguration("The gradient and Hessian must match the number of parameters."));
}
let hessian_matrix = ndarray::Array2::from_shape_vec((n, n), hessian.into_iter().flatten().collect())
.expect("n × n entries");
// Solve H p = −g rather than forming the inverse.
let step = hessian_matrix
.solve(&ndarray::Array1::from_vec(gradient))
.map_err(|_| ErrorsJSL::RuntimeError("The Hessian is singular."))?
.mapv(|x| -x);
The BFGS update, expanded to avoid forming matrix products:
let rho = 1.0 / sy;
let hy: Vec<f64> = h.iter().map(|row| dot(row, &y)).collect();
let yhy = dot(&y, &hy);
for i in 0..n {
for j in 0..n {
h[i][j] += -rho * (hy[i] * s[j] + s[i] * hy[j]) + (rho * rho * yhy + rho) * s[i] * s[j];
}
}
The L-BFGS two-loop recursion:
// Two-loop recursion: d = −H g.
let mut q = g.clone();
let mut alphas = Vec::with_capacity(pairs.len());
for (s, y, rho) in pairs.iter().rev() {
let a = rho * dot(s, &q);
q.iter_mut().zip(y).for_each(|(v, yi)| *v -= a * yi);
alphas.push(a);
}
let gamma = pairs.back().map_or(1.0, |(s, y, _)| dot(s, y) / dot(y, y));
q.iter_mut().for_each(|v| *v *= gamma);
for ((s, y, rho), a) in pairs.iter().zip(alphas.iter().rev()) {
let b = rho * dot(y, &q);
q.iter_mut().zip(s).for_each(|(v, si)| *v += (a - b) * si);
}
NewtonRaphsonMethodsolves the Newton system rather than inverting the Hessian. A singular Hessian is an error. Earlier versions panicked there, had no constructor (so they could not be created outside the crate), and looped forever without an iteration limit; the default limit is now 100.BfgsandLbfgsstop on the gradient norm (default ) and do not support bounds; setting bounds is an error.
In practice
//! Newton's method, BFGS and L-BFGS on the Rosenbrock function.
//!
//! Run with `cargo run -p lib_jsl_optimization --example optimization_quasi_newton`.
use lib_jsl_optimization::newton_raphson_method::NewtonRaphsonMethod;
use lib_jsl_optimization::optimization_traits::{
GradientBasedMinimizationEngine, GradientFunction, HessianBasedMinimizationEngine, HessianFunction, MinimizationControls, ObjectiveFunction,
};
use lib_jsl_optimization::quasi_newton::{Bfgs, Lbfgs};
/// f(x, y) = 100 (y − x²)² + (1 − x)², minimum 0 at (1, 1).
struct Rosenbrock;
impl ObjectiveFunction for Rosenbrock {
fn evaluate(&self, p: &[f64]) -> f64 {
100.0 * (p[1] - p[0] * p[0]).powi(2) + (1.0 - p[0]).powi(2)
}
}
impl GradientFunction for Rosenbrock {
fn evaluate(&self, p: &[f64]) -> Vec<f64> {
let t = p[1] - p[0] * p[0];
vec![-400.0 * p[0] * t - 2.0 * (1.0 - p[0]), 200.0 * t]
}
}
impl HessianFunction for Rosenbrock {
fn evaluate(&self, p: &[f64]) -> Vec<Vec<f64>> {
vec![vec![1200.0 * p[0] * p[0] - 400.0 * p[1] + 2.0, -400.0 * p[0]], vec![-400.0 * p[0], 200.0]]
}
}
fn main() {
let start = vec![-1.2, 1.0];
let mut newton = NewtonRaphsonMethod::new();
newton.set_tolerance(Some(1e-15));
let r = newton.hessian_based_minimize(&Rosenbrock, &Rosenbrock, &Rosenbrock, start.clone()).unwrap();
println!("Newton: {:?} in {} iterations", r.parameters, r.iterations);
let r = Bfgs::new().gradient_based_minimize(&Rosenbrock, &Rosenbrock, start.clone()).unwrap();
println!("BFGS: {:?} in {} iterations", r.parameters, r.iterations);
// L-BFGS keeps only the last few correction pairs: O(m n) memory instead of O(n²).
let r = Lbfgs::new(5).gradient_based_minimize(&Rosenbrock, &Rosenbrock, start).unwrap();
println!("L-BFGS: {:?} in {} iterations", r.parameters, r.iterations);
}
Strengths
- Newton: quadratic convergence, insensitive to conditioning, few iterations.
- BFGS: needs only gradients, superlinear, robust; the best general-purpose local method for moderate .
- L-BFGS: the same in memory, for problems with up to millions of variables.
Weaknesses
- Newton needs the Hessian and an solve, and the pure method may diverge or find a saddle.
- BFGS needs memory and work per iteration.
- All find local minima only, and need a smooth (noise in the gradient corrupts the updates).
Exercises
- Show that Newton’s method is invariant under linear changes of variables , while gradient descent is not.
- Verify that the BFGS update satisfies the secant equation .
- Show that if is positive definite and then is positive definite.
- Implement the two-loop recursion and check that it gives the same as the dense BFGS matrix when is at least the number of iterations.
- Run L-BFGS on the -dimensional Rosenbrock function for with and compare iterations and time.
Hints and answers
- With and : and . The Newton step in is , which maps to the same step in . The gradient step maps to .
- With the update is . Since , the first term kills and the second gives .
- For put : then . Both terms are non-negative, and they cannot both vanish: if then with .
- Keep the pairs for all iterations (when is at least that number) and apply the recursion to ; compare with from the dense updates started from the same .
- Expect the iteration count to fall as grows while the cost per iteration rises in proportion to ; the best trade-off is usually modest .
Further reading
- W. C. Davidon, “Variable metric method for minimization”, SIAM Journal on Optimization 1 (1991) 1–17 (the 1959 report).
- R. Fletcher, Practical Methods of Optimization, 2nd ed., Wiley, 1987.
- D. C. Liu and J. Nocedal, “On the limited memory BFGS method for large scale optimization”, Mathematical Programming 45 (1989) 503–528.
- J. Nocedal and S. J. Wright, Numerical Optimization, 2nd ed., Springer, 2006, chapters 3, 6 and 7.
- J. E. Dennis and R. B. Schnabel, Numerical Methods for Unconstrained Optimization and Nonlinear Equations, SIAM, 1996.