TExcelTAD
Home › Optimization › Limited-Memory BFGS

Limited-Memory BFGS

BFGS stores an n×nn \times n matrix. With a million variables that is 101210^{12} numbers, far too many. L-BFGS keeps only the last mm pairs (si,yi)(\mathbf{s}_i, \mathbf{y}_i), typically mm between 5 and 20, and reconstructs the product Hk∇fkH_k\nabla f_k from them on the fly. Memory and time per iteration drop to O(mn)O(mn), and the method keeps most of BFGS's speed.

The two-loop recursion

Unrolling the BFGS update mm times shows that HkqH_k\mathbf{q} can be computed from the stored pairs and an initial matrix Hk0=γkIH_k^0 = \gamma_kI with two passes over the history:

text
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 = -r

The scaling γk\gamma_k estimates the size of the inverse Hessian along the most recent direction, so a step of length 1 is usually accepted.

python · try it yourself
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 mm

Larger mm 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):

python · try it yourself
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 ℓ≤x≤u\boldsymbol{\ell} \le \mathbf{x} \le \mathbf{u}, 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) and torch.optim.LBFGS.
  • scikit-learn's LogisticRegression uses solver="lbfgs" by default; Gaussian process regression fits its kernel hyperparameters with L-BFGS-B.

Exercises

Exercise 1: Memory count

For n=106n = 10^6 and m=10m = 10, how many floating-point numbers does L-BFGS store for its history, compared with full BFGS?

Answer

2×10×106=2×1072 \times 10 \times 10^6 = 2 \times 10^7, versus 101210^{12} (or about 5×10115 \times 10^{11} using symmetry).

Solution

Each of the mm pairs has two vectors of length nn. 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, −γ0∇f(x0)-\gamma_0\nabla f(\mathbf{x}_0).

Solution

With no pairs, both loops do nothing, so r=γ0q=γ0∇f\mathbf{r} = \gamma_0\mathbf{q} = \gamma_0\nabla f. Implementations pick a small γ0\gamma_0 (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 mm larger than the number of steps taken, the two-loop recursion must equal HkgH_k\mathbf{g} from the explicit BFGS formula with H0=γIH^0 = \gamma I. Verify it for 3 random pairs with yTs>0\mathbf{y}^T\mathbf{s} > 0.

Answer

The two results agree to rounding error.

Solution
python · try it yourself
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…

  1. the full inverse Hessian
  2. the last mm pairs (si,yi)(\mathbf{s}_i, \mathbf{y}_i)
  3. all past gradients
  4. only the current point

Why is L-BFGS a poor choice for mini-batch training of deep networks?

  1. It needs Hessians
  2. Noisy gradients corrupt the curvature pairs
  3. It cannot handle more than 100 variables
  4. It needs integer variables

The "-B" in L-BFGS-B stands for…

  1. batch
  2. bounds (box constraints)
  3. backtracking
  4. Bayesian