Limited-Memory BFGS
BFGS stores an matrix. With a million variables that is numbers, far too many. L-BFGS keeps only the last pairs , typically between 5 and 20, and reconstructs the product from them on the fly. Memory and time per iteration drop to , and the method keeps most of BFGS's speed.
The two-loop recursion
Unrolling the BFGS update times shows that can be computed from the stored pairs and an initial matrix with two passes over the history:
q = gradient
for i = k-1 down to k-m: (newest to oldest)
alpha_i = rho_i * s_i . q
q = q - alpha_i * y_i
r = gamma * q gamma = s_{k-1} . y_{k-1} / y_{k-1} . y_{k-1}
for i = k-m up to k-1: (oldest to newest)
beta = rho_i * y_i . r
r = r + s_i * (alpha_i - beta)
direction = -rThe scaling estimates the size of the inverse Hessian along the most recent direction, so a step of length 1 is usually accepted.
import numpy as np
from collections import deque
from scipy.optimize import line_search
def lbfgs(f, grad, x, m=5, tol=1e-6, max_iter=1000):
S, Y = deque(maxlen=m), deque(maxlen=m)
g = grad(x)
for k in range(max_iter):
if np.linalg.norm(g) < tol:
return x, k
q = g.copy(); alphas = []
for s, y in reversed(list(zip(S, Y))):
a = (s @ q) / (y @ s); alphas.append(a); q -= a * y
r = q * ((S[-1] @ Y[-1]) / (Y[-1] @ Y[-1]) if S else 1e-3)
for (s, y), a in zip(zip(S, Y), reversed(alphas)):
b = (y @ r) / (y @ s); r += s * (a - b)
p = -r
t = line_search(f, grad, x, p, gfk=g)[0] or 1e-3
x_new = x + t * p; g_new = grad(x_new)
S.append(x_new - x); Y.append(g_new - g)
x, g = x_new, g_new
return x, max_iter
# extended Rosenbrock in 1000 dimensions: sum of 500 independent valleys
def f(x):
a, b = x[0::2], x[1::2]
return np.sum((1 - a)**2 + 100 * (b - a**2)**2)
def grad(x):
a, b = x[0::2], x[1::2]; g = np.empty_like(x)
g[0::2] = -2 * (1 - a) - 400 * a * (b - a**2); g[1::2] = 200 * (b - a**2)
return g
x0 = np.tile([-1.2, 1.0], 500)
x, iters = lbfgs(f, grad, x0)
print("n =", x.size, " iterations:", iters, " all coordinates within 1e-8 of 1:", bool(np.abs(x - 1).max() < 1e-8))n = 1000 iterations: 38 all coordinates within 1e-8 of 1: True
A full BFGS matrix here would hold a million numbers; L-BFGS stores 10 vectors of length 1000.
Choosing
Larger captures more curvature but costs more per iteration, and the returns diminish. Here is an ill-conditioned problem in 1000 variables (a quadratic with curvatures from 1 to 1000 plus a quartic coupling between neighbours):
import numpy as np
from scipy.optimize import minimize
n = 1000
d = np.linspace(1, 1000, n)
def f(x):
return 0.5 * np.sum(d * x * x) + 0.25 * np.sum((x[1:] - x[:-1])**4) - x.sum()
def grad(x):
g = d * x - 1.0; t = (x[1:] - x[:-1])**3
g[1:] += t; g[:-1] -= t
return g
for m in (1, 3, 10, 30, 100):
r = minimize(f, np.zeros(n), jac=grad, method="L-BFGS-B",
options={"maxcor": m, "gtol": 1e-6, "ftol": 0, "maxiter": 20000})
print(f"m = {m:3d}: {r.nit:4d} iterations")m = 1: 313 iterations
m = 3: 228 iterations
m = 10: 212 iterations
m = 30: 188 iterations
m = 100: 169 iterations
Going from 1 to 10 pairs saves about a third of the iterations; going from 10 to 100 multiplies the cost per iteration by 10 for a smaller further gain. Defaults of 5 to 20 are a good compromise.
L-BFGS-B: simple bounds
The SciPy routine's name ends in "-B" because it also handles box constraints , by identifying which variables sit at a bound (a projected-gradient step, see Projected Gradient Descent) and running L-BFGS on the rest. This covers many practical problems: non-negative weights, probabilities between 0 and 1, physical limits.
Where L-BFGS is the right tool
| Situation | L-BFGS? |
|---|---|
| smooth, deterministic objective, many variables, exact gradients | yes, the default choice |
| full-batch training of small models (logistic regression, CRFs, GPs) | yes |
| noisy mini-batch gradients | no: curvature pairs get corrupted; use SGD/Adam |
| non-smooth objective (L1, max) | no: use proximal methods or OWL-QN |
In software
scipy.optimize.minimize(method="L-BFGS-B")(the L-BFGS-B code of Byrd, Lu, Nocedal and Zhu, translated from Fortran to C in SciPy 1.15) andtorch.optim.LBFGS.- scikit-learn's
LogisticRegressionusessolver="lbfgs"by default; Gaussian process regression fits its kernel hyperparameters with L-BFGS-B.
Exercises
Exercise 1: Memory count
For and , how many floating-point numbers does L-BFGS store for its history, compared with full BFGS?
Answer
, versus (or about using symmetry).
Solution
Each of the pairs has two vectors of length . At 8 bytes each, that is 160 MB against 8 TB.
Exercise 2: Empty history
What direction does L-BFGS take in its first iteration?
Answer
A scaled steepest-descent direction, .
Solution
With no pairs, both loops do nothing, so . Implementations pick a small (or rely on the line search) because no curvature information exists yet.
Exercise 3: Check against the full matrix (code)
With exact inverse Hessian updates and larger than the number of steps taken, the two-loop recursion must equal from the explicit BFGS formula with . Verify it for 3 random pairs with .
Answer
The two results agree to rounding error.
Solution
import numpy as np
rng = np.random.default_rng(0)
n = 4; A = rng.normal(size=(n, n)); Q = A @ A.T + n * np.eye(n)
S = [rng.normal(size=n) for _ in range(3)]; Y = [Q @ s for s in S] # y^T s > 0
g = rng.normal(size=n); gamma = (S[-1] @ Y[-1]) / (Y[-1] @ Y[-1])
H = gamma * np.eye(n)
for s, y in zip(S, Y):
rho = 1 / (y @ s); I = np.eye(n)
H = (I - rho * np.outer(s, y)) @ H @ (I - rho * np.outer(y, s)) + rho * np.outer(s, s)
q = g.copy(); al = []
for s, y in reversed(list(zip(S, Y))):
a = (s @ q) / (y @ s); al.append(a); q -= a * y
r = gamma * q
for (s, y), a in zip(zip(S, Y), reversed(al)):
r += s * (a - (y @ r) / (y @ s))
print(np.allclose(r, H @ g))True
Test yourself
L-BFGS stores…
- the full inverse Hessian
- the last pairs
- all past gradients
- only the current point
Why is L-BFGS a poor choice for mini-batch training of deep networks?
- It needs Hessians
- Noisy gradients corrupt the curvature pairs
- It cannot handle more than 100 variables
- It needs integer variables
The "-B" in L-BFGS-B stands for…
- batch
- bounds (box constraints)
- backtracking
- Bayesian