Module contents
Lesson 9 of 20Core 110 min

The Hessian, multivariable Taylor and local geometry

The Hessian is the Jacobian of the gradient and describes a function's curvature in each direction. This lesson proves Schwarz symmetry, second-order Taylor expansion with remainder, critical-point classification and directional curvature as a Rayleigh quotient, and introduces the Hessian–vector product, enabling curvature calculations for models with millions of parameters without forming the Hessian.

After this lesson you can

  • Calculate Hessians and justify symmetry with Schwarz's theorem, knowing the counterexample when continuity fails.
  • Write and prove the second-order Taylor expansion in ℝⁿ with Peano and Lagrange remainders.
  • Classify critical points using Hessian eigenvalues, including degenerate cases.
  • Relate directional curvature, Rayleigh quotient and condition number to gradient-descent behavior.
  • Calculate Hessian–vector products without forming the Hessian and estimate the largest eigenvalue of a loss Hessian.

Before you start

Motivation: what the gradient does not say

The gradient gives the best linear approximation to a function at a point and the steepest ascent direction. This is first-order information, and almost everything is trained with it. But no tangent line can answer some questions that arise repeatedly in real work:

  • What step size is safe? If the function curves little, long steps are possible; if it curves sharply in some direction, a large step sends you across the valley. Gradient descent’s stability limit is η<2/λmax⁡\eta < 2/\lambda_{\max}, where λmax⁡\lambda_{\max} is the loss’s largest curvature. If λmax⁡\lambda_{\max} grew during training, a step that worked stops working (the root of the so-called edge of stability).
  • Which way should we really go? Newton’s method minimizes a quadratic model of the function at each step and jumps directly to its minimum, h=−(∇2f)−1∇f\vb{h} = -(\hess f)\inv\grad f. It needs curvature at each point.
  • How uncertain is an estimate? The Laplace approximation replaces a posterior with a Gaussian centered at its mode, with covariance the inverse of minus the curvature of the log density. Curvature again.
  • How sharp is this minimum? Two minima with the same loss can be wide and narrow. Sharpness is measured by the largest curvature eigenvalue, and its connection with generalization is debated (flatness and generalization).
  • Is this a minimum or saddle? A zero gradient is insufficient. Curvature decides what happens around it.

All this is summarized by one object: the matrix of second derivatives, the Hessian. This lesson builds it rigorously. It is the Jacobian of the gradient; symmetric (Schwarz’s theorem, with a counterexample when assumptions fail); gives the second-order Taylor expansion in Rn\R^n with explicit remainders; classifies critical points using eigenvalues and explains why gradient descent zigzags. It ends with a trick enabling all of this in models with millions of parameters: the Hessian–vector product, accessing curvature without ever forming the matrix.

Intuition: a smooth function up close is a bowl

In linearization you replace ff with its tangent plane. The plane gets value and slope right but misses how ff bends. The next natural step is a degree-2 polynomial also matching curvature:

q(x)=f(a)+∇f(a)⊤(x−a)+12(x−a)⊤ ∇2f(a) (x−a).q(\vb{x}) = f(\vb{a}) + \grad f(\vb{a})\T(\vb{x} - \vb{a}) + \tfrac12 (\vb{x} - \vb{a})\T\, \hess f(\vb{a})\, (\vb{x} - \vb{a}).

It is a bowl, saddle or valley depending on the signs of ∇2f(a)\hess f(\vb{a})‘s eigenvalues. The figure overlays that model on three test surfaces and measures how far it can be trusted.

InteractiveThe quadratic model and its trust region
contours: f in gray, quadratic model in orange
  • ff (true)
  • quadratic model qq and its trust region
  • linear model region
Surface
0.30
10 %
Point a\vb{a}(−0.40, 0.10)
f(a)f(\vb{a})2.320
∥∇f(a)∥\norm{\grad f(\vb{a})}17.256
Eigenvalues of ∇2f(a)\hess f(\vb{a})338.64, 15.36
Quadratic trust radius0.142
Linear trust radius0.011
At a\vb{a}: positive definite Hessian: qq is a bowl and ff is locally convex, but a\vb{a} is not a critical point (∇f≠0\grad f \neq \vb{0}).
Drag point a\vb{a} on the contour map. In orange, Taylor quadratic model qq at a\vb{a}: its contours (within the disk of radius ρ\rho) and, below, its patch on the 3D surface. The orange polygon is the region where relative error ∣f−q∣/(∥∇f(a)∥∥h∥+12∣λ∣max⁡∥h∥2)\abs{f - q}/(\norm{\grad f(\vb{a})}\norm{\vb{h}} + \tfrac12\abs{\lambda}_{\max}\norm{\vb{h}}^2) (error against the maximum possible contribution of linear and quadratic terms, with ∣λ∣max⁡\abs{\lambda}_{\max} the largest absolute eigenvalue of ∇2f(a)\hess f(\vb{a})) does not exceed tolerance; green is the same region for the linear model. Notice how the quadratic region is much larger, stretches or shrinks with position, and changes from Rosenbrock to Himmelblau. The perceptron is quadratic loss of a tanh neuron with two weights on 14 synthetic data points (fixed seed).

Three things deserve attention. The linear model resembles ff only in a small region and collapses where the gradient is nearly zero (the tangent plane is almost horizontal and says nothing about how ff curves). The quadratic model gains a much larger region almost everywhere. And that region is not a disk: in narrow Rosenbrock valleys it stretches along the valley and shrinks across it because curvature changes quickly in the steep direction. The lesson explains why: quadratic model error is controlled by the third derivative, becoming an exact bound in Taylor’s theorem.

Higher-order derivatives and the Hessian

Let f:U→Rf : U \to \R with U⊆RnU \subseteq \R^n open. If ff has partial derivatives ∂jf\partial_j f and these have partial derivatives in turn, write

∂i∂jf=∂2f∂xi ∂xj=∂i(∂jf).\partial_i\partial_j f = \frac{\partial^2 f}{\partial x_i\,\partial x_j} = \partial_i(\partial_j f).

Reading order is right to left: differentiate first with respect to xjx_j and then xix_i. We call ff class C2C^2 if all partial derivatives through order 2 exist and are continuous.

It is literally the gradient’s Jacobian. Function ∇f:U→Rn\grad f : U \to \R^n has components ∂if\partial_i f, and its Jacobian matrix has at position (i,j)(i, j) derivative ∂j(∂if)=Hji\partial_j(\partial_i f) = H_{ji}, that is, H⊤\mat{H}\T. Schwarz’s theorem (below, whose proof uses nothing following in this section) says H⊤=H\mat{H}\T = \mat{H} for C2C^2 functions, so the gradient Jacobian is the Hessian. This is the most useful way to think in machine learning, because it connects everything with the familiar chain rule: the Hessian answers “how much does the gradient change when I move slightly?”, the linear map taking displacement v\vb{v} to gradient change Hv\mat{H}\vb{v}.

A lemma used three times

To discuss curvature along a direction, restrict ff to a line: φ(t)=f(a+tv)\varphi(t) = f(\vb{a} + t\vb{v}). The chain rule gives the first two derivatives and, once ∇f\grad f is differentiable, the third equality below.

Proof

The first equality is the chain rule for t↦a+tvt \mapsto \vb{a} + t\vb{v}, whose derivative is v\vb{v}. Function t↦∇f(a+tv)t \mapsto \grad f(\vb{a} + t\vb{v}) is the composition of ∇f\grad f with that line; its Jacobian is H⊤=H\mat{H}\T = \mat{H} (by Schwarz) and the chain rule gives the third equality. Differentiating the first, φ′′(t)=( ⁣d ⁣dt∇f(a+tv))⊤v=(Hv)⊤v=v⊤H⊤v\varphi''(t) = \big(\tfrac{\dd}{\dd t}\grad f(\vb{a} + t\vb{v})\big)\T\vb{v} = (\mat{H}\vb{v})\T\vb{v} = \vb{v}\T\mat{H}\T\vb{v}, which is v⊤Hv\vb{v}\T\mat{H}\vb{v} because a scalar equals its transpose. Continuity of φ′′\varphi'' follows from that of H\mat{H}.

∎

The third equality seeds the lesson’s final topic: the Hessian–vector product is a directional derivative of the gradient, allowing computation without forming H\mat{H}. The second will be directional curvature.

Examples to have at hand

ℓi(w)=log⁡ ⁣(1+ezi)−yizi\ell_i(\vb{w}) = \log\!\big(1 + e^{z_i}\big) - y_i z_i
Loss of one example (negative log likelihood of a Bernoulli with logit zi=xi⊤wz_i = \vb{x}_i\T\vb{w} and label yi∈{0,1}y_i \in \{0, 1\}).
1/4

Symmetry: Schwarz’s theorem

The examples’ Hessians were symmetric, and not by chance. Calculations with ∂i∂jf\partial_i\partial_j f and ∂j∂if\partial_j\partial_i f agree whenever ff is reasonably smooth. The result is Schwarz’s theorem (also Clairaut’s or Young’s), and both its proof and what happens when it fails are worth knowing.

Proof

Two variables suffice; hold the others fixed. Write xx and yy for xix_i and xjx_j, and a=(a,b)\vb{a} = (a, b). For small nonzero h,kh, k consider the double quotient

Δ(h,k)=f(a+h,b+k)−f(a+h,b)−f(a,b+k)+f(a,b)hk.\Delta(h, k) = \frac{f(a + h, b + k) - f(a + h, b) - f(a, b + k) + f(a, b)}{hk}.

Let ϕ(x)=f(x,b+k)−f(x,b)\phi(x) = f(x, b + k) - f(x, b). Then Δ(h,k)=(ϕ(a+h)−ϕ(a))/(hk)\Delta(h, k) = \big(\phi(a + h) - \phi(a)\big)/(hk). By the mean value theorem, there is ξ\xi between aa and a+ha + h with ϕ(a+h)−ϕ(a)=h ϕ′(ξ)=h (∂xf(ξ,b+k)−∂xf(ξ,b))\phi(a + h) - \phi(a) = h\,\phi'(\xi) = h\,\big(\partial_x f(\xi, b + k) - \partial_x f(\xi, b)\big). Applying the mean value theorem again to differentiable y↦∂xf(ξ,y)y \mapsto \partial_x f(\xi, y), there is η\eta between bb and b+kb + k with ∂xf(ξ,b+k)−∂xf(ξ,b)=k ∂y∂xf(ξ,η)\partial_x f(\xi, b + k) - \partial_x f(\xi, b) = k\,\partial_y\partial_x f(\xi, \eta). Hence

Δ(h,k)=∂y∂xf(ξ,η),ξ∈(a,a+h), η∈(b,b+k).\Delta(h, k) = \partial_y\partial_x f(\xi, \eta), \qquad \xi \in (a, a + h), \ \eta \in (b, b + k).

The numerator of Δ\Delta is symmetric in the roles of xx and yy. Repeating with ψ(y)=f(a+h,y)−f(a,y)\psi(y) = f(a + h, y) - f(a, y) gives Δ(h,k)=∂x∂yf(ξ′,η′)\Delta(h, k) = \partial_x\partial_y f(\xi', \eta') with other intermediate points. As (h,k)→(0,0)(h, k) \to (0, 0), intermediate points tend to (a,b)(a, b) and, by continuity of both second derivatives, ∂y∂xf(a,b)=lim⁡Δ(h,k)=∂x∂yf(a,b)\partial_y\partial_x f(a, b) = \lim \Delta(h, k) = \partial_x\partial_y f(a, b).

∎

The proof shows where continuity is used: to pass from the value of Δ\Delta at intermediate points to its value at (a,b)(a, b). If mixed derivatives merely existed without continuity, quotient Δ(h,k)\Delta(h, k) would still be the same for both differentiation orders, but might lack a double limit as (h,k)→(0,0)(h, k) \to (0, 0), and the two differentiation orders are two different ways (two iterated limits) of approaching that point.

The counterexample

Let f(x,y)=xy (x2−y2)x2+y2f(x, y) = \dfrac{xy\,(x^2 - y^2)}{x^2 + y^2} if (x,y)≠(0,0)(x, y) \neq (0, 0) and f(0,0)=0f(0, 0) = 0. In polar coordinates, f=14r2sin⁡4θf = \tfrac14 r^2\sin 4\theta: a four-lobed saddle. Away from the origin it is C∞C^\infty. At the origin, calculating directly,

∂xf(0,y)=lim⁡h→0f(h,y)−f(0,y)h=lim⁡h→0y (h2−y2)h2+y2=−y,∂yf(x,0)=x.\partial_x f(0, y) = \lim_{h \to 0}\frac{f(h, y) - f(0, y)}{h} = \lim_{h \to 0}\frac{y\,(h^2 - y^2)}{h^2 + y^2} = -y, \qquad \partial_y f(x, 0) = x.

Differentiating those linear functions: ∂y∂xf(0,0)=−1\partial_y\partial_x f(0, 0) = -1 and ∂x∂yf(0,0)=+1\partial_x\partial_y f(0, 0) = +1. Both mixed derivatives exist at the origin and do not agree. More: ff is class C1C^1 (its gradient exists and is continuous), so even class C1C^1 is insufficient.

The cause is what the proof predicts. Away from the origin both mixed derivatives equal

∂y∂xf(x,y)=∂x∂yf(x,y)=x6+9x4y2−9x2y4−y6(x2+y2)3=cos⁡2θ (1+2sin⁡22θ),\partial_y\partial_x f(x, y) = \partial_x\partial_y f(x, y) = \frac{x^6 + 9x^4y^2 - 9x^2y^4 - y^6}{(x^2 + y^2)^3} = \cos 2\theta\,\big(1 + 2\sin^2 2\theta\big),

a function only of angle θ\theta (homogeneous of degree 0). On axis xx (θ=0\theta = 0) it equals 11; on axis yy (θ=π/2\theta = \pi/2) it equals −1-1; at θ=π/4\theta = \pi/4 it equals 00, and takes every value between −2-\sqrt2 and 2\sqrt2. It has no limit as (x,y)→(0,0)(x, y) \to (0, 0), so second derivatives are not continuous at the origin, the missing assumption.

InteractiveWhen mixed derivatives do not commute
f(x,y)=xy(x2−y2)x2+y2f(x,y) = \dfrac{xy(x^2-y^2)}{x^2+y^2}: four lobes around the origin
Double quotient Δ(h,k)\Delta(h,k) by step size, on a logarithmic scale
h = k: Δ = 0h ≪ k: Δ → −1k ≪ h: Δ → +1log₁₀ h →log₁₀ k ↑
Both mixed derivatives at the origin, with decreasing steps
outer step∂y(∂xf)\partial_y(\partial_x f)∂x(∂yf)\partial_x(\partial_y f)
10⁻¹−1.0000001.000000
10⁻²−1.0000001.000000
10⁻³−1.0000001.000000
10⁻⁴−1.0000001.000000
10⁻⁵−1.0000001.000000
10⁻⁶−1.0000001.000000
Second mixed derivative away from the origin along the ray at angle θ\theta (no limit at 0)
+1−10°180°
m = 4.0
20°
Step hh (in xx)10−6.010^{-6.0}
Step kk (in yy)10−3.010^{-3.0}
Δ(h,k)\Delta(h, k)−0.999998
Second derivative along ray θ\theta1.3991
Δ(h,k)=(h2−k2)/(h2+k2)\Delta(h,k) = (h^2 - k^2)/(h^2 + k^2) depends only on h/kh/k: the double limit as (h,k)→(0,0)(h,k) \to (0,0) does not exist, and the order of the limits matters.
Upper left, surface ff with a ray from the origin. On the right, double quotient Δ(h,k)=(h2−k2)/(h2+k2)\Delta(h, k) = (h^2 - k^2)/(h^2 + k^2) for all steps (h,k)(h, k) on logarithmic axes: it depends only on ratio h/kh/k, so is constant along diagonals. With h≪kh \ll k it equals −1-1 and with k≪hk \ll h it equals +1+1; it is zero exactly on diagonal h=kh = k. Below, the table computes both mixed derivatives with decreasing steps (inner step is outer times 10−m10^{-m}): lower mm to 00 and see what happens when steps are equal. To its right, the second derivative away from the origin on a ray of angle θ\theta: it oscillates between −2-\sqrt2 and 2\sqrt2, so has no limit at 00.

In Rn\R^n, symmetry has a spectral consequence used constantly. Since H(a)\mat{H}(\vb{a}) is real symmetric, the spectral theorem says it has nn real eigenvalues and an orthonormal eigenvector basis. This makes “directions of maximum and minimum curvature” meaningful.

Second-order Taylor in Rn\R^n

The multivariable Taylor proof is a good example of a general technique: reduce to one variable by restriction to a segment. The result, with three remainder versions, is the second-order multivariable Taylor expansion.

Proof

Let φ(t)=f(a+th)\varphi(t) = f(\vb{a} + t\vb{h}) for t∈[0,1]t \in [0, 1]. By the preceding section’s lemma, φ∈C2\varphi \in C^2, with φ′(0)=∇f(a)⊤h\varphi'(0) = \grad f(\vb{a})\T\vb{h} and φ′′(t)=h⊤H(a+th)h\varphi''(t) = \vb{h}\T\mat{H}(\vb{a} + t\vb{h})\vb{h}.

(1) The single-variable Taylor theorem with Lagrange remainder gives φ(1)=φ(0)+φ′(0)+12φ′′(θ)\varphi(1) = \varphi(0) + \varphi'(0) + \tfrac12\varphi''(\theta) for some θ∈(0,1)\theta \in (0, 1). Substitute the derivatives to obtain the formula.

(2) Let ω(r)=sup⁡∥x−a∥≤r∥H(x)−H(a)∥2\omega(r) = \sup_{\norm{\vb{x} - \vb{a}} \le r}\norm{\mat{H}(\vb{x}) - \mat{H}(\vb{a})}_2, tending to 0 with rr by continuity of H\mat{H}. Subtracting 12h⊤H(a)h\tfrac12\vb{h}\T\mat{H}(\vb{a})\vb{h} from formula (1),

∣12 h⊤(H(a+θh)−H(a))h∣≤12 ω(∥h∥) ∥h∥2=o(∥h∥2).\Big|\tfrac12\,\vb{h}\T\big(\mat{H}(\vb{a} + \theta\vb{h}) - \mat{H}(\vb{a})\big)\vb{h}\Big| \le \tfrac12\,\omega(\norm{\vb{h}})\,\norm{\vb{h}}^2 = o(\norm{\vb{h}}^2).

(3) With the single-variable function’s integral remainder, φ(1)−φ(0)−φ′(0)−12φ′′(0)=∫01(1−t) (φ′′(t)−φ′′(0))  ⁣dt\varphi(1) - \varphi(0) - \varphi'(0) - \tfrac12\varphi''(0) = \int_0^1 (1 - t)\,\big(\varphi''(t) - \varphi''(0)\big)\,\dd t. By assumption, ∣φ′′(t)−φ′′(0)∣=∣h⊤(H(a+th)−H(a))h∣≤L t ∥h∥3\abs{\varphi''(t) - \varphi''(0)} = \abs{\vb{h}\T(\mat{H}(\vb{a} + t\vb{h}) - \mat{H}(\vb{a}))\vb{h}} \le L\,t\,\norm{\vb{h}}^3. Since ∫01(1−t) t  ⁣dt=16\int_0^1 (1 - t)\,t\,\dd t = \tfrac16, error is at most L6∥h∥3\tfrac{L}{6}\norm{\vb{h}}^3.

∎

Each version has a use. Peano’s remainder is used in local proofs (critical-point classification below). Bound (3) is quantitative, making algorithms work: quadratic-model error grows like the cube of distance, with constant proportional to how much curvature changes. This explains the figure above and underlies trust-region methods: trust the quadratic model inside a disk and adapt its radius to how well prediction holds.

Higher orders

The same argument, using a single-variable expansion to order kk, gives

f(a+h)=∑∣α∣≤k∂αf(a)α! hα+o(∥h∥k)(f∈Ck),f(\vb{a} + \vb{h}) = \sum_{\abs{\alpha} \le k}\frac{\partial^\alpha f(\vb{a})}{\alpha!}\,\vb{h}^\alpha + o(\norm{\vb{h}}^k) \qquad (f \in C^k),

with multi-indices α=(α1,…,αn)\alpha = (\alpha_1, \dots, \alpha_n). The order-3 term is 16D3f(a)[h,h,h]\tfrac16 D^3f(\vb{a})[\vb{h}, \vb{h}, \vb{h}], where D3f(a)D^3f(\vb{a}) is a symmetric n×n×nn \times n \times n tensor (by repeated application of Schwarz’s theorem). In two variables, 16(fxxxh13+3fxxyh12h2+3fxyyh1h22+fyyyh23)\tfrac16\big(f_{xxx}h_1^3 + 3f_{xxy}h_1^2h_2 + 3f_{xyy}h_1h_2^2 + f_{yyy}h_2^3\big): the factors 3 are symmetry in action. Growth is explosive (n3n^3 entries, and nkn^k generally), so order 2 is the last routinely used in optimization.

Critical points and local geometry

A point a\vb{a} is critical (or stationary) if ∇f(a)=0\grad f(\vb{a}) = \vb{0}. At a critical point the Taylor model loses its linear part, leaving

f(a+h)−f(a)=12 h⊤H(a) h+o(∥h∥2)=12∑i=1nλici2+o(∥h∥2),f(\vb{a} + \vb{h}) - f(\vb{a}) = \tfrac12\,\vb{h}\T\mat{H}(\vb{a})\,\vb{h} + o(\norm{\vb{h}}^2) = \tfrac12\sum_{i=1}^n \lambda_i c_i^2 + o(\norm{\vb{h}}^2),

where λi\lambda_i are eigenvalues of H(a)\mat{H}(\vb{a}) and cic_i the coordinates of h\vb{h} in the orthonormal eigenvector basis. All local geometry lies in the signs of λi\lambda_i: the weighted sum of squares is a bowl if all positive, an inverted bowl if all negative, and a saddle if both signs occur.

InteractiveMinimum, maximum or saddle
log⁡10\log_{10} of each particle component amplitude: slope −λi/ln⁡10-\lambda_i/\ln 10
domain boundary
  • component along u1\vb{u}_1 (λ1\lambda_1)
  • component along u2\vb{u}_2 (λ2\lambda_2)
  • contours q>0q>0
  • contours q<0q<0
Cases
1.50
-1.00
30°
0.00
λ1, λ2\lambda_1,\ \lambda_21.50, −1.00
tr⁡H\tr\mat{H} and det⁡H\det\mat{H}0.50, −1.50
Escape or convergencedoubles every 0.69 time units
H\mat{H} indefinite: saddle.
Edit λ1\lambda_1, λ2\lambda_2 and the eigenvector angle of a 2×22\times 2 Hessian and view quadratic form q(h)=12h⊤Hhq(\vb{h}) = \tfrac12\vb{h}\T\mat{H}\vb{h} as contours (blue: q>0q > 0; red: q<0q < 0; gray: q=0q = 0) and as a surface. Particles follow continuous gradient descent, h˙=−Hh\dot{\vb{h}} = -\mat{H}\vb{h}: the component in ui\vb{u}_i is multiplied by e−λite^{-\lambda_i t}. With opposite signs they escape along the negative-eigenvalue direction, faster for larger ∣λ∣\abs{\lambda}. The lower graph shows log⁡∣ci(t)∣\log\abs{c_i(t)} is a line of slope −λi/ln⁡10-\lambda_i/\ln 10. Try the ‘flat valley’ (λ2=0\lambda_2 = 0): what does the Hessian decide there?

This is critical-point classification. The number of negative Hessian eigenvalues at a nondegenerate critical point is its index: 0 for a minimum, nn for a maximum and any intermediate value for a saddle.

Proof

For each unit direction v\vb{v}, the Peano expansion at h=tv\vb{h} = t\vb{v} gives f(a+tv)−f(a)=12t2 v⊤H(a)v+o(t2)f(\vb{a} + t\vb{v}) - f(\vb{a}) = \tfrac12t^2\,\vb{v}\T\mat{H}(\vb{a})\vb{v} + o(t^2).

(1) If a\vb{a} were a local minimum with v⊤Hv<0\vb{v}\T\mat{H}\vb{v} < 0 for some v\vb{v}, the right side would be negative for small tt, and f(a+tv)<f(a)f(\vb{a} + t\vb{v}) < f(\vb{a}), a contradiction. The maximum case is symmetric.

(3) Let u+\vb{u}_+ and u−\vb{u}_- be unit eigenvectors with λ+>0>λ−\lambda_+ > 0 > \lambda_-. Then f(a+tu+)−f(a)=12λ+t2+o(t2)>0f(\vb{a} + t\vb{u}_+) - f(\vb{a}) = \tfrac12\lambda_+t^2 + o(t^2) > 0 and f(a+tu−)−f(a)=12λ−t2+o(t2)<0f(\vb{a} + t\vb{u}_-) - f(\vb{a}) = \tfrac12\lambda_-t^2 + o(t^2) < 0 for small t≠0t \ne 0. Every neighborhood contains points with values above and below f(a)f(\vb{a}).

Part (2) is most delicate: checking lines is insufficient, all directions must be controlled at once; this is the first proof exercise below. Part (4) is illustrated by the following examples.

∎

When the Hessian does not decide

Compare these functions at the origin, where all have zero gradient:

ffH(0)\mat{H}(0)What the origin is
x2+y4x^2 + y^4diag⁡(2,0)\diag(2, 0)strict minimum
x2−y4x^2 - y^4diag⁡(2,0)\diag(2, 0)saddle: rises in xx, falls in yy
x2+y3x^2 + y^3diag⁡(2,0)\diag(2, 0)neither minimum nor maximum: on axis yy, y3y^3 changes sign
x3−3xy2x^3 - 3xy^20\mat{0}monkey saddle (three hills and three valleys)

The first three have the same Hessian and different behavior. In the null direction (λ2=0\lambda_2 = 0), the quadratic term disappears and a higher-order term decides: y4y^4, −y4-y^4 or y3y^3. The last, f=Re⁡(x+iy)3=r3cos⁡3θf = \operatorname{Re}(x + iy)^3 = r^3\cos 3\theta, has zero Hessian: the quadratic model is identically zero and sign is distributed among six sectors.

Two facts complete the picture, without proof here. First, a critical point with nonsingular Hessian is isolated: since H\mat{H} is the Jacobian of ∇f\grad f, the inverse function theorem makes ∇f\grad f injective near a\vb{a} and there are no other critical points in a neighborhood. Second, Morse’s lemma says that for ff of class C∞C^\infty, ff is locally, after a smooth coordinate change, exactly f(a)+12(±y12±⋯±yn2)f(\vb{a}) + \tfrac12(\pm y_1^2 \pm \cdots \pm y_n^2) with as many minus signs as the index.

In deep learning, degenerate situations are the norm. An overparameterized model has parameter-space directions that do not change the represented function, with zero curvature. Thus network-loss Hessians at points reached by training have many nearly zero eigenvalues, and saddle-point theory (how to escape them, the strict saddle property) matters more than isolated-minimum theory.

Directional curvature and the Rayleigh quotient

The second derivative of the function restricted to a line measures how much ff curves in that direction.

This is the Hessian’s Rayleigh quotient. A naming warning: it is the second derivative of the profile of ff along the line, not the geometric curvature of curve t↦(t,f(a+tv))t \mapsto (t, f(\vb{a} + t\vb{v})), which is φ′′/(1+φ′2)3/2\varphi''/(1 + \varphi'^2)^{3/2}. They agree when slope in that direction is zero (∇f(a)⊤v=0\grad f(\vb{a})\T\vb{v} = 0), and thus in all directions at once at a critical point; there κ(v)\kappa(\vb{v}) is also the normal curvature of surface z=f(x)z = f(\vb{x}) in direction v\vb{v} (Euler’s theorem on principal curvatures).

Proof

By orthonormality, Hv=∑iλiciui\mat{H}\vb{v} = \sum_i\lambda_ic_i\vb{u}_i and v⊤Hv=∑iλici2\vb{v}\T\mat{H}\vb{v} = \sum_i\lambda_ic_i^2, an average of the λi\lambda_i with weights ci2≥0c_i^2 \ge 0 summing to 1. An average lies between the minimum and maximum of its values and reaches the maximum when all weight is on the maximizing index.

∎

In the plane, with u1\vb{u}_1 at angle φ\varphi, this is κ(θ)=λ1cos⁡2(θ−φ)+λ2sin⁡2(θ−φ)\kappa(\theta) = \lambda_1\cos^2(\theta - \varphi) + \lambda_2\sin^2(\theta - \varphi): in polar coordinates it draws a “peanut” touching the circle of radius λ1\lambda_1 at u1\vb{u}_1 and narrowing to λ2\lambda_2 at u2\vb{u}_2.

Why gradient descent zigzags

Let f(h)=12h⊤Hhf(\vb{h}) = \tfrac12\vb{h}\T\mat{H}\vb{h} with H\mat{H} positive definite, the model of any function near a nondegenerate minimum. Gradient descent with step η\eta is hk+1=hk−ηHhk=(I−ηH)hk\vb{h}_{k+1} = \vb{h}_k - \eta\mat{H}\vb{h}_k = (\mat{I} - \eta\mat{H})\vb{h}_k. In the eigenvector basis it decouples: component cic_i is multiplied at each step by 1−ηλi1 - \eta\lambda_i.

  • Stability. It converges from every starting point if and only if ∣1−ηλi∣<1\abs{1 - \eta\lambda_i} < 1 for every ii, that is, 0<η<2/λ10 < \eta < 2/\lambda_1. With ηλ1≥2\eta\lambda_1 \ge 2 the highest-curvature component is amplified and the method diverges.
  • Zigzag. If ηλ1>1\eta\lambda_1 > 1, factor 1−ηλ11 - \eta\lambda_1 is negative: that component changes sign each step, so the iterate bounces from one valley wall to the other.
  • Slowness. The flattest component advances with factor 1−ηλn1 - \eta\lambda_n, very close to 1 if λn≪λ1\lambda_n \ll \lambda_1. With the largest stable step (η≈2/λ1\eta \approx 2/\lambda_1), that factor is 1−2/κ1 - 2/\kappa, where κ=λ1/λn\kappa = \lambda_1/\lambda_n is the Hessian’s condition number.
  • Best step. Minimizing max⁡i∣1−ηλi∣\max_i\abs{1 - \eta\lambda_i} over η\eta balances both extremes: 1−ηλn=−(1−ηλ1)1 - \eta\lambda_n = -(1 - \eta\lambda_1), giving η⋆=2λ1+λn\eta^\star = \dfrac{2}{\lambda_1 + \lambda_n} and contraction factor ρ⋆=λ1−λnλ1+λn=κ−1κ+1\rho^\star = \dfrac{\lambda_1 - \lambda_n}{\lambda_1 + \lambda_n} = \dfrac{\kappa - 1}{\kappa + 1}.

Factor (κ−1)/(κ+1)(\kappa - 1)/(\kappa + 1) is a bound that no constant step can improve. For the Rosenbrock function at its minimum, κ≈2508\kappa \approx 2508 (you calculate it in an exercise), so ρ⋆≈0.9992\rho^\star \approx 0.9992 and ln⁡(103)/ln⁡(1/ρ⋆)≈8700\ln(10^3)/\ln(1/\rho^\star) \approx 8700 steps are needed just to reduce error a thousandfold, even with the optimal step. This slowness is what second-order and momentum methods try to solve.

InteractiveCurvature in each direction
Curvature v⊤Hv\vb{v}^\top\mat{H}\vb{v} in each unit direction v\vb{v} (polar coordinates)
dashed circle: λmax = 1
Gradient descent on f(h)=12h⊤Hhf(\vb{h}) = \tfrac12\vb{h}^\top\mat{H}\vb{h}
minimum at origin
log⁡10∥hk∥\log_{10}\norm{\vb{h}_k} versus number of steps kk
reduction by 10³
  • curvature v⊤Hv\vb{v}^\top\mat{H}\vb{v}
  • descent with chosen step
  • optimal step
20.0
25°
s = 0.70
30
Curvature in the chosen direction v⊤Hv\vb{v}^\top\mat{H}\vb{v}0.729
λmax⁡, λmin⁡\lambda_{\max},\ \lambda_{\min}1.00, 0.050
Factor per step max⁡i∣1−ηλi∣\max_i \abs{1 - \eta\lambda_i}0.930
Steps to reduce ∥h∥\norm{\vb{h}} by 10310^376
With optimal step 2/(λmax⁡+λmin⁡)2/(\lambda_{\max}+\lambda_{\min})69 steps, factor 0.905
With ηλmax⁡>1\eta\lambda_{\max} > 1 the component along u1\vb{u}_1 changes sign at every step: this is the zigzag across the valley. Meanwhile, the component along u2\vb{u}_2 barely advances.
Left: curvature v⊤Hv\vb{v}\T\mat{H}\vb{v} of a Hessian with λmax⁡=1\lambda_{\max} = 1 in polar coordinates. Drag the blue point: the marked segment measures curvature in that direction, maximal along u1\vb{u}_1 and minimal along u2\vb{u}_2. Right: gradient descent on contours of 12h⊤Hh\tfrac12\vb{h}\T\mat{H}\vb{h} with step η=s⋅2/λmax⁡\eta = s\cdot 2/\lambda_{\max}. Increase κ\kappa and the step: the path zigzags across the valley and moves slowly along it. With s>1s > 1 it diverges. The lower graph compares with optimal step 2/(λmax⁡+λmin⁡)2/(\lambda_{\max} + \lambda_{\min}), whose slope is log⁡10κ−1κ+1\log_{10}\frac{\kappa - 1}{\kappa + 1}. Also drag starting point h0\vb{h}_0.

The Hessian–vector product

With nn parameters, the Hessian has n2n^2 entries. For n=106n = 10^6 these are 101210^{12} numbers, about 4 TB in float32, while one parameter vector occupies 4 MB. Forming H\mat{H} is impossible in models of that size, yet almost everything we need from curvature (largest eigenvalue, an approximate Newton step, the effect of H−1\mat{H}\inv on a vector) can be computed using one operation: multiply H\mat{H} by a vector.

That formula says two things implementable in two ways.

  • Approximate, with two gradients. Central difference ∇f(x+εv)−∇f(x−εv)2ε\dfrac{\grad f(\vb{x} + \eps\vb{v}) - \grad f(\vb{x} - \eps\vb{v})}{2\eps} approximates Hv\mat{H}\vb{v} with error O(ε2)\bigO(\eps^2) (plus roundoff, growing like 1/ε1/\eps) and needs only a gradient function. This is the first implementation and what you will build from scratch.
  • Exact, with automatic differentiation. Hv\mat{H}\vb{v} is the Jacobian–vector product (JVP) of function ∇f\grad f in direction v\vb{v}. In an automatic differentiation framework this is “forward over reverse”: compute the gradient with backpropagation and propagate a tangent v\vb{v} forward through that calculation. The “reverse over reverse” alternative differentiates scalar ∇f(x)⊤v\grad f(\vb{x})\T\vb{v} with respect to x\vb{x} and gives the same result because ∇x(∇f(x)⊤v)=Hv\grad_{\vb{x}}\big(\grad f(\vb{x})\T\vb{v}\big) = \mat{H}\vb{v} when v\vb{v} does not depend on x\vb{x}. This is Pearlmutter’s trick (1994), presented as an R{⋅}\mathcal{R}\{\cdot\} operator on the gradient computation itself.

Cost is the reason for all this. A gradient costs a few times evaluating ff (the cheap gradient principle), and an exact HVP costs a few times a gradient, with a constant factor independent of nn. Memory is that of vectors and gradient intermediates: O(n)\bigO(n), not O(n2)\bigO(n^2). A model whose curvature matrix fits on no disk admits thousands of HVPs. This idea of treating a matrix as a vector-to-vector function (matrix-free operators) underlies Krylov methods.

HVPs yield:

  • the largest eigenvalue via power iteration (which converges to the largest-magnitude eigenvalue: near a minimum it is λmax⁡\lambda_{\max}, but with strongly negative curvatures it may be λmin⁡\lambda_{\min}; the Rayleigh quotient at each step estimates λmax⁡\lambda_{\max}, improving with the square of ratio ∣λ2/λ1∣\abs{\lambda_2/\lambda_1}), or via Lanczos, which converges much sooner;
  • the Newton approximation Hs=−∇f\mat{H}\vb{s} = -\grad f solved by conjugate gradients, requiring only HVPs (Newton–CG);
  • the effect of H−1\mat{H}\inv on a vector, needed by influence functions;
  • the Hessian trace with Hutchinson’s estimator (randomized trace estimation);
  • the full spectrum of large networks: Ghorbani, Krishnan and Xiao (2019, arXiv:1901.10159) estimated deep-network Hessian eigenvalue density with Lanczos and only HVPs, describing a main body of eigenvalues near zero and a few much larger outliers.

Implementation from scratch

First, the preceding section’s tools programmed in NumPy from a gradient. The test problem is regularized logistic regression with n=400n = 400 examples and d=30d = 30 features at different scales, so the Hessian is ill-conditioned and power iteration has work to do. Since dd is small, we can also calculate the analytic Hessian and compare.

[ ]Finite-difference HVP, Hessian by columns and power iterationBrowser
import numpy as np

rng = np.random.default_rng(0)
n, d = 400, 30
X = rng.normal(size=(n, d)) * np.linspace(2.0, 0.2, d)       # características con escalas distintas
w_true = rng.normal(size=d)
y = (X @ w_true + 2.0 * rng.normal(size=n) > 0).astype(float)
lam = 1e-3

def sigmoid(z):
    return 1.0 / (1.0 + np.exp(-z))

def loss(w):
    z = X @ w
    return np.mean(np.logaddexp(0.0, z) - y * z) + 0.5 * lam * w @ w

def grad(w):
    return X.T @ (sigmoid(X @ w) - y) / n + lam * w

def hess(w):                                                  # analítico: solo para comparar
    p = sigmoid(X @ w)
    return (X.T * (p * (1 - p))) @ X / n + lam * np.eye(d)

def hvp_fd(grad_f, x, v, eps=1e-5):
    """H v por diferencias centradas de gradientes: dos gradientes, ningún hessiano."""
    return (grad_f(x + eps * v) - grad_f(x - eps * v)) / (2 * eps)

def hessian_fd(grad_f, x, eps=1e-5):
    """Hessiano completo columna a columna: d productos hessiano-vector con los vectores de la base."""
    m = x.size
    H = np.column_stack([hvp_fd(grad_f, x, np.eye(m)[:, j], eps) for j in range(m)])
    return (H + H.T) / 2

def power_iteration_hessian(grad_f, x, iters=200, seed=0):
    """Autovalor de mayor módulo del hessiano en x usando solo HVPs, con su cociente de Rayleigh."""
    v = np.random.default_rng(seed).normal(size=x.size)
    v /= np.linalg.norm(v)
    historia = []
    for _ in range(iters):
        Hv = hvp_fd(grad_f, x, v)
        historia.append(v @ Hv)                               # cociente de Rayleigh
        v = Hv / np.linalg.norm(Hv)
    return historia[-1], v, np.array(historia)

# el mínimo, por Newton (aquí sí podemos permitirnos el hessiano: d = 30)
w = np.zeros(d)
for it in range(30):
    g = grad(w)
    if np.linalg.norm(g) < 1e-12:
        break
    w -= np.linalg.solve(hess(w), g)
print("Newton:", it, "iteraciones, |grad| =", f"{np.linalg.norm(grad(w)):.1e}", " f =", round(loss(w), 6))

H_exacto = hess(w)
ev = np.linalg.eigvalsh(H_exacto)
print("autovalores exactos: min =", f"{ev[0]:.3e}", " max =", f"{ev[-1]:.4f}", " condición =", f"{ev[-1] / ev[0]:.1f}")
print("hessiano por diferencias, error máximo:", f"{np.abs(hessian_fd(grad, w) - H_exacto).max():.1e}")

lmax, v, historia = power_iteration_hessian(grad, w, iters=100)
print("potencia con HVP: lmax =", f"{lmax:.6f}", " error =", f"{abs(lmax - ev[-1]):.1e}", "  |l2/l1| =", round(ev[-2] / ev[-1], 3))
for k in (5, 10, 20, 50, 100):
    print(f"  iteración {k:3d}: error del autovalor = {abs(historia[k - 1] - ev[-1]):.2e}")

Three observations from the output. The finite-difference Hessian agrees with the analytic one to maximum error 10−1110^{-11}, because each column is an HVP and central-difference error is order ε2\eps^2 plus roundoff. Power iteration converges, but slowly: ratio ∣λ2/λ1∣=0.958\abs{\lambda_2/\lambda_1} = 0.958 is close to 1, and the Rayleigh quotient converges like (λ2/λ1)2k(\lambda_2/\lambda_1)^{2k}, so eventually error is multiplied by 0.9180.918 each iteration (initially it decreases faster while other eigenvalues matter). Most importantly, power_iteration_hessian never builds a matrix; it receives a grad_f function and works entirely with vectors, so would work equally with n=106n = 10^6.

Now critical-point analysis. Himmelblau’s function, f(x,y)=(x2+y−11)2+(x+y2−7)2f(x, y) = (x^2 + y - 11)^2 + (x + y^2 - 7)^2, is the classic test because it has four minima, four saddles and one local maximum. Newton on ∇f=0\grad f = \vb{0} converges to any critical point without distinguishing type, so run it from many points and classify each result by Hessian eigenvalues.

[ ]Himmelblau critical pointsBrowser
import numpy as np

def f_h(p):
    x, y = p
    return (x * x + y - 11) ** 2 + (x + y * y - 7) ** 2

def grad_h(p):
    x, y = p
    return np.array([4 * x * (x * x + y - 11) + 2 * (x + y * y - 7),
                     2 * (x * x + y - 11) + 4 * y * (x + y * y - 7)])

def hess_h(p):
    x, y = p
    return np.array([[12 * x * x + 4 * y - 42, 4 * x + 4 * y],
                     [4 * x + 4 * y, 4 * x + 12 * y * y - 26]])

def newton_critico(p, iters=80):
    for _ in range(iters):
        try:
            paso = np.linalg.solve(hess_h(p), grad_h(p))
        except np.linalg.LinAlgError:
            return None
        p = p - paso
        if not np.all(np.isfinite(p)) or np.abs(p).max() > 1e3:
            return None
        if np.linalg.norm(paso) < 1e-13:
            break
    return p if np.linalg.norm(grad_h(p)) < 1e-9 else None

rng = np.random.default_rng(3)
encontrados = []
for _ in range(400):
    p = newton_critico(rng.uniform(-6, 6, size=2))
    if p is not None and not any(np.linalg.norm(p - q) < 1e-6 for q in encontrados):
        encontrados.append(p)

def tipo(ev):
    if ev[0] > 0:
        return "mínimo"
    if ev[-1] < 0:
        return "máximo"
    return "silla"

filas = sorted(encontrados, key=lambda p: f_h(p))
print(f"{len(filas)} puntos críticos\n   x         y        f(x,y)    autovalores del hessiano     tipo")
cuentas = {"mínimo": 0, "silla": 0, "máximo": 0}
for p in filas:
    ev = np.linalg.eigvalsh(hess_h(p))
    t = tipo(ev)
    cuentas[t] += 1
    print(f"{p[0]:8.4f} {p[1]:8.4f} {f_h(p):10.4f}   {ev[0]:8.3f} {ev[1]:8.3f}     {t}")
print(cuentas)

Results agree with theory: four minima with f=0f = 0 and positive-definite Hessian, four saddles with one negative and one positive eigenvalue, and a local maximum with both negative. Notice Newton “finds” saddles and the maximum as easily as minima because it seeks gradient zeros rather than low values of ff: pure Newton is not a minimization method. Practical methods (damped Newton, trust regions) correct this by looking at eigenvalue signs.

Finally, the finite-difference step ε\eps tradeoff. Central-difference HVP error has two terms: truncation, proportional to ε2\eps^2 due to the third derivative, and roundoff, proportional to u/εu/\eps, where u≈10−16u \approx 10^{-16} is double-precision unit roundoff and gradient roundoff is amplified by division by 2ε2\eps. The sum’s minimum is at ε∼u1/3≈5×10−6\eps \sim u^{1/3} \approx 5\times 10^{-6}, with relative error of order u2/3≈10−11u^{2/3} \approx 10^{-11}.

[ ]Optimal step for finite-difference HVPBrowser
import numpy as np
import matplotlib.pyplot as plt

v = np.random.default_rng(1).normal(size=d)                 # d, w, grad, H_exacto vienen de la celda anterior
ref = H_exacto @ v
epsilons = 10.0 ** np.arange(-1, -13.5, -0.5)
errores = np.array([np.linalg.norm(hvp_fd(grad, w, v, e) - ref) / np.linalg.norm(ref) for e in epsilons])

i = int(np.argmin(errores))
print(f"mejor eps = {epsilons[i]:.1e}, error relativo = {errores[i]:.1e}")
for e, r in zip(epsilons[::2], errores[::2]):
    print(f"  eps = {e:.0e}   error relativo = {r:.2e}")

plt.loglog(epsilons, errores, "o-", label="error medido")
plt.loglog(epsilons, errores[0] * (epsilons / epsilons[0]) ** 2, "--", color="gray", label="pendiente 2: truncamiento")
plt.loglog(epsilons, errores[-1] * (epsilons[-1] / epsilons), ":", color="gray", label="pendiente -1: redondeo")
plt.xlabel("eps"); plt.ylabel("error relativo del HVP"); plt.legend(); plt.show()

The graph is V-shaped on logarithmic axes: truncation dominates on the right (slope 2), roundoff on the left (slope −1-1). Too small an ε\eps does not improve precision: it worsens it. In float32, with u≈6×10−8u \approx 6\times 10^{-8}, the optimum is near 4×10−34\times 10^{-3} and best possible error is order 10−510^{-5}, another reason to use exact automatic-differentiation HVPs when training in reduced precision.

The professional version

In an automatic differentiation framework everything is calculated exactly without choosing ε\eps. PyTorch offers three routes and all give the same result: torch.func.hessian (full Hessian, only for small models), jvp(grad(loss), ...) (forward over reverse, Pearlmutter’s HVP) and double torch.autograd.grad with create_graph=True (reverse over reverse, from higher-order differentiation and autograd’s dynamic graph). With a SciPy LinearOperator calling the HVP, extreme eigenvalues are obtained by Lanczos without forming the matrix. The cell runs locally because it uses PyTorch.

[ ]Exact HVP and extreme eigenvalues with PyTorch and SciPyLocal GPU
import numpy as np
import torch
from torch.func import grad, jvp, hessian
from scipy.sparse.linalg import LinearOperator, eigsh

torch.manual_seed(0)
torch.set_default_dtype(torch.float64)

n, d_in, d_h = 256, 5, 16
X = torch.randn(n, d_in)
y = torch.tanh(X @ torch.randn(d_in)) + 0.1 * torch.randn(n)
P = d_h * d_in + d_h + d_h + 1                         # 113 parámetros de un MLP 5 -> 16 -> 1

def loss(theta):
    W1 = theta[: d_h * d_in].view(d_h, d_in)
    b1 = theta[d_h * d_in : d_h * d_in + d_h]
    w2 = theta[d_h * d_in + d_h : d_h * d_in + 2 * d_h]
    b2 = theta[-1]
    pred = torch.tanh(X @ W1.T + b1) @ w2 + b2
    return 0.5 * ((pred - y) ** 2).mean()

theta = 0.5 * torch.randn(P)
g = grad(loss)
for _ in range(4000):                                   # descenso por gradiente hasta un punto casi estacionario
    theta = theta - 0.2 * g(theta)
print("pérdida:", round(float(loss(theta)), 6), "  |grad|:", f"{float(g(theta).norm()):.1e}")

def hvp_exacto(theta, v):                               # modo directo sobre modo inverso: jvp de la función gradiente
    return jvp(g, (theta,), (v,))[1]

def hvp_inverso(theta, v):                              # inverso sobre inverso: grad de (grad f . v)
    th = theta.clone().requires_grad_(True)
    (gr,) = torch.autograd.grad(loss(th), th, create_graph=True)
    (hv,) = torch.autograd.grad(gr @ v, th)
    return hv

H = hessian(loss)(theta)                                # el hessiano completo: 113 x 113, solo para comparar
v = torch.randn(P)
Hv = H @ v
rel = lambda a: float((a - Hv).norm() / Hv.norm())
eps = 1e-5
fd = (g(theta + eps * v) - g(theta - eps * v)) / (2 * eps)
print("simetría del hessiano:", f"{float((H - H.T).abs().max()):.1e}")
print("jvp(grad):", f"{rel(hvp_exacto(theta, v)):.1e}", "  doble grad:", f"{rel(hvp_inverso(theta, v)):.1e}", "  diferencias:", f"{rel(fd):.1e}")

op = LinearOperator((P, P), dtype=np.float64,
                    matvec=lambda u: hvp_exacto(theta, torch.from_numpy(np.asarray(u, dtype=np.float64).ravel())).numpy())
lmax = eigsh(op, k=1, which="LA", return_eigenvectors=False)[0]
lmin = eigsh(op, k=1, which="SA", return_eigenvectors=False)[0]
ev = np.linalg.eigvalsh(H.numpy())
print(f"eigsh (solo HVPs): lmax = {lmax:.6f}  lmin = {lmin:.3e}")
print(f"eigvalsh (completo): lmax = {ev[-1]:.6f}  lmin = {ev[0]:.3e}")
print("autovalores < -1e-3:", int((ev < -1e-3).sum()), "  |autovalor| < 1e-3:", int((np.abs(ev) < 1e-3).sum()), " de", P)
print("los cinco mayores:", np.round(ev[-5:], 4))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Correspondence with what you programmed by hand is direct: jvp(g, ...) is hvp_fd with the exact derivative instead of the difference, double autograd.grad is the same product viewed as gradient of ∇f⊤v\grad f\T\vb{v}, and eigsh with a LinearOperator does what power_iteration_hessian did, but with Lanczos, converging in far fewer iterations. Also notice the spectrum at this nearly stationary point: of 113 eigenvalues, 72 have magnitude below 10−310^{-3} and 2 are negative by more than 10−310^{-3}, against a maximum of 3.43. There are many nearly flat directions, as critical-point analysis anticipated, and the Hessian is not positive semidefinite: there are two slightly negative-curvature directions, so gradient descent has stopped not near a well-formed minimum but on a nearly flat plateau with saddle features (and a small but nonzero gradient).

Common mistakes

Exercises

NumericCurvature in a direction
For f(x,y)=x2eyf(x, y) = x^2e^y at point (1,0)(1, 0), calculate directional curvature κ(v)=v⊤Hv/∥v∥2\kappa(\vb{v}) = \vb{v}\T\mat{H}\vb{v}/\norm{\vb{v}}^2 along v=(1,1)\vb{v} = (1, 1).
NumericRosenbrock conditioning
Rosenbrock function f(x,y)=(1−x)2+100(y−x2)2f(x, y) = (1 - x)^2 + 100(y - x^2)^2 has its minimum at (1,1)(1, 1). Calculate Hessian condition number κ=λmax⁡/λmin⁡\kappa = \lambda_{\max}/\lambda_{\min} there.
QuizSame Hessian, different point
f=x2+y4f = x^2 + y^4 and g=x2−y4g = x^2 - y^4 have the same Hessian at the origin. What can be concluded about each?
QuizThe zero Hessian
What kind of critical point does f(x,y)=x3−3xy2f(x, y) = x^3 - 3xy^2 have at the origin, and why does the Hessian not decide it?
QuizWhat Schwarz requires
Let f:R2→Rf : \R^2 \to \R and (a,b)(a, b) be a point where ∂x∂yf\partial_x\partial_y f and ∂y∂xf\partial_y\partial_x f exist. Which assumption guarantees ∂x∂yf(a,b)=∂y∂xf(a,b)\partial_x\partial_y f(a, b) = \partial_y\partial_x f(a, b)?
NumericHow many steps at the optimal step size
Gradient descent on a quadratic with Hessian eigenvalues 100100 and 11 uses optimal step η⋆=2/(λmax⁡+λmin⁡)\eta^\star = 2/(\lambda_{\max} + \lambda_{\min}). Error is multiplied by ρ⋆=(κ−1)/(κ+1)\rho^\star = (\kappa - 1)/(\kappa + 1) each step. What is the smallest integer number of steps kk with (ρ⋆)k≤10−6(\rho^\star)^k \le 10^{-6}?
QuizHessian versus Gauss–Newton
Let L(θ)=12∑iri(θ)2L(\vb{\theta}) = \tfrac12\sum_i r_i(\vb{\theta})^2 with residual Jacobian J\mat{J}. The Hessian is ∇2L=J⊤J+∑iri ∇2ri\hess L = \mat{J}\T\mat{J} + \sum_i r_i\,\hess r_i. Which statements are true?

More than one answer may be correct.

ProofPositive-definite Hessian implies a strict minimum
Prove: Let ff be class C2C^2 near a\vb{a}, with ∇f(a)=0\grad f(\vb{a}) = \vb{0} and H(a)\mat{H}(\vb{a}) positive definite. Then a\vb{a} is a strict local minimum.
0
Let λmin⁡>0\lambda_{\min} > 0 be the smallest eigenvalue of H(a)\mat{H}(\vb{a}).

Step 1 of 4. What is the first step?

ProofThe HVP is a JVP of the gradient
Prove: Let ff be class C2C^2. Then H(x)v= ⁣d ⁣dt∇f(x+tv)∣t=0\mat{H}(\vb{x})\vb{v} = \dfrac{\dd}{\dd t}\grad f(\vb{x} + t\vb{v})\Big|_{t = 0}, and hence calculating Hv\mat{H}\vb{v} costs the same as a Jacobian–vector product of function ∇f\grad f.
0
Define ψ(t)=∇f(x+tv)\vb{\psi}(t) = \grad f(\vb{x} + t\vb{v}), a function from R\R to Rn\R^n.

Step 1 of 3. How do you differentiate ψ\vb{\psi}?

CodeFinite-difference HVP and power iteration on the Hessian
Implement two functions receiving a grad_f(x) function returning the gradient. hvp_fd(grad_f, x, v, eps=1e-5) returns H(x)v\mat{H}(\vb{x})\vb{v} by central differences, calling grad_f exactly twice (tests count calls). power_iteration_hessian(grad_f, x, iters=300, eps=1e-5, seed=0) returns (lam, v): the Hessian's largest-magnitude eigenvalue with its sign, estimated by the Rayleigh quotient, and its unit eigenvector. Start from a random vector with np.random.default_rng(seed), normalize it, and at each iteration compute the HVP with hvp_fd, update lam with the Rayleigh quotient and renormalize. Do not build the Hessian.
import numpy as np

def hvp_fd(grad_f, x, v, eps=1e-5):
  """H(x) v por diferencias centradas de gradientes."""
  # tu código
  return np.zeros_like(x)

def power_iteration_hessian(grad_f, x, iters=300, eps=1e-5, seed=0):
  """Autovalor de mayor módulo del hessiano en x (con signo) y su vector propio, solo con HVPs."""
  # tu código
  return 0.0, np.zeros_like(x)
Shift+Enter to run

Summary

Key idea
The Hessian is the gradient’s Jacobian: the matrix saying how the gradient changes as you move. It is symmetric (Schwarz), hence has real curvatures in orthogonal directions. With it, a smooth function near each point resembles a quadratic whose eigenvalues decide whether it is a minimum, saddle or valley, and set the stable gradient-descent step limit. All this can be calculated in enormous models without forming the matrix, using Hessian–vector products.
  • Hessian Hij=∂i∂jfH_{ij} = \partial_i\partial_j f is the Jacobian of ∇f\grad f. It is symmetric if f∈C2f \in C^2 (Schwarz); without second-derivative continuity this can fail, as in xy(x2−y2)/(x2+y2)xy(x^2 - y^2)/(x^2 + y^2), where the mixed derivatives at the origin are −1-1 and +1+1.
  • Second-order Taylor in Rn\R^n: f(a+h)=f(a)+∇f(a)⊤h+12h⊤H(a)h+Rf(\vb{a} + \vb{h}) = f(\vb{a}) + \grad f(\vb{a})\T\vb{h} + \tfrac12\vb{h}\T\mat{H}(\vb{a})\vb{h} + R, with R=o(∥h∥2)R = o(\norm{\vb{h}}^2) (Peano), R=12h⊤(H(a+θh)−H(a))hR = \tfrac12\vb{h}\T(\mat{H}(\vb{a} + \theta\vb{h}) - \mat{H}(\vb{a}))\vb{h} (Lagrange) and ∣R∣≤L6∥h∥3\abs{R} \le \tfrac L6\norm{\vb{h}}^3 if H\mat{H} is LL-Lipschitz. Quadratic-model error grows as the cube of distance.
  • At a critical point, H≻0\mat{H} \succ 0 gives a strict minimum, H≺0\mat{H} \prec 0 a strict maximum, and an indefinite Hessian a saddle. A singular semidefinite Hessian gives no conclusion: x2+y4x^2 + y^4, x2−y4x^2 - y^4 and x2+y3x^2 + y^3 have the same H\mat{H}.
  • Curvature in direction v\vb{v} is Rayleigh quotient v⊤Hv/∥v∥2\vb{v}\T\mat{H}\vb{v}/\norm{\vb{v}}^2, between λmin⁡\lambda_{\min} and λmax⁡\lambda_{\max}. On a quadratic, gradient descent is stable if η<2/λmax⁡\eta < 2/\lambda_{\max}, zigzags if ηλmax⁡>1\eta\lambda_{\max} > 1, and its best contraction factor is (κ−1)/(κ+1)(\kappa - 1)/(\kappa + 1).
  • Hessian–vector product Hv= ⁣d ⁣dt∇f(x+tv)∣t=0\mat{H}\vb{v} = \tfrac{\dd}{\dd t}\grad f(\vb{x} + t\vb{v})|_{t = 0} costs a small multiple of a gradient (Pearlmutter), with linear memory. For finite differences the optimal step is ε∼10−5\eps \sim 10^{-5} in double precision; automatic differentiation is exact.
  • HVPs calculate the largest eigenvalue (power, Lanczos), approximate Newton steps (conjugate gradients) and products with H−1\mat{H}\inv, without forming the Hessian. The Hessian is not Gauss–Newton or Fisher: it can have negative curvature.