L-BFGS: Inverse-Hessian Product From Recent Steps

OptimizationHard+20 XP+20

L-BFGS: Inverse-Hessian Product From Recent Steps

Newton's method converges beautifully and needs the inverse Hessian — an n × n matrix, impossible to store when n is in the millions. L-BFGS approximates multiplying by that inverse while storing nothing but the last few steps the optimiser took.

It keeps two short histories, oldest first:

  • s_list[i] — how much the parameters moved at that step,
  • y_list[i] — how much the gradient changed at that step.

From those it reconstructs the product H∇fH \nabla fH∇f in two passes, which is where the name comes from.

First, define ρi=1yi⋅si\rho_i = \dfrac{1}{y_i \cdot s_i}ρi​=yi​⋅si​1​ for each remembered step.

Loop one — newest to oldest. Start with q = grad, and for each i going backwards:

αi=ρi (si⋅q),q←q−αiyi\alpha_i = \rho_i \,(s_i \cdot q), \qquad q \leftarrow q - \alpha_i y_iαi​=ρi​(si​⋅q),q←q−αi​yi​

Save every αi\alpha_iαi​; the second loop needs them.

Scale. Using only the newest pair:

γ=slast⋅ylastylast⋅ylast,r=γq\gamma = \frac{s_{\text{last}} \cdot y_{\text{last}}}{y_{\text{last}} \cdot y_{\text{last}}}, \qquad r = \gamma qγ=ylast​⋅ylast​slast​⋅ylast​​,r=γq

Loop two — oldest to newest. For each i going forwards:

β=ρi (yi⋅r),r←r+si(αi−β)\beta = \rho_i \,(y_i \cdot r), \qquad r \leftarrow r + s_i (\alpha_i - \beta)β=ρi​(yi​⋅r),r←r+si​(αi​−β)

Task: write two_loop_recursion(grad, s_list, y_list) returning the final r, each entry rounded to 4 decimal places.

  • grad, and every vector in the two histories, have the same length. Both histories are the same length and hold at least one pair, ordered oldest first.
  • Every yi⋅siy_i \cdot s_iyi​⋅si​ is non-zero, so no ρ\rhoρ blows up.
  • Return r itself. It approximates H∇fH \nabla fH∇f, so the descent step the optimiser actually takes is its negative.

Nothing here ever builds a matrix — every line is a dot product or a vector add. That's the trick: the curvature information lives entirely in the history, and the cost scales with how many steps you remember rather than with how many parameters you have.

Examples

grad = [1.0, 1.0]
s_list = [[1.0, 0.0]]
y_list = [[2.0, 0.0]]
returns [0.5, 0.5]
grad = [2.0, 4.0]
s_list = [[1.0, 0.0], [0.0, 1.0]]
y_list = [[1.0, 0.0], [0.0, 2.0]]
returns [2.0, 2.0]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run