Hessian-vector products, Gauss-Newton and trace estimation
Before this lesson: lesson 03 (Jacobian, Hessian, symmetry of second derivatives), lesson 05 (JVP, VJP, forward and reverse mode, dual numbers), lesson 06 (softmax cross-entropy) and lesson 07 (step size of finite differences). From linear algebra: lesson 06 (eigenvalues of symmetric matrices, Rayleigh quotient), lesson 07 (positive semidefinite matrices) and lesson 14 (power iteration, Lanczos, conjugate gradient). Time: about 70 minutes, plus the notebook.
Why this matters #
A network with parameters has a Hessian with entries: 800 TB in float64. You can never form it. Yet many tools need curvature:
- Sharpness. The largest Hessian eigenvalue limits the stable learning rate of gradient descent. Power iteration finds it with Hessian-vector products only.
- Second-order training. Newton-CG and Hessian-free optimization (Martens 2010) solve or with conjugate gradient. CG needs only products with the matrix.
- Influence functions and implicit gradients need , again solved with products (lesson 09).
- Laplace approximations (lesson 11) use the Gauss-Newton matrix as the posterior precision.
- Trace estimation. Continuous normalizing flows need ; a physics-informed loss with a Laplacian needs . Hutchinson's estimator gives both from a few products.
All of these work with the matrix only through products. This lesson shows how to compute the products.
1. Predict first #
2. The picture #
Curvature is the rate of change of the gradient #
In lesson 05 you met the two products that automatic differentiation gives for a map with Jacobian : the JVP (forward mode) and the VJP (reverse mode). Each costs a small constant times one evaluation of , and neither forms . This lesson applies them to one special map: the gradient.
Start in one variable. The second derivative tells how fast the slope changes:
In variables, the gradient is itself a map from to . Its Jacobian is the Hessian (lesson 03). So walk along the line and watch the gradient arrow. The velocity of its tip at is
This is the Hessian-vector product (HVP): one column of information about , in the direction you choose. A central difference of two gradients approximates it: .
Drag the violet point and the violet direction handle . Left: the contour lines of , the dashed line and the gradient arrows along it. Right: the path of the gradient's tip as moves. Its tangent at is the exact ; the secant through the two points at is the finite-difference estimate. Move the slider and watch the error chart: large gives truncation error, tiny gives rounding error. For the cubic preset the gradient is quadratic in , so the secant is exact up to rounding.
Two ways to differentiate a gradient #
Automatic differentiation can differentiate any program, and the gradient computation is a program. So you can run a second pass of automatic differentiation over the first one:
- Forward-over-reverse. Run the gradient program (a forward pass and a backward pass) with dual numbers, that is, with a tangent attached to every value. The tangent of the output is . This is a JVP of the gradient.
- Reverse-over-reverse. Form the scalar and take its gradient with a second reverse pass. Then . This is a VJP of the gradient.
The figure in section 3.1 runs both on a small example, row by row.
Gauss-Newton: keep the curvature of the loss, drop the curvature of the model #
Many losses have the form : a model or residual map followed by a simple loss , for example in least squares. Replace by its linear approximation , where is the Jacobian of . The model is a convex quadratic in the step , with Hessian . This is the Gauss-Newton matrix. The true Hessian of has one more term, which comes from the curvature of and is weighted by the residuals. That extra term can be negative. The Gauss-Newton matrix cannot.
Move the slider . A one-parameter model is fitted to 12 points. Top: the loss with two quadratic models at : the Newton model (uses the true second derivative ) and the Gauss-Newton model (uses ). Bottom: residual term. Notice that everywhere, while is negative between the valleys. There the Newton model opens downward and its step goes uphill. Set the noise to 0: at the best fit the residuals vanish and .
A trace from random signs #
Take a random vector with independent entries or (each with probability ½). Then
because . Each cross term is or with equal chance, so it has mean 0. The average of over many probes is therefore . Each probe needs only one product ; for that is one HVP.
with a symmetric matrix . You compute the central difference in exact arithmetic. How large is its error compared with ?
The gradient is linear in , so exactly, and . The usual truncation error comes from third derivatives of , and a quadratic has none. In floating point, only the rounding error remains.
3. Definitions and main results #
Notation. is twice continuously differentiable (). Its gradient is the column and its Hessian is , with . The vector is fixed: it does not depend on .
3.1 Hessian-vector products #
Proposition 1 (two exact HVPs). (a) (forward-over-reverse: a JVP of ). (b) With , (reverse-over-reverse: a VJP of ).
Proof.
- The Jacobian of is the Hessian: .
- (a) The derivative of at is (chain rule, lesson 04). By step 1 this is .
- (b) with constant, so .
- is , so is symmetric (Schwarz's theorem, lesson 03) and .
Step 4 is where the Hessian is special. For a map that is not a gradient, the JVP gives and the VJP gives , and the two differ.
There are four ways to nest the two modes (Blondel and Roulet, §9.1):
| Method | What it computes | Time | Memory |
|---|---|---|---|
| forward-over-reverse | JVP of the gradient program | small constant × one gradient | like one gradient, plus the tangents |
| reverse-over-reverse | gradient of | small constant × one gradient | more: it also stores the first backward pass |
| reverse-over-forward | gradient of (the same ) | small constant × one gradient | like forward-over-reverse |
| forward-over-forward | second-order JVPs, one per basis direction | passes for one | small |
Forward-over-reverse is the usual default (for example jax.jvp(jax.grad(f), ...)). Reverse-over-reverse
is the "double backward" of PyTorch: it is available whenever the backward pass is itself differentiable.
Step through the trace of at . Rows 1–6 are the forward pass, rows 7–12 the backward pass that computes . In forward-over-reverse, every row also carries a tangent (the dot). The tangents of are . In reverse-over-reverse, a third sweep goes back up through all 12 rows and fills the second adjoints; the values at are . Notice that this third sweep needs all 12 rows stored. Choose to get the first column of .
Why one HVP costs a small constant times one gradient.
- Reverse mode gives for a small constant times the cost of , independent of . This is the cheap gradient principle (lesson 05).
- The gradient computation is itself a program made of elementary operations. Its cost is for a small constant .
- Forward mode on any program costs a constant factor times that program: each elementary operation gets one extra derivative operation.
- So the JVP of costs a constant times : a small multiple of one gradient. In practice this is about 2 to 4 gradients. No factor appears.
- Reverse-over-reverse: costs , and reverse mode on costs a constant times that. The time is of the same order. But the second reverse sweep must also store the intermediate values of the first backward pass, so it needs more memory than forward-over-reverse.
The finite-difference HVP. The central difference costs two gradients, but it is not exact. Its truncation error is (from third derivatives of ) and its rounding error is , where is float64 machine epsilon. As in lesson 07, the best step is about (for a well-scaled problem) and the best relative error is about . In float32 () the best is only about .
The full Hessian costs HVPs, with : the HVP with is column of . This is fine for and impossible for .
A model has parameters, and one gradient takes 1 second. About how long does it take to compute the full Hessian with exact HVPs (forward-over-reverse, about 3 gradients each)?
One HVP gives one column of , so you need HVPs, each about 3 seconds. This is why methods use a few HVPs, never the full matrix. The answer would be the cost of gradients; you need only HVPs.
3.2 The Gauss-Newton matrix #
Let with a model or residual map , its Jacobian , and a loss . Write for the -th output of and for .
Proposition 2 (Hessian of a composition).
Proof.
- Chain rule: . In coordinates, .
- Differentiate with respect to with the product rule. The first factor depends on through , so :
- The first sum is entry of . The second is entry of .
Definition. The (generalized) Gauss-Newton matrix is . For we have and .
Three properties.
- is positive semidefinite when is convex. For any , , because . This holds even where is indefinite.
- when the residual term vanishes: when is linear in (), or when (for least squares: a perfect fit, ). Near a good fit, .
- Matrix-free product. To compute : (i) , one JVP of ; (ii) , which is cheap: for , ; for softmax cross-entropy with probabilities , ; (iii) , one VJP of .
For softmax cross-entropy, with respect to the logits (lesson 06). It is positive semidefinite: is the variance of the numbers under the probabilities .
The Gauss-Newton step solves . If and , then , so the step is a descent direction. The Levenberg-Marquardt method adds damping, with , which keeps the system positive definite and shortens the step when the linear model is poor. The optimization track covers these methods in detail (optimization).
Gauss-Newton, Fisher information and natural gradient
Let be a negative log-likelihood, where the model output is the natural parameter of an exponential family: the logits of a softmax, or the mean of a Gaussian with fixed variance. Then does not depend on the label , and equals the Fisher information matrix of the model (Martens 2020; Blondel and Roulet §9.3). This connects Gauss-Newton to the natural gradient and to K-FAC (Martens and Grosse 2015), which approximates by Kronecker factors, one pair per layer.
At some , the Hessian of a least-squares loss has eigenvalues and . What can you say about the Gauss-Newton matrix at the same point?
for every , so always. The negative curvature lives in the residual term , which drops. equals the Hessian only if that term is zero, for example at a perfect fit.
3.3 Hutchinson's trace estimator #
Proposition 3. Let , and let be random with . Then . If is symmetric and is Rademacher (independent entries, or with probability ½ each), then .
Proof.
- A number equals its own trace, so (cyclic property of the trace).
- Trace and expectation are both linear, so .
- For Rademacher , . With symmetric, .
- Each product () has mean 0 and variance 1. Two different products are uncorrelated: for example .
- The variance of a sum of uncorrelated terms is the sum of the variances: .
The Hutchinson estimator averages independent probes: . It needs products (for : HVPs), and its variance is the single-probe variance divided by . So the standard error falls like : four times more probes halve the error.
Variance for general probes, and why Rademacher is best
Let the entries be independent with mean 0, variance 1 and fourth moment , and let be symmetric.
- Split .
- The diagonal part has variance .
- The off-diagonal part has variance , as in the proof above.
- The two parts are uncorrelated: for , because or appears with power 1 and has mean 0.
- So .
Gaussian probes have , which gives . Rademacher probes have , the smallest possible value (since ), and they add nothing for the diagonal. For a non-symmetric , use its symmetric part : it has the same quadratic form .
Press "New probes" a few times. The lines are running averages of for a fixed symmetric matrix: Rademacher and Gaussian probes. The dashed curves are one standard deviation from the variance formula; they shrink like . This matrix is diagonal-heavy, so the Rademacher band is narrow and the Gaussian band is wide. Switch to the off-diagonal-heavy matrix: both bands are wide and almost equal. For the diagonal matrix, every Rademacher probe gives the exact trace.
. What is the variance of one Hutchinson probe with Rademacher ?
, which is 6 or with equal chance: mean 2, variance . The formula gives . The value 20 is the Gaussian variance ; 8 forgets the factor 2 from the two off-diagonal entries.
3.4 Algorithms that need only #
- Largest eigenvalue (sharpness). Power iteration converges to the eigenvector of the eigenvalue with the largest absolute value (linear-algebra lesson 05). The Rayleigh quotient then estimates that eigenvalue. Near a minimum, and this is . The Lanczos method (linear-algebra lesson 14) gets several extreme eigenvalues with fewer HVPs.
- Newton-CG. The Newton step solves . Conjugate gradient solves it with one HVP per iteration, and stopping after a few iterations gives a "truncated Newton" step. CG needs a positive definite matrix, which is one reason to use (or ) instead of .
- Trace and diagonal. Hutchinson's estimator gives . The same probes give an estimate of the diagonal: for Rademacher .
Answers to section 1. (1) About : a small constant times one gradient (in practice 2 to 4), never , by the cost argument in section 3.1. (2) No. For a squared-error loss, for every , so has no negative eigenvalue. The negative curvature lives in the residual term. (3) One. For a diagonal , for every Rademacher probe, so the variance is 0.
4. Worked example #
(a) An HVP both ways. at with . The gradient is , so .
- Forward-over-reverse. Move along the line: , so the two entries of are and . Their derivatives in are and . At this is .
- Reverse-over-reverse. . Its gradient is . At : .
- Check with the full Hessian. and . ✓
- , so the eigenvalues have opposite signs: the point is saddle-like.
- Finite difference. is quadratic in , so the central difference equals for every , up to rounding.
(b) Gauss-Newton against the Hessian. Residuals , loss , at , with .
- , and .
- Matrix-free product: , then .
- The matrix itself: . Its eigenvalues are and : positive definite.
- Residual term: only is nonzero, and (the second derivatives of ). So the term is .
- , with eigenvalues and : indefinite. Also .
- The steps. The gradient is . The Gauss-Newton step solves : . It lands at , where : an exact solution in one step. The Newton step also goes downhill here, but this is not guaranteed when is indefinite.
The large residual makes the dropped term large, so and differ a lot here.
(c) Hutchinson by hand. , . For a Rademacher probe, . The four possible probes give : mean 5 and variance . Gaussian probes would give variance .
5. In code #
NumPy checks the numbers of section 4. The gradients are written by hand.
import itertools
import numpy as np
g = lambda x: np.array([3 * x[0]**2 + x[1]**2, 2 * x[0] * x[1]]) # gradient of x1^3 + x1 x2^2
H = lambda x: np.array([[6 * x[0], 2 * x[1]], [2 * x[1], 2 * x[0]]])
x, v = np.array([1.0, 2.0]), np.array([1.0, 1.0])
for eta in (1e-1, 1e-5):
print((g(x + eta * v) - g(x - eta * v)) / (2 * eta)) # [10. 6.] both times: g is quadratic
print(H(x) @ v) # [10. 6.]
# Gauss-Newton product with one JVP (J @ v) and one VJP (J.T @ u)
r = lambda th: np.array([th[0] * th[1] + 2, th[0] - 1])
th, v = np.array([1.0, 2.0]), np.array([1.0, -1.0])
J = np.array([[th[1], th[0]], [1.0, 0.0]])
HL = J.T @ J + r(th)[0] * np.array([[0.0, 1.0], [1.0, 0.0]])
print(J.T @ (J @ v), HL @ v) # [3. 1.] [-1. 5.]
print(np.linalg.eigvalsh(J.T @ J), np.linalg.eigvalsh(HL)) # [0.17 5.83] [-3.32 9.32]
print(np.linalg.solve(J.T @ J, -J.T @ r(th))) # [0. -4.]: lands on r = 0
# Hutchinson: all four Rademacher probes
A = np.array([[2.0, 1.0], [1.0, 3.0]])
q = [z @ A @ z for z in map(np.array, itertools.product([-1, 1], repeat=2))]
print(q, np.mean(q), np.var(q)) # [7, 3, 3, 7] 5.0 4.0
In PyTorch, torch.func composes the two modes directly. The eager "double backward" needs
create_graph=True in the first call, so that the gradient is itself recorded in a graph:
import torch
from torch.func import grad, jvp, vjp
torch.set_default_dtype(torch.float64)
f = lambda x: x[0]**3 + x[0] * x[1]**2
x, v = torch.tensor([1.0, 2.0]), torch.tensor([1.0, 1.0])
print(jvp(grad(f), (x,), (v,))[1]) # forward-over-reverse: tensor([10., 6.])
print(grad(lambda x: grad(f)(x) @ v)(x)) # reverse-over-reverse: tensor([10., 6.])
xr = x.clone().requires_grad_(True) # eager double backward
(gx,) = torch.autograd.grad(f(xr), xr, create_graph=True)
print(torch.autograd.grad(gx @ v, xr)[0]) # tensor([10., 6.])
r = lambda th: torch.stack([th[0] * th[1] + 2, th[0] - 1])
th, v = torch.tensor([1.0, 2.0]), torch.tensor([1.0, -1.0])
u = jvp(r, (th,), (v,))[1] # u = J v -> tensor([1., 1.])
print(vjp(r, th)[1](u)[0]) # G v = J^T u -> tensor([3., 1.])
In JAX the same forward-over-reverse HVP is jax.jvp(jax.grad(f), (x,), (v,))[1].
6. Where it shows up #
- Sharpness and the edge of stability. On a quadratic, gradient descent with step is stable only if . Cohen et al. (2021) observed that in full-batch training the sharpness rises until it reaches about and then stays there. Such studies measure with power iteration or Lanczos on HVPs; PyHessian (Yao et al. 2020) also estimates the trace with Hutchinson and the eigenvalue density with stochastic Lanczos.
- Second-order optimization. Hessian-free optimization (Martens 2010) runs CG on damped Gauss-Newton products . K-FAC and Shampoo approximate or the Fisher matrix with Kronecker factors.
- Influence functions. The effect of one training point on a prediction needs (Koh and Liang 2017). It is computed with CG or a truncated Neumann series on HVPs.
- Laplace approximation (lesson 11). The common "GGN Laplace" posterior uses the covariance , because is positive semidefinite and may not be.
- Trace estimation in generative models. A continuous normalizing flow (FFJORD, Grathwohl et al. 2019) needs in its log-density ODE. Hutchinson with one VJP per probe replaces backward passes by one. Sliced score matching uses the same trick (generative models).
- ML for science. In 4D-Var data assimilation for weather prediction, the "tangent-linear model" is the JVP and the "adjoint model" is the VJP of the forecast model. Incremental 4D-Var is a Gauss-Newton method, and its inner solver uses exactly . Full-waveform inversion in seismology uses the same Gauss-Newton and truncated-Newton products. A physics-informed loss with a Laplacian needs : HVPs for input dimension , or a Hutchinson estimate when is large (ML for science).
7. Common mistakes #
- Forming the full matrix. If you need , or , do not form , or . Use products.
- Letting depend on in reverse-over-reverse. If is not detached from the graph, then : an extra term appears.
- Forgetting
create_graph=Truein the first backward call of a double-backward HVP. Without it the first gradient is not part of any graph, and the second call raises an error ("does not require grad"). - Treating as the Hessian. drops . It is positive semidefinite by construction, so it cannot show negative curvature or saddle points. Far from a good fit it can be a poor model of .
- Using power iteration as if it returned . It returns the eigenvalue of largest absolute value. If has a large negative eigenvalue, that is what you get.
- Gaussian probes by default. They add to the variance. Rademacher probes do not.
- Finite-difference HVPs in float32. With the best relative error is only about . Use the exact autodiff HVP.
8. Check yourself #
- Reverse-over-reverse computes . Why does this equal the HVP, and what goes wrong for a
vector field that is not a gradient?
Answer
For with , is symmetric (Schwarz), so . For a general , is not symmetric, and the VJP differs from the JVP . - (one residual, one parameter) and . Give and
at and at .
Answer
and , so and . At : , . At : , . The true curvature is negative there; stays positive. - . What is the single-probe variance of Hutchinson's
estimator with Gaussian probes? What is the standard deviation of the mean of 100 Rademacher probes?
Answer
Gaussian: . Rademacher: per probe, so the mean of 100 probes has standard deviation , around the true trace 2. - For softmax cross-entropy with probabilities , how do you apply to a vector
inside a Gauss-Newton product, and why is positive semidefinite?
Answer
, so . And is the variance of the numbers under , so it is . Hence . - Which HVP method needs less memory, forward-over-reverse or reverse-over-reverse, and why?
Answer
Forward-over-reverse. The tangents travel with the forward and backward passes and can be freed as the passes go. Reverse-over-reverse must also store the intermediate values of the first backward pass, because the second reverse sweep visits them. - You run power iteration with HVPs and get the estimate . What does this tell you about ?
Answer
The eigenvalue of largest absolute value is about : has strong negative curvature in some direction, so the point is not a minimum. All eigenvalues lie in about , so the shifted matrix has eigenvalues (about). Power iteration on it finds ; one HVP of is . Lanczos gives both ends directly.
Write the Hessian-vector product as the derivative of the gradient.
: a JVP of the gradient map (forward-over-reverse).
How does reverse-over-reverse compute ?
Form the scalar with fixed, and take its gradient: .
Why do the JVP and the VJP of the gradient give the same vector?
The Jacobian of is the Hessian, which is symmetric for (Schwarz), so .
What does one exact HVP cost, compared with one gradient?
A small constant times one gradient (about 2–4), independent of the number of parameters .
How many HVPs do you need to form the full Hessian?
: the HVP with is column of .
What is the Gauss-Newton matrix of ?
with . It drops the residual term of the Hessian.
Why is the Gauss-Newton matrix positive semidefinite?
when is convex. For least squares, .
How do you compute without forming ?
One JVP , then one VJP .
What is Hutchinson's estimator, and why is it unbiased?
. Since and , each term has mean .
Variance of one Rademacher Hutchinson probe for ?
. (Gaussian probes: .)
9. Interview angle #
- "How do you get the top Hessian eigenvalue of a 1B-parameter model?" Power iteration or Lanczos on HVPs. Each HVP costs a few gradients; never form . Power iteration returns the eigenvalue of largest absolute value.
- "What does an HVP cost, and how is it computed?" A small constant times a gradient. Forward-over-reverse: a JVP of the gradient function. Or double backward: the gradient of .
- "Why is Gauss-Newton safer than Newton on a neural network?" for convex , so the quadratic model is convex and the step is a descent direction. is indefinite in general.
- "How do you get the trace of a Jacobian in a continuous normalizing flow without forming it?" Hutchinson: with one VJP per probe, Rademacher probes.
- "When is Gauss-Newton equal to the Hessian?" When the residual term vanishes: a linear model, or zero residuals at a perfect fit.
10. Practice #
The notebook for this lesson runs in Colab. It uses NumPy only: a small dual-number class (from lesson 05) gives forward-over-reverse on hand-written gradients. Five exercises, each with a check cell and a folded solution:
hvp_fwd_revandhvp_fdon a logistic-regression loss; compare with the exact .hessian_from_hvp: build column by column and check that it is symmetric.gauss_newton_vpfor a small exponential curve fit; compare with the full Hessian near and far from the fit.hutchinson_tracewith Rademacher and Gaussian probes; compare the empirical variance with the formula.top_eigenvalue: power iteration with HVPs for of a small MLP loss Hessian.
11. Watch and read #
- Blondel and Roulet, The Elements of Differentiable Programming (free): §9.1 (the four HVP methods and their costs), §9.2 (Gauss-Newton matrix and Gauss-Newton vector product), §9.8.1 (Girard-Hutchinson trace estimator).
- JAX, The Autodiff Cookbook: sections on Hessian-vector products with grad-of-grad and with forward-over-reverse.
- PyTorch tutorial, Jacobians, Hessians, hvp, vhp, and more
(
torch.func). - Pearlmutter (1994), Fast exact multiplication by the Hessian: the original exact HVP.
- Martens (2010), Deep learning via Hessian-free optimization: CG on Gauss-Newton products.
- Yao et al. (2020), PyHessian: Neural Networks Through the Lens of the Hessian: power iteration, Hutchinson and stochastic Lanczos on HVPs.
- Cohen et al. (2021), Gradient Descent on Neural Networks Typically Occurs at the Edge of Stability.
- Bright, Edelman and Johnson, Matrix Calculus (for Machine Learning and Beyond): the course notes of the MIT lectures, with a chapter on second derivatives.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.