TExcelTAD
Home › Optimization › Nonlinear Conjugate Gradient

Nonlinear Conjugate Gradient

The conjugate gradient method was built for quadratics, but its recipe, "new direction = negative gradient + β\beta times old direction", makes sense for any smooth function. Nonlinear CG keeps CG's tiny memory footprint (a few vectors) and usually beats gradient descent by a wide margin, though it is less robust than L-BFGS.

The iteration

p0=−∇f0,xk+1=xk+tkpk,pk+1=−∇fk+1+βk+1pk\mathbf{p}_0 = -\nabla f_0, \qquad \mathbf{x}_{k+1} = \mathbf{x}_k + t_k\mathbf{p}_k, \qquad \mathbf{p}_{k+1} = -\nabla f_{k+1} + \beta_{k+1}\mathbf{p}_k

The step tkt_k comes from a line search (strong Wolfe with a small c2c_2, around 0.1, because CG needs fairly accurate searches). Different formulas for β\beta agree on quadratics but behave differently elsewhere:

Name βk+1\beta_{k+1} Notes
Fletcher-Reeves (FR) ∇fk+1T∇fk+1∇fkT∇fk\frac{\nabla f_{k+1}^T\nabla f_{k+1}}{\nabla f_k^T\nabla f_k} global convergence theory, can stall
Polak-Ribière (PR) ∇fk+1T(∇fk+1−∇fk)∇fkT∇fk\frac{\nabla f_{k+1}^T(\nabla f_{k+1} - \nabla f_k)}{\nabla f_k^T\nabla f_k} resets itself when progress stalls; usually faster
PR+ max⁡(βPR,0)\max(\beta^{PR}, 0) PR with a safeguard; the common default
Hestenes-Stiefel (HS) ∇fk+1TykpkTyk\frac{\nabla f_{k+1}^T\mathbf{y}_k}{\mathbf{p}_k^T\mathbf{y}_k} close to PR in practice
python · try it yourself
import numpy as np
import warnings
from scipy.optimize import line_search
warnings.filterwarnings("ignore")      # line_search warns when it gives up on a step

f = lambda p: (1 - p[0])**2 + 100 * (p[1] - p[0]**2)**2
grad = lambda p: np.array([-2 * (1 - p[0]) - 400 * p[0] * (p[1] - p[0]**2), 200 * (p[1] - p[0]**2)])

def ncg(beta_rule, x, tol=1e-6, max_iter=20000):
    g = grad(x); p = -g
    for k in range(max_iter):
        if np.linalg.norm(g) < tol:
            return k
        t = line_search(f, grad, x, p, gfk=g, c2=0.1)[0]
        if t is None:                       # line search failed: restart along -g
            p = -g; t = line_search(f, grad, x, p, gfk=g, c2=0.1)[0] or 1e-4
        x = x + t * p; g_new = grad(x)
        if beta_rule == "FR":
            beta = (g_new @ g_new) / (g @ g)
        else:
            beta = max((g_new @ (g_new - g)) / (g @ g), 0.0)
        p = -g_new + beta * p; g = g_new
    return max_iter

for rule in ("FR", "PR+"):
    print(rule, "iterations:", ncg(rule, np.array([-1.2, 1.0])))
FR iterations: 48
PR+ iterations: 20

Restarts

Nonlinear CG loses conjugacy as the function departs from a quadratic, so implementations restart with p=−∇f\mathbf{p} = -\nabla f every nn iterations or whenever consecutive gradients are far from orthogonal (∣∇fk+1T∇fk∣≥0.1∥∇fk+1∥2\lvert \nabla f_{k+1}^T\nabla f_k \rvert \ge 0.1\lVert \nabla f_{k+1} \rVert^2). PR+ restarts automatically: when βPR<0\beta^{PR} < 0 the max sets it to 0.

Comparison on a larger problem

python · try it yourself
import numpy as np
from scipy.optimize import minimize

n = 200
rng = np.random.default_rng(0)
A = rng.normal(size=(n, n)) / np.sqrt(n); Q = A.T @ A + 0.01 * np.eye(n); b = rng.normal(size=n)
f = lambda x: 0.5 * x @ Q @ x - b @ x + 0.1 * np.sum(np.log(np.cosh(x)))
grad = lambda x: Q @ x - b + 0.1 * np.tanh(x)
for method in ("CG", "L-BFGS-B", "BFGS"):
    r = minimize(f, np.zeros(n), jac=grad, method=method, options={"gtol": 1e-6, "maxiter": 10000})
    print(f"{method:9s} iterations {r.nit:4d}, gradient evaluations {r.njev:4d}")
CG        iterations  152, gradient evaluations  211
L-BFGS-B  iterations   87, gradient evaluations   91
BFGS      iterations  107, gradient evaluations  109

When to choose nonlinear CG

  • Memory is extremely tight (it stores 3–4 vectors versus L-BFGS's 2m2m).
  • The function is close to quadratic, where CG's conjugacy pays off.
  • Otherwise L-BFGS is usually the safer default: it tolerates inexact line searches better.

In software

  • scipy.optimize.minimize(method="CG") is Polak-Ribière with a strong-Wolfe line search; scipy.optimize.fmin_cg is the older interface.
  • Large-scale scientific codes (geophysical inversion, molecular mechanics energy minimization) traditionally use nonlinear CG because of its tiny memory.

Exercises

Exercise 1: Reduce to linear CG

Show that on a quadratic with exact line searches, the Fletcher-Reeves and Polak-Ribière formulas give the same β\beta.

Answer

Consecutive gradients are orthogonal, so ∇fk+1T∇fk=0\nabla f_{k+1}^T\nabla f_k = 0 and the PR numerator reduces to the FR numerator.

Solution

In linear CG, residuals (negative gradients) are mutually orthogonal. Then ∇fk+1T(∇fk+1−∇fk)=∇fk+1T∇fk+1\nabla f_{k+1}^T(\nabla f_{k+1} - \nabla f_k) = \nabla f_{k+1}^T\nabla f_{k+1}.

Exercise 2: Descent property

Why must the line search be accurate for pk+1\mathbf{p}_{k+1} to be a descent direction?

Answer

∇fk+1Tpk+1=−∥∇fk+1∥2+β ∇fk+1Tpk\nabla f_{k+1}^T\mathbf{p}_{k+1} = -\lVert \nabla f_{k+1} \rVert^2 + \beta\,\nabla f_{k+1}^T\mathbf{p}_k, and the second term is only small if the search made ∇fk+1Tpk\nabla f_{k+1}^T\mathbf{p}_k nearly zero.

Solution

An exact search makes ∇fk+1Tpk=0\nabla f_{k+1}^T\mathbf{p}_k = 0, leaving −∥∇fk+1∥2<0-\lVert \nabla f_{k+1} \rVert^2 < 0. With strong Wolfe and small c2c_2, ∣∇fk+1Tpk∣≤c2∣∇fkTpk∣\lvert \nabla f_{k+1}^T\mathbf{p}_k \rvert \le c_2\lvert \nabla f_k^T\mathbf{p}_k \rvert, which keeps the sum negative for FR when c2<12c_2 < \frac{1}{2}.

Exercise 3: Restart frequency (code)

On a convex quadratic in 50 variables, compare linear CG with a "CG" that restarts (β=0\beta = 0) every 5 iterations. Which needs more iterations to reach a residual of 10−810^{-8}?

Answer

The restarted version, because each restart throws away conjugacy information.

Solution
python · try it yourself
import numpy as np
rng = np.random.default_rng(3)
M = rng.normal(size=(50, 50)); A = M @ M.T / 50 + 0.05 * np.eye(50); b = rng.normal(size=50)
def run(restart):
    x = np.zeros(50); r = b.copy(); p = r.copy()
    for k in range(1, 100000):
        Ap = A @ p; a = (r @ r) / (p @ Ap); x += a * p; r_new = r - a * Ap
        if np.linalg.norm(r_new) < 1e-8:
            return k
        beta = 0.0 if (restart and k % restart == 0) else (r_new @ r_new) / (r @ r)
        p = r_new + beta * p; r = r_new
print("no restart:", run(None), " restart every 5:", run(5))
no restart: 58  restart every 5: 171

Test yourself

Nonlinear CG's new direction is…

  1. −∇fk+1-\nabla f_{k+1} only
  2. −∇fk+1+βk+1pk-\nabla f_{k+1} + \beta_{k+1}\mathbf{p}_k
  3. −Hk∇fk+1-H_k\nabla f_{k+1}
  4. a random direction

What does the "+" in PR+ do?

  1. Adds momentum
  2. Sets β=max⁡(βPR,0)\beta = \max(\beta^{PR}, 0), restarting when βPR\beta^{PR} is negative
  3. Doubles the step
  4. Adds a Hessian term

Compared with L-BFGS, nonlinear CG…

  1. uses more memory
  2. uses less memory but is usually less robust
  3. needs Hessians
  4. cannot handle more than 100 variables