Module contents
Lesson 14 of 27Core 100 min

Quasi-Newton and inexact Newton: second order at scale

Obtain much of Newton's advantage without calculating or factoring Hessians: the secant equation, BFGS update and limited-memory L-BFGS two-loop recursion. Complete the picture with inexact Newton (Newton-CG), which only needs Hessian-vector products.

After this lesson you can

  • Derive the secant equation and BFGS update as a minimum-change rank-two correction.
  • Explain why Wolfe's curvature condition guarantees that BFGS retains a positive definite matrix.
  • Implement L-BFGS with the two-loop recursion and initial scaling.
  • Implement Newton-CG with Hessian-vector products, forcing tolerances and negative-curvature detection.
  • Choose among GD, L-BFGS, Newton-CG and Newton based on dimension, gradient cost and stochasticity.

Before you start

Motivation: curvature without paying for the Hessian

The previous lesson’s Newton method converges in a handful of iterations because it uses curvature. But each iteration assembles and stores the Hessian and solves an n×nn \times n system. With n=106n = 10^6 parameters, a small network, a double-precision Hessian occupies 8×10128 \times 10^{12} bytes, eight terabytes, and Cholesky factorization costs n3/3≈3×1017n^3/3 \approx 3 \times 10^{17} operations. This is impractical. Yet second-order methods solve problems at that scale daily: inverse problems and variational data assimilation, original neural style transfer (Gatys et al. used L-BFGS on pixels), logistic regressions with millions of variables, and physical-model refinement with adjoint gradients.

The key: curvature need not be calculated; it can be measured. Each step s\vb{s} and observed gradient change y\vb{y} measures curvature in that direction for free, from evaluations already made. Quasi-Newton methods accumulate these measurements in an approximate Hessian (or inverse). A second, orthogonal route: even if ∇2f\hess f cannot be formed, ∇2f(x) v\hess f(\vb{x})\,\vb{v} can almost always be computed for the cost of a few gradients (Hessian-vector product), enough to solve Newton’s system approximately with conjugate gradients. This is inexact Newton.

This lesson develops both routes and orders them by cost:

MethodMemoryWork per iterationLocal convergence
NewtonO(n2)\bigO(n^2)O(n3)\bigO(n^3)quadratic
BFGSO(n2)\bigO(n^2)O(n2)\bigO(n^2)superlinear
L-BFGS (memory mm)O(mn)\bigO(mn)O(mn)\bigO(mn)linear (R-linear proven)
Newton-CGO(n)\bigO(n)kk Hessian-vector productssuperlinear or quadratic with adjusted tolerance
Gradient descentO(n)\bigO(n)O(n)\bigO(n)linear

The order: the secant equation, what can be learned from a step; BFGS, the best way to use it; L-BFGS, which forgets old information to fit in memory; Newton-CG, the other route; why all this breaks with stochastic gradients; and how to choose. Code from scratch and with libraries follows.

The secant equation: measure curvature with two gradients

In one variable, the secant method approximates ff‘s second derivative by (f′(xk+1)−f′(xk))/(xk+1−xk)\big(f'(x_{k+1}) - f'(x_k)\big)/(x_{k+1} - x_k) and uses it instead of f′′f'' in Newton’s step. It converges with order 1+52≈1.618\tfrac{1+\sqrt5}{2} \approx 1.618: slower than Newton’s quadratic rate, but without second derivatives and with one f′f' evaluation per step. In several variables this quotient is a vector equality. Let xk+1=xk+sk\vb{x}_{k+1} = \vb{x}_k + \vb{s}_k and

yk=∇f(xk+1)−∇f(xk).\vb{y}_k = \grad f(\vb{x}_{k+1}) - \grad f(\vb{x}_k).

By the fundamental theorem of calculus applied to t↦∇f(xk+tsk)t \mapsto \grad f(\vb{x}_k + t\vb{s}_k),

yk=Gˉk sk,Gˉk=∫01∇2f(xk+tsk) ⁣dt.\vb{y}_k = \bar{\mat{G}}_k\,\vb{s}_k, \qquad \bar{\mat{G}}_k = \int_0^1 \hess f(\vb{x}_k + t\vb{s}_k)\dd t.

The pair (sk,yk)(\vb{s}_k, \vb{y}_k) gives the average Hessian along the segment applied to direction sk\vb{s}_k and nothing more: one column of information (nn numbers) about a matrix with n(n+1)/2n(n+1)/2. We ask the new Hessian approximation Bk+1\mat{B}_{k+1} to agree with what was observed.

The curvature condition is essential. If Bk+1\mat{B}_{k+1} must be positive definite (so −Bk+1−1∇f-\mat{B}_{k+1}\inv\grad f descends), multiplying the secant equation by sk⊤\vb{s}_k\T gives sk⊤Bk+1sk=sk⊤yk\vb{s}_k\T\mat{B}_{k+1}\vb{s}_k = \vb{s}_k\T\vb{y}_k, which must be positive. Conversely:

Proof

(⇒\Rightarrow) s⊤y=s⊤Bs>0\vb{s}\T\vb{y} = \vb{s}\T\mat{B}\vb{s} > 0 since B≻0\mat{B} \succ 0. (⇐\Leftarrow) Take

B=I−ss⊤s⊤s+yy⊤s⊤y.\mat{B} = \mat{I} - \frac{\vb{s}\vb{s}\T}{\vb{s}\T\vb{s}} + \frac{\vb{y}\vb{y}\T}{\vb{s}\T\vb{y}}.

It is symmetric and Bs=s−s+y=y\mat{B}\vb{s} = \vb{s} - \vb{s} + \vb{y} = \vb{y}. For v≠0\vb{v} \neq \vb{0}, v⊤Bv=∥Pv∥2+(y⊤v)2/(s⊤y)≥0\vb{v}\T\mat{B}\vb{v} = \norm{\mat{P}\vb{v}}^2 + (\vb{y}\T\vb{v})^2/(\vb{s}\T\vb{y}) \ge 0, where P\mat{P} projects orthogonally onto s⊥\vb{s}^\perp. It vanishes only if Pv=0\mat{P}\vb{v} = \vb{0}, i.e. v=cs\vb{v} = c\vb{s}, and also y⊤v=c y⊤s=0\vb{y}\T\vb{v} = c\,\vb{y}\T\vb{s} = 0, forcing c=0c = 0.

∎

The figure shows the secant equation in one variable in detail. Below is f′f': in one dimension curvature is its slope. The secant between the two gradients is the magenta line, whose slope y/sy/s averages f′′f'' along the segment. For the convex function it is always positive. For the double-well function it can be negative even if curvature is positive at both endpoints: the function is concave between wells and a crossing step measures negative average curvature. This is s⊤y≤0\vb{s}\T\vb{y} \le 0, excluded by a line search with Wolfe’s curvature condition but not by Armijo.

InteractiveWhat the secant equation measures
The function ff
Its gradient f′f': the secant between the two points measures curvature
  • f′f'
  • secant: slope y/sy/s
  • tangent: slope f′′(xk)f''(x_k)
  • xkx_k
  • xk+1x_{k+1}
Function
−0.9
1.8
s=xk+1−xks = x_{k+1} - x_k1.8
y=f′(xk+1)−f′(xk)y = f'(x_{k+1}) - f'(x_k)−0.342
Secant slope y/sy/s−0.19
Mean f′′f'' over the interval−0.19
f′′(xk)f''(x_k) and f′′(xk+1)f''(x_{k+1})1.4 and 1.4
s ys\,y−0.616
Step directionascent
Armijonot applicable
Wolfe: curvaturenot applicable
The secant slope is y/s=−0.19<0y/s = −0.19 < 0: average curvature along the interval is negative. The secant equation Bk+1s=yB_{k+1}s = y would require Bk+1<0B_{k+1} < 0, and a BFGS update here would no longer be positive definite. Notice that curvature is positive at both endpoints, but not over the whole interval.
Above, the double-well function ff; below, its gradient f′f' with draggable points xkx_k (orange) and xk+1x_{k+1} (teal). The magenta line is the secant and dashed gray line the tangent at xkx_k (local curvature Newton would use). Start with a long step from xk=−0.9x_k = -0.9 to xk+1=0.9x_{k+1} = 0.9: curvature is positive at both ends (1.431.43) and the secant slope negative, so s⊤y<0\vb{s}\T\vb{y} < 0 and no positive definite matrix can satisfy the equation. Shorten the step with the slider: secant slope approaches tangent slope. Set xk=0.4x_k = 0.4 and step 0.10.1: Armijo accepts this descent (ff drops from −0.014-0.014 to −0.034-0.034), but s⊤y<0\vb{s}\T\vb{y} < 0 and Wolfe curvature fails. Switch to the convex function: because f′′>0f'' > 0 everywhere, secant slope and s⊤y>0\vb{s}\T\vb{y} > 0 for any pair. In both functions the readout 'average f′′f'' over the segment' matches the secant slope.

The secant equation gives nn equations for n(n+1)/2n(n+1)/2 unknowns (entries of a symmetric matrix): once n>1n > 1 infinitely many solutions exist, and each quasi-Newton method’s trick is which to choose. Naturally choose the closest to the previous approximation: change as little as possible to incorporate new information.

BFGS: the closest rank-two correction

Variational derivation

Work with inverse Hk≈∇2f(xk)−1\mat{H}_k \approx \hess f(\vb{x}_k)\inv instead of Bk\mat{B}_k, because search direction is dk=−Hk∇f(xk)\vb{d}_k = -\mat{H}_k\grad f(\vb{x}_k) and no system needs solving. Among symmetric matrices satisfying the inverse secant equation, choose closest to Hk\mat{H}_k in weighted Frobenius norm ∥A∥W=∥W1/2AW1/2∥F\norm{\mat{A}}_{\mat{W}} = \norm{\mat{W}^{1/2}\mat{A}\mat{W}^{1/2}}_F, with positive definite W\mat{W} and Wsk=yk\mat{W}\vb{s}_k = \vb{y}_k (e.g. average Hessian Gˉk\bar{\mat{G}}_k). This weight makes the result independent of variable units.

Proof

Write s,y,ρ,H\vb{s}, \vb{y}, \rho, \mat{H} without subscripts and H+\mat{H}_+ for the formula’s matrix.

Feasibility. It is symmetric. Since (I−ρys⊤)y=y−ρ(s⊤y)y=0(\mat{I} - \rho\vb{y}\vb{s}\T)\vb{y} = \vb{y} - \rho(\vb{s}\T\vb{y})\vb{y} = \vb{0}, the first term vanishes on y\vb{y} and H+y=ρs(s⊤y)=s\mat{H}_+\vb{y} = \rho\vb{s}(\vb{s}\T\vb{y}) = \vb{s}.

Orthogonality to feasible directions. The norm’s inner product is ⟨A,C⟩W=tr⁡(WAWC)\langle\mat{A}, \mat{C}\rangle_{\mat{W}} = \tr(\mat{W}\mat{A}\mat{W}\mat{C}). Expanding,

H+−H=−ρ s(Hy)⊤−ρ (Hy)s⊤+(ρ2 y⊤Hy+ρ) ss⊤.\mat{H}_+ - \mat{H} = -\rho\,\vb{s}(\mat{H}\vb{y})\T - \rho\,(\mat{H}\vb{y})\vb{s}\T + (\rho^2\,\vb{y}\T\mat{H}\vb{y} + \rho)\,\vb{s}\vb{s}\T.

Multiplying on both sides by W\mat{W} and using Ws=y\mat{W}\vb{s} = \vb{y} yields a matrix of form uy⊤+yu⊤\vb{u}\vb{y}\T + \vb{y}\vb{u}\T, with u=−ρWHy+12(ρ2 y⊤Hy+ρ)y\vb{u} = -\rho\mat{W}\mat{H}\vb{y} + \tfrac12(\rho^2\,\vb{y}\T\mat{H}\vb{y} + \rho)\vb{y}. Any other feasible matrix is H++D\mat{H}_+ + \mat{D} with symmetric D\mat{D} and Dy=0\mat{D}\vb{y} = \vb{0}, so ⟨H+−H,D⟩W=tr⁡((uy⊤+yu⊤)D)=y⊤Du+u⊤Dy=0\langle\mat{H}_+ - \mat{H}, \mat{D}\rangle_{\mat{W}} = \tr\big((\vb{u}\vb{y}\T + \vb{y}\vb{u}\T)\mat{D}\big) = \vb{y}\T\mat{D}\vb{u} + \vb{u}\T\mat{D}\vb{y} = 0.

Pythagoras. Thus ∥H++D−H∥W2=∥H+−H∥W2+∥D∥W2\norm{\mat{H}_+ + \mat{D} - \mat{H}}_{\mat{W}}^2 = \norm{\mat{H}_+ - \mat{H}}_{\mat{W}}^2 + \norm{\mat{D}}_{\mat{W}}^2, greater unless D=0\mat{D} = \mat{0}.

∎

The proof says more: any other matrix satisfying the secant is farther from Hk\mat{H}_k by exactly ∥D∥W\norm{\mat{D}}_{\mat{W}}, checked against a thousand competitors in the cell below. About the formula:

  • It is a rank-two correction. Hk+1−Hk\mat{H}_{k+1} - \mat{H}_k has rank at most two: only what pair (sk,yk)(\vb{s}_k, \vb{y}_k) contributes changes. Expanded, Hk+1=Hk−ρk(skw⊤+wsk⊤)+(ρk2 yk⊤w+ρk)sksk⊤\mat{H}_{k+1} = \mat{H}_k - \rho_k(\vb{s}_k\vb{w}\T + \vb{w}\vb{s}_k\T) + (\rho_k^2\,\vb{y}_k\T\vb{w} + \rho_k)\vb{s}_k\vb{s}_k\T with w=Hkyk\vb{w} = \mat{H}_k\vb{y}_k, costing O(n2)\bigO(n^2) (one matrix-vector and two outer products), not O(n3)\bigO(n^3) like direct matrix multiplication.
  • It is the inverse of another rank-two correction. By Sherman–Morrison–Woodbury, Bk+1=Hk+1−1\mat{B}_{k+1} = \mat{H}_{k+1}\inv satisfies
Bk+1=Bk−Bksksk⊤Bksk⊤Bksk+ykyk⊤yk⊤sk.\mat{B}_{k+1} = \mat{B}_k - \frac{\mat{B}_k\vb{s}_k\vb{s}_k\T\mat{B}_k}{\vb{s}_k\T\mat{B}_k\vb{s}_k} + \frac{\vb{y}_k\vb{y}_k\T}{\vb{y}_k\T\vb{s}_k}.

The first term removes Bk\mat{B}_k‘s curvature in direction sk\vb{s}_k and the second inserts the measurement.

  • It preserves positive definiteness. This makes the method usable; prove it in the first exercise:

Thus dk=−Hk∇f(xk)\vb{d}_k = -\mat{H}_k\grad f(\vb{x}_k) is always a descent direction: ∇f⊤dk=−∇f⊤Hk∇f<0\grad f\T\vb{d}_k = -\grad f\T\mat{H}_k\grad f < 0. We must guarantee sk⊤yk>0\vb{s}_k\T\vb{y}_k > 0, which is what the Wolfe curvature condition does: with sk=αkdk\vb{s}_k = \alpha_k\vb{d}_k, condition ∇f(xk+αkdk)⊤dk≥c2 ∇f(xk)⊤dk\grad f(\vb{x}_k + \alpha_k\vb{d}_k)\T\vb{d}_k \ge c_2\,\grad f(\vb{x}_k)\T\vb{d}_k with c2<1c_2 < 1 implies yk⊤dk≥(c2−1)∇f(xk)⊤dk>0\vb{y}_k\T\vb{d}_k \ge (c_2 - 1)\grad f(\vb{x}_k)\T\vb{d}_k > 0 (second exercise). Armijo backtracking is insufficient: it accepts steps so short or long that s⊤y\vb{s}\T\vb{y} can be negative, as in the previous figure.

The algorithm

Trying α=1\alpha = 1 first is essential: this is Newton’s step and enables superlinear convergence. With H0=I\mat{H}_0 = \mat{I} the first step is gradient descent. Standard practice rescales H0←y0⊤s0y0⊤y0I\mat{H}_0 \leftarrow \dfrac{\vb{y}_0\T\vb{s}_0}{\vb{y}_0\T\vb{y}_0}\mat{I} after the first step and before the first update, matching the problem’s scale (the L-BFGS section explains why and the cell below measures it).

The figure shows what BFGS learns. On the right is ellipse {v:v⊤Mv=c}\{\vb{v} : \vb{v}\T\mat{M}\vb{v} = c\} for the true matrix M=∇2f\mat{M} = \hess f (gray) and approximation Bk=Hk−1\mat{B}_k = \mat{H}_k\inv (blue). It starts as a circle: it knows nothing. Each update deforms it and, on the quadratic where y=As\vb{y} = \mat{A}\vb{s}, it matches the true one along the last step: the secant equation made visible. (On Rosenbrock Bk\mat{B}_{k} reproduces the last segment’s average Hessian, not the iterate’s, so there is no exact match to mark.) Left, three arrows from the iterate: steepest descent (teal), Newton (dashed gray) and BFGS (orange). As kk advances orange leaves teal and approaches gray.

InteractiveBFGS learns curvature
Cargando el interactivo…
Press ▶ to step through iterations. Left, contours, BFGS path (red), and three directions from the iterate: steepest descent (teal), Newton (dashed gray) and BFGS (orange). Right, ellipse of the true Hessian (gray) versus Bk\mat{B}_k (blue): with H0=I\mat{H}_0 = \mat{I} it starts circular, and on the quadratic red marks show the last step's direction, where the ellipses match by the secant equation (both use the same level, chosen to fit the larger one). Below, gradient norm versus gradient descent with the same search. On the quadratic with κ=30\kappa = 30, BFGS finishes in 77 iterations with Wolfe search and 22 with exact search. Raise κ\kappa and rotate axes: gradient descent worsens and BFGS hardly changes. Switch to Rosenbrock (drag the start): from (−1.2,1)(-1.2, 1) BFGS reaches ∥∇f∥≈10−15\norm{\nabla f} \approx 10^{-15} in 3636 iterations and 5353 evaluations, while gradient descent with the same search remains at ∥∇f∥≈4×10−3\norm{\nabla f} \approx 4 \times 10^{-3} after 6060. Watch κ(Hk∇2f)\kappa(\mat{H}_k\hess f): it equals 11 when Hk\mat{H}_k is proportional to the inverse Hessian and BFGS direction is Newton's.

The figure’s last lesson is subtle and central to convergence theory: Bk\mat{B}_k need not converge to ∇2f(x⋆)\hess f(\vb{x}^\star). It only needs to resemble the Hessian along directions the algorithm traverses.

Convergence

The long proof is in Nocedal and Wright (theorems 6.5 and 6.6): global convergence controls trace and determinant of Bk\mat{B}_k, while superlinear convergence rests on a useful Dennis–Moré characterization.

This conditions Bk\mat{B}_k along the step direction, not the entire matrix. It formalizes the figure’s observation and explains why one pair (s,y)(\vb{s}, \vb{y}) per iteration suffices. Two qualifications:

  • BFGS is superlinear, not quadratic: near optimum it gains more than one digit per iteration, but digits do not double. In the figure this appears as an increasingly steep curve without Newton’s vertical fall.
  • Global BFGS theory for nonconvex problems is incomplete. Counterexamples with Wolfe search (Dai, 2002) and exact search (Mascarenhas, 2004) fail to converge to a stationary point, although rare in practice. Serious implementations add safeguards (skip an update if s⊤y\vb{s}\T\vb{y} is too small or damp it via Powell’s technique).

On a quadratic the theory is complete: with exact search, BFGS generates conjugate directions, terminates in at most nn iterations and Hn=A−1\mat{H}_n = \mat{A}\inv. In the figure, exact search finishes the dimension-22 quadratic in two steps.

L-BFGS: forget to scale

BFGS needs n2n^2 numbers and O(n2)\bigO(n^2) operations per iteration. At n=105n = 10^5 that is 80 GB. Nocedal’s (1980) observation: Hk\mat{H}_k is defined by H0\mat{H}_0 and the applied pairs (si,yi)(\vb{s}_i, \vb{y}_i); the matrix is merely a cache. Keeping only the most recent mm pairs and reconstructing Hk\mat{H}_k by applying them to a simple initial matrix Hk0\mat{H}_k^0 gives limited-memory L-BFGS (Liu and Nocedal, 1989): 2mn2mn stored numbers and, as shown below, O(mn)\bigO(mn) operations per iteration, never forming an n×nn \times n matrix.

The two-loop recursion

Write Vi=I−ρiyisi⊤\mat{V}_i = \mat{I} - \rho_i\vb{y}_i\vb{s}_i\T, so BFGS is Hi+1=Vi⊤HiVi+ρisisi⊤\mat{H}_{i+1} = \mat{V}_i\T\mat{H}_i\mat{V}_i + \rho_i\vb{s}_i\vb{s}_i\T. Unrolling mm steps,

Hk=(Vk−1⊤⋯Vk−m⊤) Hk0 (Vk−m⋯Vk−1)+∑i=k−mk−1ρi (Vk−1⊤⋯Vi+1⊤) sisi⊤ (Vi+1⋯Vk−1).\mat{H}_k = (\mat{V}_{k-1}\T\cdots\mat{V}_{k-m}\T)\,\mat{H}_k^0\,(\mat{V}_{k-m}\cdots\mat{V}_{k-1}) + \sum_{i=k-m}^{k-1}\rho_i\,(\mat{V}_{k-1}\T\cdots\mat{V}_{i+1}\T)\,\vb{s}_i\vb{s}_i\T\,(\mat{V}_{i+1}\cdots\mat{V}_{k-1}).

Each Vi\mat{V}_i is identity minus an outer product: applying it to a vector costs a dot product and an axpy, O(n)\bigO(n). Thus calculate Hkg\mat{H}_k\vb{g} by traversing pairs twice: newest to oldest applying Vi\mat{V}_i, and oldest to newest applying Vi⊤\mat{V}_i\T and adding ρisisi⊤\rho_i\vb{s}_i\vb{s}_i\T terms.

Each loop uses one dot product and one axpy per pair: about 4mn4mn multiplications and as many additions total. L-BFGS direction is dk=−Hk∇f(xk)\vb{d}_k = -\mat{H}_k\grad f(\vb{x}_k) with exactly BFGS’s Wolfe search. By the preceding formula, output matches multiplication by the matrix BFGS would build starting from Hk0\mat{H}_k^0 and applying the mm pairs: the cell below checks this to roundoff.

Initial matrix and scaling

The only freedom is Hk0\mat{H}_k^0, an often neglected ingredient. Standard choice is Hk0=γkI\mat{H}_k^0 = \gamma_k\mat{I} with

γk=sk−1⊤yk−1yk−1⊤yk−1.\gamma_k = \frac{\vb{s}_{k-1}\T\vb{y}_{k-1}}{\vb{y}_{k-1}\T\vb{y}_{k-1}}.

With y=Gˉs\vb{y} = \bar{\mat{G}}\vb{s}, γk=s⊤Gˉss⊤Gˉ2s\gamma_k = \dfrac{\vb{s}\T\bar{\mat{G}}\vb{s}}{\vb{s}\T\bar{\mat{G}}^2\vb{s}} is a generalized Rayleigh quotient which, if Gˉ≻0\bar{\mat{G}} \succ 0, lies between 1/λmax⁡(Gˉ)1/\lambda_{\max}(\bar{\mat{G}}) and 1/λmin⁡(Gˉ)1/\lambda_{\min}(\bar{\mat{G}}): an inverse-curvature estimate at the last step’s scale. Without scaling, Hk0=I\mat{H}_k^0 = \mat{I} assumes curvature 11 everywhere and proposed steps have sizes unrelated to the problem; line search spends evaluations correcting them. The cell below measures this: without scaling, L-BFGS with m=10m = 10 takes seven times more iterations on logistic regression and about seventeen times more evaluations on Rosenbrock. (In the two-variable figure it is barely visible because H\mat{H} fills with only two pairs; scaling matters when n≫mn \gg m.)

How much memory is needed?

With m=1m = 1 L-BFGS remembers one pair and resembles nonlinear conjugate gradient. With mm larger than the iteration count (full memory) it forgets nothing and is BFGS, with a difference: BFGS scales once at the start; L-BFGS recalculates scaling each iteration. Between them is diminishing returns, measured in the figure on logistic regression with 600600 variables and 300300 examples whose features decay in scale, giving a multiscale Hessian. Change mm and observe three readings: iterations to ∥∇f∥≤10−6\norm{\grad f} \le 10^{-6}, memory used versus the full matrix, and modeled cost.

InteractiveHow much memory is needed?
Cargando el interactivo…
L-BFGS convergence with memory mm between 11 and 5050 on logistic regression with 600600 variables and 300300 examples. Blue curve is chosen memory, dashed gray curves are m=1m = 1 and full memory. Right, iterations to ∥∇f∥≤10−6\norm{\nabla f} \le 10^{-6} for several mm. With m=1m = 1 it takes 7878; m=5m = 5, 6868; m=10m = 10, 6262; m=20m = 20, 5555; full memory, 5151. Between 1010 and 2020 fewer than 25 %25\,\% extra iterations are lost versus full memory for a fraction of storage. Set gradient cost to '100 times more expensive': extra iterations matter more and memory pays off more. Bottom readings extrapolate to d=106d = 10^6: m=10m = 10 costs 160 MB160\,\text{MB} versus 8 TB8\,\text{TB}.

The message is engineering rather than theory. For mm between 55 and 2020 (SciPy defaults to m=10m = 10), almost all benefit remains, but the right value depends on the problem’s spectrum: more distinct Hessian scales require more pairs to represent. Two qualifications. First, in nonquadratic problems forgetting old pairs does not always hurt, since curvature measured far away may no longer apply; in this logistic problem, however, more memory always helps. Second, L-BFGS theory is more modest than BFGS: Liu and Nocedal proved global R-linear convergence for strongly convex functions, and BFGS superlinear convergence is not generally inherited.

Inexact Newton: solve the system only as much as needed

The other route starts with Newton’s step ∇2f(xk)p=−∇f(xk)\hess f(\vb{x}_k)\vb{p} = -\grad f(\vb{x}_k) and seeks to solve the system without forming the matrix rather than approximate it. Conjugate gradients (numerical methods lesson) solves Ax=b\mat{A}\vb{x} = \vb{b} with A≻0\mat{A} \succ 0 using only products Av\mat{A}\vb{v}. Here A=∇2f(xk)\mat{A} = \hess f(\vb{x}_k) and the product is a Hessian-vector product, computed exactly by automatic differentiation for the cost of a few gradients: Pearlmutter’s (1994) mode composition (forward over reverse), without forming the matrix or finite differences. If unavailable, ∇2f(x)v≈(∇f(x+εv)−∇f(x))/ε\hess f(\vb{x})\vb{v} \approx (\grad f(\vb{x} + \varepsilon\vb{v}) - \grad f(\vb{x}))/\varepsilon costs an extra gradient and loses half the digits.

The second idea is that the system need not be solved accurately. Far from the solution the quadratic model is unreliable and an approximate direction suffices; near it accuracy must increase to preserve Newton’s fast convergence.

Consider the inner loop. Start from z0=0\vb{z}_0 = \vb{0}, r0=∇f(xk)\vb{r}_0 = \grad f(\vb{x}_k) and p0=−r0\vb{p}_0 = -\vb{r}_0. At each iteration jj, compute Hpj\mat{H}\vb{p}_j and curvature pj⊤Hpj\vb{p}_j\T\mat{H}\vb{p}_j:

  • If pj⊤Hpj≤0\vb{p}_j\T\mat{H}\vb{p}_j \le 0, the Hessian is not positive definite in that direction and CG cannot continue (step αj=rj⊤rj/pj⊤Hpj\alpha_j = \vb{r}_j\T\vb{r}_j/\vb{p}_j\T\mat{H}\vb{p}_j minimizes nothing). Return −∇f(xk)-\grad f(\vb{x}_k) if j=0j = 0 and zj\vb{z}_j if j>0j > 0.
  • Otherwise αj=rj⊤rj/pj⊤Hpj\alpha_j = \vb{r}_j\T\vb{r}_j / \vb{p}_j\T\mat{H}\vb{p}_j, zj+1=zj+αjpj\vb{z}_{j+1} = \vb{z}_j + \alpha_j\vb{p}_j, rj+1=rj+αjHpj\vb{r}_{j+1} = \vb{r}_j + \alpha_j\mat{H}\vb{p}_j, and stop if ∥rj+1∥≤ηk∥∇f(xk)∥\norm{\vb{r}_{j+1}} \le \eta_k\norm{\grad f(\vb{x}_k)}. Otherwise pj+1=−rj+1+(∥rj+1∥2/∥rj∥2)pj\vb{p}_{j+1} = -\vb{r}_{j+1} + (\norm{\vb{r}_{j+1}}^2/\norm{\vb{r}_j}^2)\vb{p}_j.

The output always descends, even if H\mat{H} does not. For j≥1j \ge 1, pi⊤r0=pi⊤ri=−∥ri∥2\vb{p}_i\T\vb{r}_0 = \vb{p}_i\T\vb{r}_i = -\norm{\vb{r}_i}^2 by direction conjugacy, so ∇f⊤zj=−∑i<jαi∥ri∥2<0\grad f\T\vb{z}_j = -\sum_{i<j}\alpha_i\norm{\vb{r}_i}^2 < 0 while all αi\alpha_i are positive, as they are because curvature was positive. Apply Armijo backtracking to the output and update the iterate: the method is global even for nonconvex functions. (The Steihaug–Toint trust-region variant follows negative curvature to the boundary rather than stopping; large-scale trust regions use it.)

How accurately to solve: forcing terms

With ηk=0\eta_k = 0 this is exact Newton; with large ηk\eta_k it nearly becomes gradient descent. Theory locates the balance.

(Nocedal and Wright, theorem 7.1; the step error is O(ηk∥ek∥)\bigO(\eta_k\norm{\vb{e}_k}) plus Newton’s usual quadratic error, so ηk→0\eta_k \to 0 replaces linear with superlinear rate.) This orders common choices: ηk=0.5\eta_k = 0.5 gives linear convergence; ηk=min⁡{0.5,∥∇f∥}\eta_k = \min\{0.5, \sqrt{\norm{\grad f}}\} is superlinear, order 1.51.5 if ∇2f\hess f is Lipschitz; ηk=min⁡{0.5,∥∇f∥}\eta_k = \min\{0.5, \norm{\grad f}\} is quadratic but requires system accuracy that rarely pays. The figure compares five criteria on two problems, one convex and one nonconvex.

InteractiveNewton-CG's inner loop
Cargando el interactivo…
Press ▶ to step through outer iterations. Left, CG relative residual ∥rj∥/∥∇f∥\norm{\vb{r}_j}/\norm{\nabla f} in the current outer iteration and forcing tolerance ηk\eta_k (red dashed): CG stops on crossing it. Right, gradient norm versus total work (cumulative Hessian-vector products) for five rules. For logistic regression, ηk=0.5\eta_k = 0.5 gives 2222 outer iterations and 171171 products; nearly exact (η=10−10\eta = 10^{-10}) needs only 1111 outer iterations but about 640640 products; ηk=min⁡{0.5,∥∇f∥}\eta_k = \min\{0.5, \sqrt{\norm{\nabla f}}\} reduces this to about 135135 with the same 1111 outer iterations. Solving accurately costs more than iterating more. Switch to double wells: the Hessian has negative curvature near the origin, stopping CG (table's 'Negative-curvature stops' column) without completing the system.

CG converges in at most rr iterations (exact arithmetic) if the Hessian has rr distinct eigenvalues; with large κ\kappa, residual decreases by a fixed factor every O(κ)\bigO(\sqrt{\kappa}) iterations, not O(κ)\bigO(\kappa): the accelerated rate’s advantage, improved greatly by a good preconditioner (diagonal, block, or L-BFGS itself). Newton-CG pays when Hessian-vector products are cheap and the problem is ill-conditioned or nonconvex: computing Hv\mat{H}\vb{v} in a neural network costs one second-order forward and backward pass. Martens (2010) applied it to deep network training as Hessian-free: replace the indefinite Hessian with the positive semidefinite generalized Gauss-Newton approximation and damp it with a Levenberg-Marquardt variant.

Stochastic gradients: why all this breaks

In deep learning the gradient comes from a minibatch, ∇fB(x)=∇f(x)+ξB\grad f_B(\vb{x}) = \grad f(\vb{x}) + \vb{\xi}_B, with noise ξB\vb{\xi}_B of variance σ2/∣B∣\sigma^2/\abs{B} (minibatch variance). See what happens to curvature measurement:

yk=∇fB′(xk+1)−∇fB(xk)=Gˉksk⏟signal+ξB′−ξB⏟noise.\vb{y}_k = \grad f_{B'}(\vb{x}_{k+1}) - \grad f_{B}(\vb{x}_k) = \underbrace{\bar{\mat{G}}_k\vb{s}_k}_{\text{signal}} + \underbrace{\vb{\xi}_{B'} - \vb{\xi}_B}_{\text{noise}}.

Signal is proportional to the step, ∥sk∥=αk∥dk∥\norm{\vb{s}_k} = \alpha_k\norm{\vb{d}_k}, tiny at small learning rates. Noise does not depend on the step. Once noise exceeds signal, yk\vb{y}_k is random: sk⊤yk\vb{s}_k\T\vb{y}_k changes sign (and with it positivity), and Hk\mat{H}_k learns nonexistent curvature. Two more issues: Wolfe search must compare a function changing with every batch, and memory lets each noisy y\vb{y} contaminate the next mm directions. Known remedies:

  • Use the same batch for both gradients of yk\vb{y}_k: then yk=GˉB,ksk\vb{y}_k = \bar{\mat{G}}_{B,k}\vb{s}_k measures that batch loss’s curvature and inter-batch noise disappears, at the cost of two evaluations per iteration. To avoid paying, use overlapping consecutive batches and calculate yk\vb{y}_k on their intersection (Berahas, Nocedal and Takáč, 2016).
  • Collect pairs less often and with larger batches, using Hessian-vector products on a large batch every LL steps while stepping with small batches (Byrd, Hansen, Nocedal and Singer, 2016).
  • Damp yk\vb{y}_k (Powell’s technique) to force sk⊤yk>0\vb{s}_k\T\vb{y}_k > 0 without skipping the update.
  • Increase batch size to full-batch regime, where L-BFGS becomes reliable again. Common for small networks, inverse problems with a network parameterization and fine-tuning few parameters.
  • Change preconditioner family: Adam (diagonal preconditioning), and at scale, block preconditioners K-FAC and Shampoo, replacing pair memory with statistics averaged across batches.

Stochastic optimization and optimizer-frontier lessons return to this. The practical lesson: L-BFGS rules full-batch problems and stops doing so when gradients are noisy.

What to use and when

SituationReasonable choice
nn in hundreds to a few thousand, exact gradient, high accuracyNewton or BFGS (with Wolfe search)
Large nn (thousands to millions), deterministic gradient, no Hessian-vector productsL-BFGS with mm between 5 and 20
Large nn, cheap Hessian-vector products, ill-conditioning or nonconvexityNewton-CG (forcing tolerance min⁡{0.5,∥∇f∥}\min\{0.5, \sqrt{\norm{\nabla f}}\})
Expensive gradient (simulation, adjoint), few evaluations availableL-BFGS: one gradient evaluation per iteration or slightly more
Stochastic gradient, small batchesGradient descent with momentum or adaptive method (Adam), not unmodified L-BFGS
Box constraintsL-BFGS-B

Implementation from scratch

First, complete BFGS and L-BFGS with strong Wolfe search: bracket the step and refine by bisection. BFGS updates the inverse with the expanded O(n2)\bigO(n^2) form; L-BFGS uses two-loop recursion and forms no matrix. Line search is the only nontrivial component, and without it none of the above holds: without curvature condition s⊤y\vb{s}\T\vb{y} can be negative and the update breaks.

[ ]BFGS and L-BFGS from scratch with Wolfe searchBrowser
import numpy as np
from scipy.optimize import minimize

class Contador:
    """Envuelve (f, grad) y cuenta evaluaciones."""
    def __init__(self, f, grad):
        self.f, self.grad, self.n = f, grad, 0
    def __call__(self, x):
        self.n += 1
        return self.f(x), self.grad(x)

def wolfe(fg, x, fx, gx, d, a=1.0, c1=1e-4, c2=0.9, max_eval=30):
    """Búsqueda de Wolfe fuerte: acotación y zoom por bisección (Nocedal y Wright, 3.5 y 3.6)."""
    dg0 = gx @ d
    a_prev, f_prev = 0.0, fx

    def zoom(lo, f_lo, hi, evals):
        for _ in range(evals):
            a = 0.5 * (lo + hi)
            fa, ga = fg(x + a * d)
            if fa > fx + c1 * a * dg0 or fa >= f_lo:
                hi = a                                  # Armijo falla: el mínimo está en [lo, a]
            else:
                if abs(ga @ d) <= -c2 * dg0:
                    return a, fa, ga                    # Wolfe fuerte cumplido
                if (ga @ d) * (hi - lo) >= 0:
                    hi = lo
                lo, f_lo = a, fa
        return a, fa, ga

    for i in range(max_eval):
        fa, ga = fg(x + a * d)
        if fa > fx + c1 * a * dg0 or (i > 0 and fa >= f_prev):
            return zoom(a_prev, f_prev, a, max_eval)
        if abs(ga @ d) <= -c2 * dg0:
            return a, fa, ga
        if ga @ d >= 0:
            return zoom(a, fa, a_prev, max_eval)
        a_prev, f_prev, a = a, fa, 2 * a                # sigue bajando: ampliar el paso
    return a_prev, fa, ga

def actualiza_inversa(H, s, y):
    """H_{k+1} = (I - rho s y^T) H (I - rho y s^T) + rho s s^T, desarrollada para costar O(n^2) y no O(n^3)."""
    rho = 1.0 / (s @ y)
    Hy = H @ y
    return H - rho * (np.outer(s, Hy) + np.outer(Hy, s)) + (rho * rho * (y @ Hy) + rho) * np.outer(s, s)

def bfgs(fg, x0, tol=1e-6, max_iter=1500):
    """BFGS con actualización de la inversa H_k; devuelve (x, historial de ||g||)."""
    n = len(x0)
    x = np.array(x0, float)
    f, g = fg(x)
    H = np.eye(n)
    hist = [np.linalg.norm(g)]
    for k in range(max_iter):
        if hist[-1] <= tol:
            break
        d = -H @ g
        a, f_new, g_new = wolfe(fg, x, f, g, d)
        s, y = a * d, g_new - g
        sy = s @ y
        if sy > 1e-12 * np.linalg.norm(s) * np.linalg.norm(y):   # salvaguarda: solo con curvatura positiva
            if k == 0:
                H = (sy / (y @ y)) * np.eye(n)                  # escalado del primer par
            H = actualiza_inversa(H, s, y)
        x, f, g = x + s, f_new, g_new
        hist.append(np.linalg.norm(g))
    return x, hist

def dos_bucles(g, S, Y, gamma=None):
    """Calcula H_k g con la recursión de dos bucles, sin formar H_k."""
    q = g.copy()
    alphas = []
    for s, y in zip(reversed(S), reversed(Y)):            # del par más reciente al más antiguo
        a = (s @ q) / (s @ y)
        alphas.append(a)
        q -= a * y
    if gamma is None:
        gamma = (S[-1] @ Y[-1]) / (Y[-1] @ Y[-1]) if S else 1.0   # escalado gamma_k
    r = gamma * q                                          # r = H_k^0 q
    for (s, y), a in zip(zip(S, Y), reversed(alphas)):    # del más antiguo al más reciente
        b = (y @ r) / (s @ y)
        r += (a - b) * s
    return r

def lbfgs(fg, x0, m=10, tol=1e-6, max_iter=1500, escalar=True):
    """L-BFGS: guarda como mucho m pares (s, y). Con escalar=False usa H0 = I en vez de gamma_k I."""
    x = np.array(x0, float)
    f, g = fg(x)
    S, Y = [], []
    hist = [np.linalg.norm(g)]
    for k in range(max_iter):
        if hist[-1] <= tol:
            break
        d = -dos_bucles(g, S, Y, None if escalar else 1.0)
        a, f_new, g_new = wolfe(fg, x, f, g, d)
        s, y = a * d, g_new - g
        if s @ y > 1e-12 * np.linalg.norm(s) * np.linalg.norm(y):
            S.append(s); Y.append(y)
            if len(S) > m:
                S.pop(0); Y.pop(0)
        x, f, g = x + s, f_new, g_new
        hist.append(np.linalg.norm(g))
    return x, hist

Now the benchmark: chained Rosenbrock of dimension 100100 (the same SciPy uses in its documentation) and regularized logistic regression with features at very different scales. Count ff and gradient evaluations, the real-world cost, and compare with scipy.optimize.minimize(method='L-BFGS-B') at the same memory.

[ ]Rosenbrock in dimension 100 and logistic regression versus SciPyBrowser
# --- Problema 1: Rosenbrock encadenada de dimensión 100 ---
def ros_f(x):
    return np.sum(100 * (x[1:] - x[:-1] ** 2) ** 2 + (1 - x[:-1]) ** 2)

def ros_g(x):
    g = np.zeros_like(x)
    t = x[1:] - x[:-1] ** 2
    g[:-1] = -400 * x[:-1] * t - 2 * (1 - x[:-1])
    g[1:] += 200 * t
    return g

# --- Problema 2: regresión logística con regularización ---
rng = np.random.default_rng(0)
n_ej, dim = 400, 50
X = rng.normal(size=(n_ej, dim)) * (1 + np.arange(dim)) ** -0.5   # escalas muy distintas
w_ver = rng.normal(size=dim) * 3
yy = (X @ w_ver + rng.normal(size=n_ej) > 0).astype(float)
lam = 1e-3

def log_f(w):
    z = X @ w
    return np.mean(np.logaddexp(0, z) - yy * z) + 0.5 * lam * w @ w

def log_g(w):
    z = X @ w
    return X.T @ (1 / (1 + np.exp(-z)) - yy) / n_ej + lam * w

def ejecutar(nombre, f, grad, x0):
    filas = []
    for etiqueta, metodo in [("BFGS", lambda fg: bfgs(fg, x0)),
                             ("L-BFGS m=10", lambda fg: lbfgs(fg, x0, m=10)),
                             ("L-BFGS m=3", lambda fg: lbfgs(fg, x0, m=3)),
                             ("L-BFGS m=10, H0 = I", lambda fg: lbfgs(fg, x0, m=10, escalar=False))]:
        fg = Contador(f, grad)
        x, h = metodo(fg)
        filas.append((etiqueta, len(h) - 1, fg.n, f(x), h[-1]))
    r = minimize(f, x0, jac=grad, method="L-BFGS-B", options={"maxcor": 10, "gtol": 1e-6, "ftol": 0})
    filas.append(("SciPy L-BFGS-B m=10", r.nit, r.nfev, r.fun, np.linalg.norm(r.jac)))
    print(f"\n{nombre}")
    print(f"{'método':<24}{'iter':>6}{'evals':>7}{'f final':>14}{'||g||':>11}")
    for e, it, ne, ff, gn in filas:
        print(f"{e:<24}{it:>6}{ne:>7}{ff:>14.6f}{gn:>11.1e}")

x0 = np.full(100, -1.2); x0[1::2] = 1.0
ejecutar("Rosenbrock encadenada, n = 100", ros_f, ros_g, x0)
ejecutar("Regresión logística, 400 ejemplos, 50 variables", log_f, log_g, np.zeros(dim))

# L-BFGS sin olvidar nada: es BFGS con el escalado gamma_k recalculado en cada iteración
fg = Contador(log_f, log_g)
_, h = lbfgs(fg, np.zeros(dim), m=10**6)
print(f"\nL-BFGS con memoria ilimitada en la logística: {len(h) - 1} iteraciones, {fg.n} evaluaciones")

Three readings. First: our implementation and SciPy spend almost the same (about 640640 evaluations versus 620620 on Rosenbrock; 3333 versus 2929 on logistic regression): line search and scaling are correct, with differences due to implementation details. Second: memory is not the only factor. On logistic regression L-BFGS with m=10m = 10 needs fewer than half as many iterations as BFGS (3030 versus 6666), not because forgetting helps: unlimited memory reduces it to 2424 (last line). The difference is the initial matrix. BFGS fixes γ0\gamma_0 using the first pair and carries it throughout; L-BFGS recalculates it each iteration from the newest pair, worth more here than forgotten pairs. On difficult chained Rosenbrock, scaled methods take around five hundred iterations and full BFGS uses slightly fewer evaluations. Third: scaling Hk0\mat{H}_k^0 matters. With Hk0=I\mat{H}_k^0 = \mat{I}, L-BFGS needs 224224 iterations on logistic regression (versus 3030) and over a thousand iterations with about eleven thousand evaluations on Rosenbrock (versus about five hundred and six hundred).

The next cell checks theory on small matrices to roundoff: secant equation, symmetry and positivity; cheap formula matches Vi\mat{V}_i factors; BFGS inverts the rank-two B\mat{B} update; variational minimality (the proof’s Pythagorean identity, with a thousand feasible competitors); termination in nn steps on a quadratic; and two-loop recursion reproduces multiplication by the full matrix.

[ ]Check theory: secant, positivity, minimum change and two loopsBrowser
rng = np.random.default_rng(1)
n = 6

def actualiza_V(H, s, y):
    """La fórmula con los factores V = I - rho y s^T escritos tal cual (cuesta O(n^3): solo para comprobar)."""
    rho = 1 / (s @ y)
    V = np.eye(len(s)) - rho * np.outer(y, s)
    return V.T @ H @ V + rho * np.outer(s, s)

# Un par (s, y) con curvatura positiva: y = G s con G definida positiva (el "hessiano medio")
M = rng.normal(size=(n, n)); G = M @ M.T + 0.5 * np.eye(n)
s = rng.normal(size=n); y = G @ s
M = rng.normal(size=(n, n)); Hk = M @ M.T + 0.5 * np.eye(n)     # H_k simétrica definida positiva
H1 = actualiza_inversa(Hk, s, y)
print("fórmula barata frente a la de los factores V: ", np.abs(H1 - actualiza_V(Hk, s, y)).max())

# 1) La ecuación secante, la simetría y la positividad
print("ecuación secante  ||H1 y - s||    =", np.linalg.norm(H1 @ y - s))
print("simetría          ||H1 - H1^T||   =", np.linalg.norm(H1 - H1.T))
print("autovalor mínimo de H1             =", np.linalg.eigvalsh(H1).min())

# 2) Es la inversa de la actualización de rango dos de B = H^{-1}
B = np.linalg.inv(Hk)
B1 = B - np.outer(B @ s, B @ s) / (s @ B @ s) + np.outer(y, y) / (s @ y)
print("H1 = inv(B1)?     max |H1 inv(B1) - I| =", np.abs(H1 @ B1 - np.eye(n)).max())

# 3) Mínima variación: entre las H simétricas con H y = s, BFGS es la más cercana a H_k en la norma ponderada
#    ||A||_W = ||W^(1/2) A W^(1/2)||_F con W = G (el hessiano medio, W s = y). Cualquier competidora
#    H1 + D, con D simétrica y D y = 0, está más lejos exactamente en ||D||_W (Pitágoras).
L = np.linalg.cholesky(G)
def dist2(H):
    return np.linalg.norm(L.T @ H @ L, "fro") ** 2
Z = np.linalg.svd(y.reshape(1, -1))[2][1:].T                    # base del complemento ortogonal de y
exceso = []
for _ in range(1000):
    E = rng.normal(size=(n - 1, n - 1)); E = (E + E.T) / 2
    D = Z @ E @ Z.T
    assert np.allclose((H1 + D) @ y, s)                          # competidora factible
    exceso.append(dist2(H1 + D - Hk) - dist2(H1 - Hk) - dist2(D))
print(f"||H1 - H_k||_W = {np.sqrt(dist2(H1 - Hk)):.4f};  desviación máxima de la identidad de Pitágoras en 1000 competidoras: {np.abs(exceso).max():.1e}")

# 4) Terminación finita en una cuadrática con búsqueda exacta: n pasos y H_n = A^{-1}
A = G
b = rng.normal(size=n)
x = np.zeros(n); g = A @ x - b; H = np.eye(n)
for k in range(n):
    d = -H @ g
    a = -(g @ d) / (d @ A @ d)                                   # paso exacto en una cuadrática
    s_k = a * d; g_new = A @ (x + s_k) - b; y_k = g_new - g
    H = actualiza_inversa(H, s_k, y_k)
    x, g = x + s_k, g_new
print("tras n pasos exactos: ||g|| =", np.linalg.norm(g), "  ||H - A^{-1}|| =", np.linalg.norm(H - np.linalg.inv(A)))

# 5) La recursión de dos bucles reproduce H_k g con la matriz completa, sin formarla
m = 5
S, Y = [], []
x_ = rng.normal(size=n)
for _ in range(m):
    s_ = rng.normal(size=n); S.append(s_); Y.append(A @ s_ + 0.01 * rng.normal(size=n))
gamma = (S[-1] @ Y[-1]) / (Y[-1] @ Y[-1])
Hd = gamma * np.eye(n)
for s_, y_ in zip(S, Y):
    Hd = actualiza_inversa(Hd, s_, y_)                                 # H_k = actualización encadenada desde gamma I
g = rng.normal(size=n)
print("dos bucles frente a matriz completa:", np.linalg.norm(Hd @ g - dos_bucles(g, S, Y)))

Newton-CG from scratch

Now Newton-CG: the previous section’s truncated conjugate gradient with negative-curvature detection, and an outer loop with Armijo backtracking. Apply it to the same logistic regression with three forcing terms, and to a nonconvex coupled double-well function to see negative curvature detected without breaking anything.

[ ]Newton-CG from scratch with negative curvatureBrowser
def cg_truncado(hvp, g, eta, max_inner=200):
    """Gradiente conjugado truncado para H p = -g. Devuelve (p, productos H v usados, motivo)."""
    z = np.zeros_like(g)
    r = g.copy()                     # residuo de H z + g en z = 0
    p = -r
    gn = np.linalg.norm(g)
    for j in range(max_inner):
        Hp = hvp(p)
        curv = p @ Hp
        if curv <= 1e-12 * (p @ p):                  # curvatura no positiva: H no es definida positiva en esta dirección
            return (p if j == 0 else z), j + 1, "curvatura negativa"
        a = (r @ r) / curv
        z = z + a * p
        r_nuevo = r + a * Hp
        if np.linalg.norm(r_nuevo) <= eta * gn:      # tolerancia forzada
            return z, j + 1, "tolerancia"
        p = -r_nuevo + (r_nuevo @ r_nuevo) / (r @ r) * p
        r = r_nuevo
    return z, max_inner, "tope"

def newton_cg(f, grad, hvp_en, x0, forcing, tol=1e-8, max_outer=100):
    """Newton-CG con retroceso de Armijo. hvp_en(x) devuelve la función v -> H(x) v."""
    x = np.array(x0, float)
    historial, usados = [], 0
    for k in range(max_outer):
        g = grad(x)
        gn = np.linalg.norm(g)
        if gn <= tol:
            break
        p, nh, motivo = cg_truncado(hvp_en(x), g, forcing(gn))
        t, fx = 1.0, f(x)
        while f(x + t * p) > fx + 1e-4 * t * (g @ p) and t > 1e-12:
            t *= 0.5
        x = x + t * p
        usados += nh
        historial.append((nh, motivo))
    return x, k, usados, historial

# Regresión logística de la celda anterior: log_f, log_g, X, lam
def log_hvp_en(w):
    s = 1 / (1 + np.exp(-(X @ w)))
    D = s * (1 - s)
    return lambda v: X.T @ (D * (X @ v)) / n_ej + lam * v

reglas = {
    "η = 0.5": lambda gn: 0.5,
    "η = min(0.5, √‖g‖)": lambda gn: min(0.5, np.sqrt(gn)),
    "η = 1e-10 (casi exacto)": lambda gn: 1e-10,
}
print(f"{'tolerancia forzada':<26}{'externas':>9}{'prods H·v':>11}{'||g||':>10}")
for nombre, eta in reglas.items():
    x, it, nh, _ = newton_cg(log_f, log_g, log_hvp_en, np.zeros(dim), eta)
    print(f"{nombre:<26}{it:>9}{nh:>11}{np.linalg.norm(log_g(x)):>10.1e}")

# Con curvatura negativa: pozos dobles acoplados, f = sum (x^2 - 1)^2 / 4 + 0.25 sum (x_{i+1} - x_i)^2
def pozo_f(x):
    return np.sum((x ** 2 - 1) ** 2) / 4 + 0.25 * np.sum(np.diff(x) ** 2)

def pozo_g(x):
    g = x * (x ** 2 - 1)
    dx = np.diff(x)
    g[:-1] -= 0.5 * dx
    g[1:] += 0.5 * dx
    return g

def pozo_hvp_en(x):
    def hv(v):
        r = (3 * x ** 2 - 1) * v
        dv = np.diff(v)
        r[:-1] -= 0.5 * dv
        r[1:] += 0.5 * dv
        return r
    return hv

x0 = 0.05 * np.random.default_rng(3).normal(size=30)       # cerca del punto de silla x = 0
x, it, nh, hist = newton_cg(pozo_f, pozo_g, pozo_hvp_en, x0, lambda gn: min(0.5, np.sqrt(gn)))
motivos = [m for _, m in hist]
print(f"\npozos dobles (n = 30), arranque cerca de la silla: {it} externas, {nh} prods H·v, ||g|| = {np.linalg.norm(pozo_g(x)):.1e}")
print("iteraciones externas cortadas por curvatura negativa:", motivos.count("curvatura negativa"), "de", len(motivos))

def hessiano(x):
    H = np.column_stack([pozo_hvp_en(x)(e) for e in np.eye(len(x))])
    return (H + H.T) / 2
print(f"menor autovalor del hessiano: {np.linalg.eigvalsh(hessiano(x0)).min():.3f} en el arranque, {np.linalg.eigvalsh(hessiano(x)).min():.3f} en el punto final")

Logistic regression confirms the figure: fixed tolerance 0.50.5 takes three times as many outer iterations; nearly exact takes the same iterations as decreasing tolerance but five times as many Hessian-vector products; decreasing min⁡{0.5,∥∇f∥}\min\{0.5, \sqrt{\norm{\nabla f}}\} is best in work. On double wells, starting from a tiny perturbation of saddle x=0\vb{x} = \vb{0} (where the Hessian has negative eigenvalues), CG stops for negative curvature in 66 of 1515 outer iterations and the method finishes at a local minimum: the smallest Hessian eigenvalue changes from −0.993-0.993 initially to 0.2970.297 at the end.

With autograd: Newton-CG in PyTorch

In a neural network no formula is available for the Hessian-vector product, but none is needed: differentiate twice. Compute the gradient retaining the graph, create_graph=True, and backpropagate scalar g⊤v\vb{g}\T\vb{v}: its parameter gradient is exactly ∇2f v\hess f\,\vb{v}, without forming the matrix and at the cost of a couple of backward passes. Compare torch.optim.LBFGS (strong Wolfe search) and Adam on a small full-batch MLP. This local cell needs PyTorch. The network is tiny and runs on CPU (device placement: change DEVICE to "cuda" to compare GPU times), and second-order derivatives use autograd’s dynamic graph.

[ ]Newton-CG with autograd versus L-BFGS and Adam in PyTorchLocal GPU
import time
import numpy as np
import torch
from torch import nn

torch.set_num_threads(2)
DEVICE = "cpu"            # con GPU: "cuda". La red es diminuta y en CPU ya va sobrada
torch.manual_seed(0)

# Regresión de una función oscilante con un MLP pequeño; lote completo y doble precisión
x = torch.linspace(-3, 3, 200, dtype=torch.float64, device=DEVICE).unsqueeze(1)
y = torch.sin(2 * x) + 0.3 * x
red = nn.Sequential(nn.Linear(1, 24), nn.Tanh(), nn.Linear(24, 24), nn.Tanh(), nn.Linear(24, 1)).double().to(DEVICE)
params = list(red.parameters())
n_par = sum(p.numel() for p in params)
estado0 = [p.detach().clone() for p in params]

def reiniciar():
    with torch.no_grad():
        for p, q in zip(params, estado0):
            p.copy_(q)

def perdida():
    return 0.5 * ((red(x) - y) ** 2).mean()

def plano(ts):
    return torch.cat([t.reshape(-1) for t in ts])

def poner(v):
    i = 0
    with torch.no_grad():
        for p in params:
            p.copy_(v[i:i + p.numel()].view_as(p)); i += p.numel()

def grad_y_hvp():
    """Devuelve g (plano) y una función v -> H v por doble retropropagación (Pearlmutter sin formar H)."""
    L = perdida()
    g = torch.autograd.grad(L, params, create_graph=True)
    gf = plano(g)
    def hvp(v):
        # d(g.v)/dw = H v: se retropropaga otra vez el escalar g.v, reutilizando el grafo de g
        return plano(torch.autograd.grad(gf @ v, params, retain_graph=True))
    return L.item(), gf.detach(), hvp

def cg_truncado(hvp, g, eta, max_inner=100):
    z = torch.zeros_like(g); r = g.clone(); p = -r
    for j in range(max_inner):
        Hp = hvp(p)
        curv = p @ Hp
        if curv <= 1e-12 * (p @ p):
            return (p if j == 0 else z), j + 1
        a = (r @ r) / curv
        z = z + a * p
        r_nuevo = r + a * Hp
        if r_nuevo.norm() <= eta * g.norm():
            return z, j + 1
        p = -r_nuevo + (r_nuevo @ r_nuevo) / (r @ r) * p
        r = r_nuevo
    return z, max_inner

def newton_cg_torch(max_outer=60, tol=1e-6):
    reiniciar()
    hv_total, hist = 0, []
    t0 = time.perf_counter()
    for k in range(max_outer):
        f, g, hvp = grad_y_hvp()
        hist.append(f)
        if g.norm() <= tol:
            break
        p, nh = cg_truncado(hvp, g, min(0.5, g.norm().sqrt().item()))
        hv_total += nh
        w0, t = plano([q.detach() for q in params]), 1.0
        while True:                                          # retroceso de Armijo
            poner(w0 + t * p)
            if perdida().item() <= f + 1e-4 * t * (g @ p).item() or t < 1e-10:
                break
            t *= 0.5
    return hist, hv_total, time.perf_counter() - t0, g.norm().item()

def lbfgs_torch(max_iter=400):
    reiniciar()
    opt = torch.optim.LBFGS(params, lr=1, max_iter=max_iter, history_size=10, line_search_fn="strong_wolfe",
                            tolerance_grad=1e-6, tolerance_change=1e-14)
    n_eval = [0]
    def cierre():
        opt.zero_grad(); L = perdida(); L.backward(); n_eval[0] += 1
        return L
    t0 = time.perf_counter()
    opt.step(cierre)
    return perdida().item(), n_eval[0], time.perf_counter() - t0

def adam_torch(pasos=3000, lr=1e-2):
    reiniciar()
    opt = torch.optim.Adam(params, lr=lr)
    t0 = time.perf_counter()
    for _ in range(pasos):
        opt.zero_grad(); perdida().backward(); opt.step()
    return perdida().item(), pasos, time.perf_counter() - t0

hist, nh, t_ncg, gn = newton_cg_torch()
f_lb, ev_lb, t_lb = lbfgs_torch()
f_ad, ev_ad, t_ad = adam_torch()
print(f"MLP con {n_par} parámetros, {DEVICE}, doble precisión")
print(f"{'método':<11}{'pérdida final':>14}{'gradientes':>12}{'prods H·v':>11}{'tiempo (s)':>12}")
print(f"{'Newton-CG':<11}{hist[-1]:>14.2e}{len(hist):>12}{nh:>11}{t_ncg:>12.2f}")
print(f"{'L-BFGS':<11}{f_lb:>14.2e}{ev_lb:>12}{0:>11}{t_lb:>12.2f}")
print(f"{'Adam':<11}{f_ad:>14.2e}{ev_ad:>12}{0:>11}{t_ad:>12.2f}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

With 673673 parameters, all three reach loss of order 10−610^{-6}, between 7×10−77 \times 10^{-7} and 5×10−65 \times 10^{-6} (Newton-CG, capped at 6060 outer iterations, goes lowest), but their costs differ: Newton-CG performs 6060 gradients and about 450450 Hessian-vector products (each worth several gradients), L-BFGS about 450450 gradient evaluations, Adam 30003000 steps. Timings are not a general conclusion (they depend on machine and size, and here everything is full-batch double precision), but the theoretical lesson holds: in full batch, Newton-CG and L-BFGS arrive with a fraction of first-order steps; with stochastic batches none of this holds, and Adam returns.

Common mistakes

Exercises

ProofBFGS preserves positive definiteness
Prove: Let H≻0\mat{H} \succ 0 and s⊤y>0\vb{s}\T\vb{y} > 0. Then H+=(I−ρsy⊤) H (I−ρys⊤)+ρss⊤\mat{H}_{+} = (\mat{I} - \rho\vb{s}\vb{y}\T)\,\mat{H}\,(\mat{I} - \rho\vb{y}\vb{s}\T) + \rho\vb{s}\vb{s}\T, with ρ=1/(y⊤s)\rho = 1/(\vb{y}\T\vb{s}), is positive definite.
0
Let arbitrary v≠0\vb{v} \neq \vb{0} and u=(I−ρys⊤)v=v−ρ(s⊤v)y\vb{u} = (\mat{I} - \rho\vb{y}\vb{s}\T)\vb{v} = \vb{v} - \rho(\vb{s}\T\vb{v})\vb{y}.

Step 1 of 4. How do you write v⊤H+v\vb{v}\T\mat{H}_{+}\vb{v}?

ProofWolfe curvature gives $\vb{s}\T\vb{y} > 0$
Prove: Let d\vb{d} be a descent direction at x\vb{x}, i.e. ∇f(x)⊤d<0\grad f(\vb{x})\T\vb{d} < 0, and let α>0\alpha > 0 satisfy strong Wolfe curvature, ∣∇f(x+αd)⊤d∣≤c2∣∇f(x)⊤d∣\abs{\grad f(\vb{x} + \alpha\vb{d})\T\vb{d}} \le c_2\abs{\grad f(\vb{x})\T\vb{d}} with 0<c2<10 < c_2 < 1. Then s⊤y>0\vb{s}\T\vb{y} > 0 with s=αd\vb{s} = \alpha\vb{d} and y=∇f(x+s)−∇f(x)\vb{y} = \grad f(\vb{x} + \vb{s}) - \grad f(\vb{x}).
0
Write g=∇f(x)\vb{g} = \grad f(\vb{x}) and g+=∇f(x+αd)\vb{g}_{+} = \grad f(\vb{x} + \alpha\vb{d}).

Step 1 of 4. What does strong curvature say about g+⊤d\vb{g}_{+}\T\vb{d}, knowing g⊤d<0\vb{g}\T\vb{d} < 0?

CodeThe two-loop recursion
Implement two_loop_recursion(grad, s_list, y_list), returning Hkg\mat{H}_k\vb{g} for vector grad using L-BFGS two-loop recursion. s_list and y_list contain pairs (si,yi)(\vb{s}_i, \vb{y}_i) from oldest to newest (at most mm pairs, all with si⊤yi>0\vb{s}_i\T\vb{y}_i > 0). Use Hk0=γI\mat{H}_k^0 = \gamma\mat{I} with γ=s⊤y/y⊤y\gamma = \vb{s}\T\vb{y}/\vb{y}\T\vb{y} from the newest pair, and γ=1\gamma = 1 if no pairs exist. Do not form an n×nn \times n matrix or modify inputs.
import numpy as np

def two_loop_recursion(grad, s_list, y_list):
  """Devuelve H_k @ grad con la recursión de dos bucles. Pares de más antiguo a más reciente."""
  q = grad.copy()
  # tu código: primer bucle (del más reciente al más antiguo), H0 = gamma I, segundo bucle
  return q
Shift+Enter to run
QuizL-BFGS with small minibatches
You train a deep network with L-BFGS, calculating each gradient on a different minibatch of 32 examples, and loss oscillates without falling. What is the main explanation?
QuizChoose a method
Fit 3×1063 \times 10^6 parameters of a deterministic physical model. Each gradient evaluation (by the adjoint method) costs several minutes and Hessian-vector products are unavailable. Which method would you use?
QuizNegative curvature inside CG
When applying CG to Newton's system with a possibly indefinite Hessian, which statements are true?

More than one answer may be correct.

NumericBFGS versus L-BFGS memory
With n=106n = 10^6 parameters, how many times more numbers does BFGS store (full n×nn \times n matrix Hk\mat{H}_k, without exploiting symmetry) than L-BFGS with m=10m = 10 (storing mm pairs (si,yi)(\vb{s}_i, \vb{y}_i) of length nn)?
NumericA BFGS update by hand
With H0=I\mat{H}_0 = \mat{I} (dimension 2), s=(1,2)\vb{s} = (1, 2) and y=(3,1)\vb{y} = (3, 1), calculate BFGS update H1\mat{H}_1 and give the second component of direction −H1g-\mat{H}_1\vb{g} for g=(1,−1)\vb{g} = (1, -1).
NumericCG iterations with few eigenvalues
A quadratic problem's Hessian is 1000×10001000 \times 1000 and positive definite, but has only 4 distinct eigenvalues. In exact arithmetic, how many CG iterations at most are needed to solve Newton's system from p=0\vb{p} = \vb{0}?

Summary

Key idea
Curvature is measured, not calculated: BFGS converts each pair (s,y)(\vb{s}, \vb{y}) into the smallest rank-two correction satisfying the secant equation, preserving positivity when Wolfe search guarantees s⊤y>0\vb{s}\T\vb{y} > 0; L-BFGS keeps only mm pairs and applies Hk\mat{H}_k in two loops; Newton-CG avoids the matrix by solving Newton’s system with Hessian-vector products and a tolerance tightened as the gradient falls. All three depend on gradients being free of noise.
  • The secant equation Bk+1sk=yk\mat{B}_{k+1}\vb{s}_k = \vb{y}_k states what a step teaches and is compatible with a positive definite matrix iff sk⊤yk>0\vb{s}_k\T\vb{y}_k > 0. Wolfe curvature (strong or weak) guarantees this; Armijo does not.
  • BFGS uniquely solves min⁡∥H−Hk∥W\min\norm{\mat{H} - \mat{H}_k}_{\mat{W}} with H=H⊤\mat{H} = \mat{H}\T and Hyk=sk\mat{H}\vb{y}_k = \vb{s}_k. It costs O(n2)\bigO(n^2) memory and work, converges superlinearly (Dennis–Moré: it only needs the Hessian right along the step) and terminates in nn steps on a quadratic with exact search.
  • L-BFGS reconstructs Hkg\mat{H}_k\vb{g} by two-loop recursion in O(mn)\bigO(mn) without forming a matrix; scale Hk0=γkI\mat{H}_k^0 = \gamma_k\mat{I} with γk=s⊤y/y⊤y\gamma_k = \vb{s}\T\vb{y}/\vb{y}\T\vb{y}. mm between 55 and 2020 is often enough but depends on the spectrum; its theory is weaker than BFGS (R-linear).
  • Newton-CG solves ∇2f p=−∇f\hess f\,\vb{p} = -\grad f with truncated conjugate gradients: it uses only Hessian-vector products (via double backpropagation), stops on forcing tolerance or nonpositive curvature, and always returns a descent direction. With ηk→0\eta_k \to 0 convergence is superlinear; ηk=min⁡{0.5,∥∇f∥}\eta_k = \min\{0.5, \sqrt{\norm{\grad f}}\} is the practical choice.
  • With minibatch gradients, yk\vb{y}_k contains noise from different batches and both families become unreliable: use the same batch in both gradients, large batches or damping. In stochastic deep learning an adaptive preconditioner (Adam, Shampoo, K-FAC) is the alternative, discussed in later lessons.