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 system. With parameters, a small network, a double-precision Hessian occupies bytes, eight terabytes, and Cholesky factorization costs 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 and observed gradient change 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 cannot be formed, 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:
| Method | Memory | Work per iteration | Local convergence |
|---|---|---|---|
| Newton | quadratic | ||
| BFGS | superlinear | ||
| L-BFGS (memory ) | linear (R-linear proven) | ||
| Newton-CG | Hessian-vector products | superlinear or quadratic with adjusted tolerance | |
| Gradient descent | 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 ‘s second derivative by and uses it instead of in Newton’s step. It converges with order : slower than Newton’s quadratic rate, but without second derivatives and with one evaluation per step. In several variables this quotient is a vector equality. Let and
By the fundamental theorem of calculus applied to ,
The pair gives the average Hessian along the segment applied to direction and nothing more: one column of information ( numbers) about a matrix with . We ask the new Hessian approximation to agree with what was observed.
The curvature condition is essential. If must be positive definite (so descends), multiplying the secant equation by gives , which must be positive. Conversely:
Proof
() since . () Take
It is symmetric and . For , , where projects orthogonally onto . It vanishes only if , i.e. , and also , forcing .
∎The figure shows the secant equation in one variable in detail. Below is : in one dimension curvature is its slope. The secant between the two gradients is the magenta line, whose slope averages 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 , excluded by a line search with Wolfe’s curvature condition but not by Armijo.
The secant equation gives equations for unknowns (entries of a symmetric matrix): once 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 instead of , because search direction is and no system needs solving. Among symmetric matrices satisfying the inverse secant equation, choose closest to in weighted Frobenius norm , with positive definite and (e.g. average Hessian ). This weight makes the result independent of variable units.
Proof
Write without subscripts and for the formula’s matrix.
Feasibility. It is symmetric. Since , the first term vanishes on and .
Orthogonality to feasible directions. The norm’s inner product is . Expanding,
Multiplying on both sides by and using yields a matrix of form , with . Any other feasible matrix is with symmetric and , so .
Pythagoras. Thus , greater unless .
∎The proof says more: any other matrix satisfying the secant is farther from by exactly , checked against a thousand competitors in the cell below. About the formula:
- It is a rank-two correction. has rank at most two: only what pair contributes changes. Expanded, with , costing (one matrix-vector and two outer products), not like direct matrix multiplication.
- It is the inverse of another rank-two correction. By Sherman–Morrison–Woodbury, satisfies
The first term removes ‘s curvature in direction and the second inserts the measurement.
- It preserves positive definiteness. This makes the method usable; prove it in the first exercise:
Thus is always a descent direction: . We must guarantee , which is what the Wolfe curvature condition does: with , condition with implies (second exercise). Armijo backtracking is insufficient: it accepts steps so short or long that can be negative, as in the previous figure.
The algorithm
Trying first is essential: this is Newton’s step and enables superlinear convergence. With the first step is gradient descent. Standard practice rescales 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 for the true matrix (gray) and approximation (blue). It starts as a circle: it knows nothing. Each update deforms it and, on the quadratic where , it matches the true one along the last step: the secant equation made visible. (On Rosenbrock 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 advances orange leaves teal and approaches gray.
The figure’s last lesson is subtle and central to convergence theory: need not converge to . 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 , while superlinear convergence rests on a useful Dennis–Moré characterization.
This conditions along the step direction, not the entire matrix. It formalizes the figure’s observation and explains why one pair 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 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 iterations and . In the figure, exact search finishes the dimension- quadratic in two steps.
L-BFGS: forget to scale
BFGS needs numbers and operations per iteration. At that is 80 GB. Nocedal’s (1980) observation: is defined by and the applied pairs ; the matrix is merely a cache. Keeping only the most recent pairs and reconstructing by applying them to a simple initial matrix gives limited-memory L-BFGS (Liu and Nocedal, 1989): stored numbers and, as shown below, operations per iteration, never forming an matrix.
The two-loop recursion
Write , so BFGS is . Unrolling steps,
Each is identity minus an outer product: applying it to a vector costs a dot product and an axpy, . Thus calculate by traversing pairs twice: newest to oldest applying , and oldest to newest applying and adding terms.
Each loop uses one dot product and one axpy per pair: about multiplications and as many additions total. L-BFGS direction is with exactly BFGS’s Wolfe search. By the preceding formula, output matches multiplication by the matrix BFGS would build starting from and applying the pairs: the cell below checks this to roundoff.
Initial matrix and scaling
The only freedom is , an often neglected ingredient. Standard choice is with
With , is a generalized Rayleigh quotient which, if , lies between and : an inverse-curvature estimate at the last step’s scale. Without scaling, assumes curvature 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 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 fills with only two pairs; scaling matters when .)
How much memory is needed?
With L-BFGS remembers one pair and resembles nonlinear conjugate gradient. With 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 variables and examples whose features decay in scale, giving a multiscale Hessian. Change and observe three readings: iterations to , memory used versus the full matrix, and modeled cost.
The message is engineering rather than theory. For between and (SciPy defaults to ), 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 and seeks to solve the system without forming the matrix rather than approximate it. Conjugate gradients (numerical methods lesson) solves with using only products . Here 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, 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 , and . At each iteration , compute and curvature :
- If , the Hessian is not positive definite in that direction and CG cannot continue (step minimizes nothing). Return if and if .
- Otherwise , , , and stop if . Otherwise .
The output always descends, even if does not. For , by direction conjugacy, so while all 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 this is exact Newton; with large it nearly becomes gradient descent. Theory locates the balance.
(Nocedal and Wright, theorem 7.1; the step error is plus Newton’s usual quadratic error, so replaces linear with superlinear rate.) This orders common choices: gives linear convergence; is superlinear, order if is Lipschitz; is quadratic but requires system accuracy that rarely pays. The figure compares five criteria on two problems, one convex and one nonconvex.
CG converges in at most iterations (exact arithmetic) if the Hessian has distinct eigenvalues; with large , residual decreases by a fixed factor every iterations, not : 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 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, , with noise of variance (minibatch variance). See what happens to curvature measurement:
Signal is proportional to the step, , tiny at small learning rates. Noise does not depend on the step. Once noise exceeds signal, is random: changes sign (and with it positivity), and learns nonexistent curvature. Two more issues: Wolfe search must compare a function changing with every batch, and memory lets each noisy contaminate the next directions. Known remedies:
- Use the same batch for both gradients of : then 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 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 steps while stepping with small batches (Byrd, Hansen, Nocedal and Singer, 2016).
- Damp (Powell’s technique) to force 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
| Situation | Reasonable choice |
|---|---|
| in hundreds to a few thousand, exact gradient, high accuracy | Newton or BFGS (with Wolfe search) |
| Large (thousands to millions), deterministic gradient, no Hessian-vector products | L-BFGS with between 5 and 20 |
| Large , cheap Hessian-vector products, ill-conditioning or nonconvexity | Newton-CG (forcing tolerance ) |
| Expensive gradient (simulation, adjoint), few evaluations available | L-BFGS: one gradient evaluation per iteration or slightly more |
| Stochastic gradient, small batches | Gradient descent with momentum or adaptive method (Adam), not unmodified L-BFGS |
| Box constraints | L-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 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 can be negative and the update breaks.
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, histNow the benchmark: chained Rosenbrock of dimension (the same SciPy uses in its documentation) and regularized logistic regression with features at very different scales. Count and gradient evaluations, the real-world cost, and compare with scipy.optimize.minimize(method='L-BFGS-B') at the same memory.
# --- 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 evaluations versus on Rosenbrock; versus 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 needs fewer than half as many iterations as BFGS ( versus ), not because forgetting helps: unlimited memory reduces it to (last line). The difference is the initial matrix. BFGS fixes 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 matters. With , L-BFGS needs iterations on logistic regression (versus ) 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 factors; BFGS inverts the rank-two update; variational minimality (the proof’s Pythagorean identity, with a thousand feasible competitors); termination in steps on a quadratic; and two-loop recursion reproduces multiplication by the full matrix.
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.
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 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 is best in work. On double wells, starting from a tiny perturbation of saddle (where the Hessian has negative eigenvalues), CG stops for negative curvature in of outer iterations and the method finishes at a local minimum: the smallest Hessian eigenvalue changes from initially to 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 : its parameter gradient is exactly , 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.
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}")npm run lab and open the connection link.With parameters, all three reach loss of order , between and (Newton-CG, capped at outer iterations, goes lowest), but their costs differ: Newton-CG performs gradients and about Hessian-vector products (each worth several gradients), L-BFGS about gradient evaluations, Adam 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
Step 1 of 4. How do you write ?
Step 1 of 4. What does strong curvature say about , knowing ?
two_loop_recursion(grad, s_list, y_list), returning for vector grad using L-BFGS two-loop recursion. s_list and y_list contain pairs from oldest to newest (at most pairs, all with ). Use with from the newest pair, and if no pairs exist. Do not form an 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 qMore than one answer may be correct.
Summary
- The secant equation states what a step teaches and is compatible with a positive definite matrix iff . Wolfe curvature (strong or weak) guarantees this; Armijo does not.
- BFGS uniquely solves with and . It costs memory and work, converges superlinearly (Dennis–Moré: it only needs the Hessian right along the step) and terminates in steps on a quadratic with exact search.
- L-BFGS reconstructs by two-loop recursion in without forming a matrix; scale with . between and is often enough but depends on the spectrum; its theory is weaker than BFGS (R-linear).
- Newton-CG solves 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 convergence is superlinear; is the practical choice.
- With minibatch gradients, 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.