The Hessian Matrix and the Curvature of a Loss Surface
Learn what the Hessian says about curvature, step sizes and saddle points, and how to probe it without storing the whole matrix.
Key takeaways
- Entry (i, j) of the Hessian is ∂²L/∂wᵢ∂wⱼ, and the matrix is symmetric when those second derivatives are continuous.
- Positive eigenvalues mean the surface curves upward, negative ones mean it curves downward, and a mix at a flat point means a saddle.
- On a quadratic loss, plain gradient descent is stable only when the learning rate is below 2 divided by the largest eigenvalue.
- A large ratio between the largest and smallest positive eigenvalues makes gradient descent zigzag and crawl.
- Large models never store the Hessian, but they can multiply it by a vector at roughly the cost of a few gradient evaluations.
The Hessian is the matrix of second partial derivatives of a loss. Where the gradient tells you which way is downhill, the Hessian tells you how the slope itself changes as you move: how sharply the surface bends, in which directions, and how far a step can safely go.
Its eigenvalues are the useful summary. Each one is the curvature along a particular direction, and together they explain much of why training is fast on some problems and painfully slow on others.
From slope to curvature
For a loss L(w) of d parameters, the gradient is a vector of d first derivatives. Differentiate each of those again with respect to each parameter and you get a d by d table, H.
Take a loss with two parameters.
L(w) = 3w₁² + 2w₁w₂ + 3w₂²
gradient: (6w₁ + 2w₂, 2w₁ + 6w₂)
H = [ 6 2 ]
[ 2 6 ] The diagonal entries describe curvature along each parameter axis. The off-diagonal entry says that moving w₂ changes the slope with respect to w₁. For a quadratic like this one, H is the same everywhere. For a neural network it changes from point to point.
The curvature along any unit direction u is the number uᵀHu. It is the second derivative you would measure if you walked in a straight line along u.
Eigenvalues are the principal curvatures
A symmetric matrix has a set of perpendicular eigenvectors with real eigenvalues. For the matrix above:
| Direction u | H u | Curvature uᵀHu |
|---|---|---|
| (1, 1)/√2 | 8 u | 8 |
| (1, −1)/√2 | 4 u | 4 |
| (1, 0) | (6, 2) | 6 |
The first two rows are the eigenvectors. The curvature in every other direction lies between the smallest eigenvalue, 4, and the largest, 8. The contour lines of this loss are ellipses, narrower along the direction of curvature 8 and longer along the direction of curvature 4.
The same decomposition appears for covariance matrices, as in eigenvectors of a covariance matrix, though there the eigenvalues measure spread in the data.
Classifying flat points
A critical point is where the gradient is zero. The eigenvalues of H at that point tell you what kind it is.
Neural network losses commonly have many eigenvalues at or near zero, so the inconclusive case is not rare. Some of that flatness comes from symmetry. In a ReLU network you can multiply the weights and bias of a hidden unit by a positive constant and divide its outgoing weights by the same constant, leaving the function unchanged. Along that curve the loss is exactly flat.
Saddle points and plateaus looks at why mixed signs become so common when there are many dimensions.
Convexity in two standard models
A twice-differentiable function on a convex region is convex exactly when its Hessian is positive semidefinite everywhere there, meaning no eigenvalue is negative. Two familiar losses pass this test.
Let X have shape (n, d), one example per row.
mean squared error (1/n) ‖Xw − y‖²:
H = (2/n) Xᵀ X
logistic regression, mean log loss (natural log):
H = (1/n) Xᵀ S X, S = diagonal matrix of pᵢ(1 − pᵢ) Both have the form of something transposed times itself, so uᵀHu is a sum of squares with nonnegative weights. The formulas also show where trouble comes from. If two feature columns are nearly identical, XᵀX has an eigenvalue near zero, and many weight vectors fit almost equally well. An L2 penalty (λ/2)‖w‖² adds λ to every eigenvalue.
In logistic regression, pᵢ(1 − pᵢ) shrinks toward zero for confidently predicted examples, so those examples contribute almost no curvature.
Curvature sets the speed limit
Near a minimum, a loss looks approximately quadratic. Gradient descent on a quadratic splits into independent one-dimensional problems along the eigenvectors. With learning rate η, the distance from the optimum along an eigenvector with eigenvalue λ is multiplied by (1 − ηλ) at each step.
To shrink, that factor must lie between −1 and 1, so you need 0 < η < 2/λ. The largest eigenvalue gives the tightest limit.
Say the eigenvalues are 100 and 1. Stability requires η < 0.02. Choose η = 0.019.
steep direction: factor 1 − 0.019 · 100 = −0.9 flips sign, shrinks quickly
flat direction: factor 1 − 0.019 · 1 = 0.981 shrinks slowly
steps to cut the flat error to 1%: ln 0.01 / ln 0.981 ≈ 240 The ratio of largest to smallest eigenvalue is the condition number, here 100. Condition numbers covers the remedies, which include feature scaling, momentum and preconditioning.
In full-batch training of neural networks with a fixed learning rate, researchers have observed that the top eigenvalue often rises until it hovers around 2/η, while the loss still trends downward unevenly. The quadratic analysis is a local guide, not a full account of deep training.
Newton's method and its hazards
If you trust the local quadratic shape, you can jump to its stationary point.
w_new = w − H⁻¹ g g is the gradient at w On a quadratic with a positive definite H, one step lands on the minimum, whatever the condition number. The difficulties appear elsewhere. If H has a negative eigenvalue, the step moves uphill along that direction, toward a saddle. If an eigenvalue is near zero, the step becomes huge.
Practical methods therefore damp the matrix, solving (H + μI)Δ = −g with μ > 0 large enough to make it positive definite. Others replace H with a positive semidefinite stand-in, such as the Gauss-Newton matrix, or build an approximation from past gradients, as in Newton and quasi-Newton methods.
Probing a Hessian you cannot store
With a million parameters, H has 10¹² entries, around 4 TB in 32-bit floating point. You can still compute H v for any vector v, because it is the directional derivative of the gradient.
H v = ∇(∇L · v) with automatic differentiation
H v ≈ [∇L(w + εv) − ∇L(w − εv)] / (2ε) with finite differences Repeating v ← H v and normalizing, known as power iteration, finds the eigenvalue with the largest absolute value. The code below does this for a small logistic regression.
import numpy as np
rng = np.random.default_rng(1)
X = rng.normal(size=(500, 5)) * np.array([3.0, 1.0, 1.0, 0.5, 0.2])
y = (rng.random(500) < 0.5).astype(float) # labels, shape (500,)
w = np.zeros(5)
def grad(w):
p = 1 / (1 + np.exp(-X @ w))
return X.T @ (p - y) / len(y)
def hvp(w, v, eps=1e-5):
return (grad(w + eps*v) - grad(w - eps*v)) / (2*eps)
v = rng.normal(size=5)
for _ in range(50):
v = hvp(w, v)
v /= np.linalg.norm(v)
top = v @ hvp(w, v)
exact = np.linalg.eigvalsh(0.25 * X.T @ X / len(y)).max()
print(top, exact) # nearly equal At w = 0 every p equals 0.5, so the exact Hessian is 0.25 XᵀX/n, which gives a reference value. Related methods, such as the Lanczos algorithm, recover several extreme eigenvalues. Averaging vᵀHv over random vectors with entries of ±1 estimates the trace, the sum of all eigenvalues.
Sharp and flat minima
A popular idea holds that minima with low curvature generalize better than sharp ones, because a small shift between training and test losses hurts less in a wide basin. Some experiments support a link, and methods that favor flat regions often help.
The caution is that the Hessian depends on parameterization. The rescaling described earlier changes the eigenvalues without changing a single prediction, so raw sharpness cannot by itself determine test performance. Measures that adjust for scale narrow the gap, and the question is still studied. Sharpness and weight averaging weighs the evidence.
What to do with what you learn
Curvature information is useful when it changes a decision. If training blows up above some learning rate, a very large top eigenvalue is a likely suspect, and finding the matching eigenvector shows which parameters take part. Weights tied to an unscaled input column often turn out to be responsible, and standardizing that column fixes more than any optimizer setting would.
If the loss falls quickly at first and then crawls, the remaining error may lie mostly along low-curvature directions. Momentum, better scaling or a longer schedule addresses that, while a larger learning rate may be blocked by the steep directions.
Curvature also supports analysis after training. The Laplace approximation treats the weights near a fitted minimum as roughly Gaussian, with a covariance equal to the inverse Hessian of the negative log posterior. High-curvature directions are then tightly determined by the data and prior, and flat ones remain uncertain. Pruning methods use a related idea: a weight is cheaper to remove when changing it barely raises the quadratic estimate of the loss.
In each case the estimate is local. It describes the neighborhood of the current weights, so recompute it after the weights have moved far.
Mistakes to avoid
- Reading curvature from the diagonal alone. The matrix [[0, 1], [1, 0]] has a zero diagonal but eigenvalues 1 and −1.
- Forgetting the factor in the loss. Summing instead of averaging over examples multiplies H by n, and changes the stable learning rate with it.
- Estimating on one small batch. A mini-batch Hessian is noisy, and its extreme eigenvalues can differ noticeably from those on more data.
- Leaving random layers on. Turn off dropout and freeze any batch statistics when you probe curvature, or you will be measuring a moving surface.