Take a Hessian-free Newton step with finite-difference Hessian-vector products

Second-order optimisers want the Newton step d solving H d = -g, but for a model with many parameters you can never form H. Two tricks fix that: a Hessian-vector product only needs two gradient calls, and conjugate gradient (CG) solves H d = -g using only those products.

Write newton_cg_step(grad_fn, x, max_iter=50, eps=1e-5, tol=1e-10). grad_fn maps a 1D array to its gradient. Assume the Hessian is symmetric positive definite.
- Hessian-vector product: Hv = (grad_fn(x + eps * v) - grad_fn(x - eps * v)) / (2 * eps).
- CG: start d = 0, r = -grad_fn(x), p = r, rs = r.r. If sqrt(rs) < tol return d. Then repeat up to max_iter times: Hp = Hv of p; alpha = rs / (p.Hp); d = d + alpha p; r = r - alpha Hp; rs_new = r.r; if sqrt(rs_new) < tol stop; p = r + (rs_new / rs) p; rs = rs_new.
Return d, shape like x.

Signaturedef newton_cg_step(grad_fn, x, max_iter=50, eps=1e-5, tol=1e-10)

Example

for f(x) = 0.5 x^T A x - b^T x the gradient is A x - b, and x + d is exactly the minimiser A^{-1} b (up to rounding).

Understand the idea

Newton's method jumps to the minimum of a local quadratic by solving H d = -g, but you can never build H for a large model. Two tricks help. A Hessian-vector product needs only two gradient calls: (grad(x + eps v) - grad(x - eps v)) / (2 eps). Conjugate gradient then solves H d = -g using only such products, choosing each search direction so it does not undo earlier progress; on an n-dimensional quadratic it finishes in at most n steps. Worked example: A = diag(2, 1), b = [2, 1], f = 0.5 x^T A x - b^T x, x = 0. Then g = [-2, -1], r = [2, 1], p = r, rs = 5. Step 1: Hp = [4, 1], alpha = 5 / 9 = 0.556, d = [1.111, 0.556], r = [-0.222, 0.444], rs_new = 0.247. New p = r + (0.247 / 5) p = [-0.123, 0.494]. Step 2: alpha = 0.9, d = [1, 1], and r becomes 0. Indeed A^-1 b = [1, 1]. Rule: follow the CG updates in the prompt exactly. Hessian-free optimisers and influence functions use this.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: quadratic stepnewton_cg_step(_g1, _x0)
  • Sample 2: quadratic lands on the minimiser_x0 + newton_cg_step(_g1, _x0)