22.2 Multivariable Calculus

In the previous section, we studied a loss as a function of a single weight while holding every other weight fixed. Real training never works that way. Every step of gradient descent nudges all the weights at once, so we need to know how the loss responds to a joint move, and which joint move drives it down fastest. Having a million separate slopes, one per weight, does not by itself answer either question.

Yet under one modest hypothesis, those slopes answer both. When the loss is differentiable, the vector of slopes, called the gradient, predicts the effect of every small joint move at once to first order and points in the direction of steepest increase. To go further and tell a local minimum from a saddle, we need a symmetric table of second derivatives, the Hessian, which measures how the surface bends. This section develops what these two objects tell us about a function of many variables. How a program actually computes a gradient for a large network is a separate problem, which Section 22.3 takes up next.

Section 1.4 already stated the differentiation rules and put the gradient to work. Here we supply the foundations, much as Section 22.1 did for one variable: we prove when the linear approximation holds and how second derivatives classify critical points. Two results carry the entire section: the multivariable linear model and the second-derivative test. The short subsection on tangent planes and the closing material on Lagrange multipliers can safely be skipped on a first reading. Throughout, we will test each idea on a running example: the two-variable log-sum-exp function f(x,y)=log⁡(ex+ey)f(x, y) = \log(e^x + e^y) evaluated at (0,log⁡2)(0, \log 2). Its gradient will turn out to be the familiar softmax.

22.2.1 Partial Derivatives and the Gradient#

22.2.1.1 Partial Derivatives#

If we freeze every weight except w1w_1, the loss becomes a function of a single variable. Its ordinary derivative is the partial derivative ∂ℓ/∂w1\partial\ell/\partial w_1 from Section 1.4: geometrically, it is the slope of the one-dimensional slice of the graph of ℓ\ell obtained by varying only w1w_1. Just as in single-variable calculus, this slope predicts the effect of a small change ϵ1\epsilon_1 in w1w_1 alone,

ℓ(w1+ϵ1,w2,…,wN)≈ℓ(w1,w2,…,wN)+ϵ1∂ℓ∂w1(w1,w2,…,wN).(22.2.1)\ell(w_1+\epsilon_1, w_2, \ldots, w_N) \approx \ell(w_1, w_2, \ldots, w_N) + \epsilon_1 \frac{\partial \ell}{\partial w_1}(w_1, w_2, \ldots, w_N). \tag{22.2.1}

Let us compute the partial derivatives of our running example f(x,y)=log⁡(ex+ey)f(x, y) = \log(e^x + e^y). Holding yy fixed and differentiating with respect to xx gives ∂f/∂x=ex/(ex+ey)\partial f/\partial x = e^x/(e^x+e^y), and by symmetry ∂f/∂y=ey/(ex+ey)\partial f/\partial y = e^y/(e^x+e^y). At the point (0,log⁡2)(0, \log 2), we have ex=1e^x = 1 and ey=2e^y = 2, so f(0,log⁡2)=log⁡3≈1.0986f(0, \log 2) = \log 3 \approx 1.0986, ∂f/∂x=13\partial f/\partial x = \tfrac13, and ∂f/∂y=23\partial f/\partial y = \tfrac23. In other words, nudging yy alone raises ff twice as fast as nudging xx alone.

22.2.1.2 Differentiability and the Gradient#

Partial derivatives tell us the slope along each coordinate axis, one at a time. They do not automatically tell us what happens when all coordinates move together, for instance when we step from (0,log⁡2)(0, \log 2) by ϵ=(0.01,−0.03)\boldsymbol{\epsilon} = (0.01, -0.03). It is tempting to guess that the two coordinate-wise changes simply add, giving 13⋅0.01+23⋅(−0.03)\tfrac13 \cdot 0.01 + \tfrac23 \cdot (-0.03). That guess is actually a strong claim about how ff behaves near the point, and it requires a hypothesis.

The hypothesis is that near w\mathbf{w}, the function ℓ\ell looks linear up to an error that vanishes faster than the step size. Formally, we say that ℓ\ell is differentiable at w\mathbf{w} if there exists a linear map Λ\Lambda such that

ℓ(w+ϵ)=ℓ(w)+Λ(ϵ)+o(∥ϵ∥),(22.2.2)\ell(\mathbf{w} + \boldsymbol{\epsilon}) = \ell(\mathbf{w}) + \Lambda(\boldsymbol{\epsilon}) + o(\|\boldsymbol{\epsilon}\|), \tag{22.2.2}

where o(∥ϵ∥)o(\|\boldsymbol{\epsilon}\|) denotes any remainder that, when divided by ∥ϵ∥\|\boldsymbol{\epsilon}\|, tends to zero as ϵ→0\boldsymbol{\epsilon} \to \mathbf{0}.

Whenever such a linear map Λ\Lambda exists, the partial derivatives determine it completely. Setting ϵ=hei\boldsymbol{\epsilon} = h\mathbf{e}_i in (22.2.2), dividing both sides by hh, and letting h→0h \to 0 forces Λ(ei)=∂ℓ/∂wi\Lambda(\mathbf{e}_i) = \partial\ell/\partial w_i. Because Λ\Lambda is linear, its action on any joint step ϵ\boldsymbol{\epsilon} is then fixed:

Λ(ϵ)=Λ(∑i=1Nϵiei)=∑i=1Nϵi∂ℓ∂wi=ϵ⋅∇wℓ,∇wℓ=[∂ℓ∂w1,…,∂ℓ∂wN]⊤.\Lambda(\boldsymbol{\epsilon}) = \Lambda\Bigl(\sum_{i=1}^N \epsilon_i \mathbf{e}_i\Bigr) = \sum_{i=1}^N \epsilon_i \frac{\partial \ell}{\partial w_i} = \boldsymbol{\epsilon} \cdot \nabla_{\mathbf{w}} \ell, \qquad \nabla_{\mathbf{w}} \ell = \left[\frac{\partial \ell}{\partial w_1}, \ldots, \frac{\partial \ell}{\partial w_N}\right]^\top.

We call this column vector ∇wℓ\nabla_{\mathbf{w}}\ell of partial derivatives the gradient of ℓ\ell. Substituting it back into (22.2.2) gives the multivariable linear approximation

ℓ(w+ϵ)=ℓ(w)+ϵ⋅∇wℓ(w)+o(∥ϵ∥).(22.2.3)\ell(\mathbf{w} + \boldsymbol{\epsilon}) = \ell(\mathbf{w}) + \boldsymbol{\epsilon}\cdot \nabla_{\mathbf{w}} \ell(\mathbf{w}) + o(\|\boldsymbol{\epsilon}\|). \tag{22.2.3}

Compare this with the one-variable approximation f(x+ϵ)≈f(x)+ϵf′(x)f(x+\epsilon) \approx f(x) + \epsilon f'(x): the shape is identical, with the scalar slope replaced by a vector and ordinary multiplication replaced by a dot product. The gradient is the unique vector whose dot product with a step gives the first-order change in ℓ\ell. Of all the ways to think about a gradient, this is the one to remember. Throughout this book, we treat the gradient as a column vector.

Returning to our running example at (0,log⁡2)(0, \log 2), we have ∇f=[13,23]⊤\nabla f = [\tfrac13, \tfrac23]^\top. Plugging ϵ=(0.01,−0.03)\boldsymbol{\epsilon} = (0.01, -0.03) into (22.2.3) predicts f(0.01,log⁡2−0.03)≈log⁡3+13⋅0.01−23⋅0.03≈1.081946f(0.01, \log 2 - 0.03) \approx \log 3 + \tfrac13 \cdot 0.01 - \tfrac23 \cdot 0.03 \approx 1.081946. Notice that at every point (x,y)(x, y), the two entries of ∇f\nabla f are positive and sum to one: the gradient of log-sum-exp is the softmax p=softmax⁡(x,y)\mathbf{p} = \operatorname{softmax}(x, y), with entries ex/(ex+ey)e^x/(e^x+e^y) and ey/(ex+ey)e^y/(e^x+e^y).

It is worth pausing to see why differentiability asks for more than the mere existence of partial derivatives. Consider f(x,y)=2xy/(x2+y2)f(x, y) = 2xy/(x^2+y^2) with f(0,0)=0f(0, 0) = 0. Along both coordinate axes ff is identically zero, so both partial derivatives at the origin are 00, leaving the constant function 00 as the only possible linear model. Yet along the diagonal x=y≠0x = y \neq 0, we have f(x,x)=1f(x, x) = 1 no matter how close we get to the origin, so no linear approximation can hold there. Here ff is not even continuous at the origin, and Exercise 1 shows that even a continuous function can have all partial derivatives and still fail to be differentiable.

Fortunately, we rarely have to check (22.2.2) directly. A convenient sufficient condition is that all partial derivatives exist in a neighborhood of w\mathbf{w} and are continuous at w\mathbf{w} (Rudin, 1976). Since the partial derivatives of log-sum-exp are continuous everywhere, it is differentiable everywhere.

The definition of differentiability promises only that the approximation error is o(∥ϵ∥)o(\|\boldsymbol{\epsilon}\|), meaning it shrinks faster than ∥ϵ∥\|\boldsymbol{\epsilon}\|. How much faster is it in practice? Before running the next cell, guess by what factor the error of the linear model shrinks when we cut the step ϵ=(0.01,−0.03)\boldsymbol{\epsilon} = (0.01, -0.03) by a factor of ten. The experiment below uses plain NumPy to check.

import numpy as np
import torch
def lse(xy):  # f(x, y) = log(e^x + e^y), computed stably
    return np.logaddexp(xy[0], xy[1])

def grad_lse(xy):  # its gradient, the softmax of (x, y)
    return np.exp(xy - lse(xy))

xy0 = np.array([0.0, np.log(2)])
print('gradient:', grad_lse(xy0))
for scale in [1, 0.1, 0.01]:
    eps = scale * np.array([0.01, -0.03])
    linear = lse(xy0) + eps @ grad_lse(xy0)
    true = lse(xy0 + eps)
    print(f'|eps| {np.linalg.norm(eps):.1e}: linear {linear:.8f}, '
          f'true {true:.8f}, gap {true - linear:.3e}')
gradient: [0.33333333 0.66666667]
|eps| 3.2e-02: linear 1.08194562, true 1.08212418, gap 1.786e-04
|eps| 3.2e-03: linear 1.09694562, true 1.09694740, gap 1.779e-06
|eps| 3.2e-04: linear 1.09844562, true 1.09844564, gap 1.778e-08

At ∥ϵ∥≈0.03\|\boldsymbol{\epsilon}\| \approx 0.03, the linear model misses the true value by 1.79×10−41.79 \times 10^{-4} (only in the fourth decimal place), and each tenfold reduction in the step shrinks the gap by a factor of a hundred. That means the error is second order in the step, which is considerably tighter than differentiability alone guarantees. Soon, the Hessian will let us predict this gap accurately (Section 22.2.3.2).

22.2.1.3 Directional Derivatives#

So far we have used the gradient to predict small steps. It also gives the exact instantaneous slope along any direction, not just along the coordinate axes. Take any unit vector u\mathbf{u}, substitute ϵ=hu\boldsymbol{\epsilon} = h\mathbf{u} into (22.2.3), divide by hh, and let h→0h \to 0. The o(∥hu∥)o(\|h\mathbf{u}\|) remainder vanishes, leaving

lim⁡h→0ℓ(w+hu)−ℓ(w)h=u⋅∇wℓ(w).(22.2.4)\lim_{h \to 0} \frac{\ell(\mathbf{w} + h\mathbf{u}) - \ell(\mathbf{w})}{h} = \mathbf{u} \cdot \nabla_{\mathbf{w}} \ell(\mathbf{w}). \tag{22.2.4}

The limit on the left is the directional derivative of ℓ\ell along u\mathbf{u}; the right side says it is simply the projection of the gradient onto u\mathbf{u}. A single vector therefore encodes the slope in every possible direction at once.

Three directions for our running example at (0,log⁡2)(0, \log 2) illustrate the full range of behavior. Along the diagonal u=(1,1)/2\mathbf{u} = (1, 1)/\sqrt{2}, the slope is (13+23)/2=1/2≈0.707(\tfrac13 + \tfrac23)/\sqrt{2} = 1/\sqrt{2} \approx 0.707. In fact, this slope is the same at every point, because f(x+t,y+t)=log⁡(et(ex+ey))=f(x,y)+tf(x+t, y+t) = \log\bigl(e^t(e^x+e^y)\bigr) = f(x, y) + t: moving a distance 2 t\sqrt{2}\,t along the diagonal always raises ff by tt. Pointing directly against the gradient, along u=−(1,2)/5\mathbf{u} = -(1, 2)/\sqrt{5}, gives the slope −(13+43)/5=−5/3≈−0.745-(\tfrac13 + \tfrac43)/\sqrt{5} = -\sqrt{5}/3 \approx -0.745. Finally, along u=(2,−1)/5\mathbf{u} = (2, -1)/\sqrt{5}, the slope is (23−23)/5=0(\tfrac23 - \tfrac23)/\sqrt{5} = 0, so to first order ff does not change at all in that direction.

22.2.2 The Geometry of Gradients#

22.2.2.1 Steepest Descent#

Gradient descent (Section 2.1) nudges the parameters a short distance in the direction along which the loss drops fastest. By (22.2.4), we are looking for the unit vector v\mathbf{v} whose projection v⋅∇ℓ\mathbf{v}\cdot\nabla\ell is as negative as possible. Section 1.4 identified this direction from the cosine of the angle between v\mathbf{v} and the gradient; the Cauchy–Schwarz inequality gives an even cleaner proof and confirms that the direction is unique.

Proposition (steepest ascent and descent). At any point where ∇ℓ≠0\nabla \ell \neq \mathbf{0}, among all unit vectors v\mathbf{v}, the directional derivative v⋅∇ℓ\mathbf{v}\cdot\nabla \ell is maximized by v=∇ℓ/∥∇ℓ∥\mathbf{v} = \nabla\ell/\|\nabla\ell\| and minimized by v=−∇ℓ/∥∇ℓ∥\mathbf{v} = -\nabla\ell/\|\nabla\ell\|. Thus +∇ℓ+\nabla \ell is the direction of steepest ascent and −∇ℓ-\nabla \ell is the direction of steepest descent.

Proof. The Cauchy–Schwarz inequality (Section 21.1) states that ∣v⋅g∣≤∥v∥∥g∥|\mathbf{v}\cdot\mathbf{g}| \le \|\mathbf{v}\|\|\mathbf{g}\|, with equality if and only if v\mathbf{v} and g\mathbf{g} are collinear. For a unit vector v\mathbf{v} and g=∇ℓ\mathbf{g} = \nabla \ell, this reads

−∥∇ℓ∥  ≤  v⋅∇ℓ  ≤  ∥∇ℓ∥.-\|\nabla \ell\| \;\le\; \mathbf{v}\cdot\nabla \ell \;\le\; \|\nabla \ell\|.

Each bound is attained uniquely by a unit vector collinear with ∇ℓ\nabla \ell: the upper bound by v=∇ℓ/∥∇ℓ∥\mathbf{v} = \nabla \ell/\|\nabla \ell\| and the lower bound by v=−∇ℓ/∥∇ℓ∥\mathbf{v} = -\nabla \ell/\|\nabla \ell\|. ■\blacksquare

In our running example at (0,log⁡2)(0, \log 2), the steepest descent direction is −(1,2)/5-(1, 2)/\sqrt{5}, with slope −∥∇f∥=−5/3≈−0.745-\|\nabla f\| = -\sqrt{5}/3 \approx -0.745, the most negative of the three slopes we computed a moment ago. Taking a step along −∇wℓ-\nabla_{\mathbf{w}} \ell gives the familiar gradient-descent update

w←w−η ∇wℓ(w).\mathbf{w} \leftarrow \mathbf{w} - \eta\,\nabla_{\mathbf{w}} \ell(\mathbf{w}).

Notice that the update does not normalize the gradient. Its step length is η∥∇ℓ∥\eta\|\nabla\ell\|, which naturally shrinks as the gradient gets smaller near a minimum.

It is easy to overlook that "unit" in the proposition means unit Euclidean length, and that this is a modeling choice rather than a law of nature. If we instead constrain each coordinate of the step to have magnitude at most one, the steepest descent step becomes −sign⁡(∇ℓ)-\operatorname{sign}(\nabla \ell) applied coordinate by coordinate. At (0,log⁡2)(0, \log 2), that step is (−1,−1)(-1, -1), with slope −(13+23)=−1-(\tfrac13 + \tfrac23) = -1. Adaptive optimizers like Adam, which divide each coordinate of the update by a running estimate of its scale (Chapter 9), behave much more like this sign step than like Euclidean steepest descent. Exercise 4 explores steepest descent under other norms.

22.2.2.2 Gradients and Level Sets#

We can also read the gradient directly off a contour map, without talking about steps at all. A level set of ℓ\ell is the collection of all points where ℓ\ell takes a fixed value cc. Because moving along a level set keeps ℓ\ell constant, the directional derivative along any tangent direction should vanish.

Proposition (gradients are normal to level sets). Let ℓ\ell be differentiable at x\mathbf{x}. Then ∇ℓ(x)\nabla \ell(\mathbf{x}) is orthogonal to every direction tangent at x\mathbf{x} to the level set {x′:ℓ(x′)=c}\{\mathbf{x}' : \ell(\mathbf{x}') = c\} passing through x\mathbf{x}.

Proof. A vector v\mathbf{v} is tangent to the level set at x\mathbf{x} if v=γ′(0)\mathbf{v} = \boldsymbol{\gamma}'(0) for some differentiable curve γ(t)\boldsymbol{\gamma}(t) lying inside the level set with γ(0)=x\boldsymbol{\gamma}(0) = \mathbf{x}. Along such a curve, ℓ(γ(t))=c\ell(\boldsymbol{\gamma}(t)) = c for all tt, so the derivative of t↦ℓ(γ(t))t \mapsto \ell(\boldsymbol{\gamma}(t)) at t=0t = 0 must be zero. To first order, γ(t)=x+tv+o(t)\boldsymbol{\gamma}(t) = \mathbf{x} + t\mathbf{v} + o(t), so (22.2.3) tells us that this derivative equals v⋅∇ℓ(x)\mathbf{v}\cdot\nabla \ell(\mathbf{x}). Hence v⋅∇ℓ(x)=0\mathbf{v}\cdot\nabla \ell(\mathbf{x}) = 0. ■\blacksquare

Let us check this on our running example. The level set of ff passing through (0,log⁡2)(0, \log 2) is the curve ex+ey=3e^x + e^y = 3. Differentiating along it gives ex dx+ey dy=0e^x\,dx + e^y\,dy = 0, so the tangent direction at (0,log⁡2)(0, \log 2) is (ey,−ex)=(2,−1)(e^y, -e^x) = (2, -1). Taking the dot product with the gradient confirms (2,−1)⋅(13,23)=0(2, -1)\cdot(\tfrac13, \tfrac23) = 0, the direction of zero slope we found earlier.

On a contour map, the gradient therefore crosses every contour at a right angle and points toward higher values. Moreover, if neighboring contours differ by Δc\Delta c and sit a distance dd apart, the slope across them is roughly Δc/d\Delta c/d, so the gradient is longest wherever the contours are packed most tightly (Figure 22.2.1).

Figure 22.2.1:

Contours of a loss ℓ\ell (gray) with ∇ℓ\nabla \ell at several points. Each gradient is normal to its contour, points toward larger values, and is longest where the contours are packed most tightly.

22.2.2.3 Tangent Planes#

If we drop the error term from the linear approximation (22.2.3) and write the predicted height as zz, we obtain the tangent plane to the graph of ff at x0\mathbf{x}_0,

z=f(x0)+∇f(x0)⋅(x−x0).(22.2.5)z = f(\mathbf{x}_0) + \nabla f(\mathbf{x}_0)\cdot(\mathbf{x}-\mathbf{x}_0). \tag{22.2.5}

For our running example at (0,log⁡2)(0, \log 2), this plane is z=log⁡3+13x+23(y−log⁡2)z = \log 3 + \tfrac13 x + \tfrac23 (y - \log 2). Rewriting (22.2.5) as ∇f(x0)⋅(x−x0)−(z−f(x0))=0\nabla f(\mathbf{x}_0)\cdot(\mathbf{x}-\mathbf{x}_0) - (z - f(\mathbf{x}_0)) = 0 shows immediately that the vector [∇f(x0),−1]⊤[\nabla f(\mathbf{x}_0), -1]^\top is normal to the tangent plane in (x,z)(\mathbf{x}, z)-space. Dropping its height coordinate leaves ∇f(x0)\nabla f(\mathbf{x}_0), which is the normal to the level curve in the base plane (Figure 22.2.2).

Figure 22.2.2:

A surface z=f(x)z = f(\mathbf{x}) (blue) with its tangent plane at a point (orange). The vector [−∇f,1][-\nabla f, 1], the negative of [∇f,−1][\nabla f, -1], is normal to the plane (black arrow). Dropping the height coordinate leaves a multiple of ∇f\nabla f, which on the base plane (orange arrow) is normal to the level curve through the point (black).

22.2.2.4 Critical Points#

Deep learning losses are far too complicated to minimize in closed form, yet the linear model still gives a necessary condition that every minimum must obey, and gradient descent comes to rest right where this condition holds. Throughout this discussion, suppose ff is defined on all of Rn\mathbb{R}^n and differentiable at x0\mathbf{x}_0.

If ∇f(x0)≠0\nabla f(\mathbf{x}_0) \neq \mathbf{0}, we can step against it by setting ϵ=−η∇f(x0)\boldsymbol{\epsilon} = -\eta\nabla f(\mathbf{x}_0) with η>0\eta > 0. By (22.2.3), the resulting change in ff is −η∥∇f(x0)∥2+o(η)-\eta\|\nabla f(\mathbf{x}_0)\|^2 + o(\eta), which is strictly negative for every sufficiently small η\eta. Thus x0\mathbf{x}_0 cannot be a local minimum; repeating the argument with +η+\eta shows it cannot be a local maximum either. Therefore, at any local minimum or maximum, ∇f(x0)=0\nabla f(\mathbf{x}_0) = \mathbf{0}. Points where the gradient vanishes are called critical points. This first-order condition is necessary, not sufficient, and the next example shows what else we need to be sure we have found a global extremum.

Consider ψ(x,y)=xe−x2−y2\psi(x, y) = x e^{-x^2-y^2}, a surface with a positive hill for x>0x > 0 and a matching negative pit for x<0x \lt 0. Its partial derivatives are

∂ψ∂x=(1−2x2) e−x2−y2,∂ψ∂y=−2xy e−x2−y2.\frac{\partial \psi}{\partial x} = (1 - 2x^2)\,e^{-x^2-y^2}, \qquad \frac{\partial \psi}{\partial y} = -2xy\,e^{-x^2-y^2}.

Setting the second partial to zero forces either x=0x = 0 or y=0y = 0. Since x=0x = 0 makes the first partial equal to e−y2≠0e^{-y^2} \neq 0, we must have y=0y = 0, and then 1−2x2=01 - 2x^2 = 0 gives x=±1/2x = \pm 1/\sqrt{2}. The two critical points have values ψ(∓1/2,0)=∓e−1/2/2≈∓0.4289\psi(\mp 1/\sqrt{2}, 0) = \mp e^{-1/2}/\sqrt{2} \approx \mp 0.4289.

To conclude that (−1/2,0)(-1/\sqrt{2}, 0) is the global minimum, however, we also need to know that a global minimum exists at all. Outside the disc of radius R=2R = 2, the exponential decay forces ∣ψ∣≤Re−R2<0.04|\psi| \le R e^{-R^2} \lt 0.04, whereas inside the disc ψ(−1/2,0)≈−0.43\psi(-1/\sqrt{2}, 0) \approx -0.43. Because ψ\psi is continuous, it attains its minimum on the closed disc; since that minimum is below −0.04-0.04, it cannot lie on the boundary and must be a global minimum of ψ\psi on all of R2\mathbb{R}^2, hence a critical point. Comparing our two candidates identifies (−1/2,0)(-1/\sqrt{2}, 0) as the global minimum, and the same argument identifies (+1/2,0)(+1/\sqrt{2}, 0) as the global maximum. Skip the existence check and the logic breaks down: x3x^3 has a single critical point yet no minimum anywhere.

Notice also what first-order information cannot do: both the minimum and the maximum have zero gradient, so the gradient alone cannot tell them apart. For that, we turn to second derivatives (Section 22.2.3.3).

22.2.3 The Hessian#

22.2.3.1 Symmetry of the Hessian#

The linear model captures only first-order behavior. Whether a critical point is a minimum, a maximum, or neither depends on how the surface curves away from its tangent plane, and curvature is measured by second derivatives. A function of nn variables has n2n^2 second partial derivatives,

∂2f∂xi∂xj=∂∂xi(∂f∂xj),\frac{\partial^2 f}{\partial x_i \partial x_j} = \frac{\partial}{\partial x_i}\left(\frac{\partial f}{\partial x_j}\right),

which we collect into the Hessian matrix

Hf(x)=[∂2f∂x1∂x1⋯∂2f∂x1∂xn⋮⋱⋮∂2f∂xn∂x1⋯∂2f∂xn∂xn].(22.2.6)\mathbf{H}_f(\mathbf{x}) = \begin{bmatrix} \frac{\partial^2 f}{\partial x_1 \partial x_1} & \cdots & \frac{\partial^2 f}{\partial x_1 \partial x_n} \\ \vdots & \ddots & \vdots \\ \frac{\partial^2 f}{\partial x_n \partial x_1} & \cdots & \frac{\partial^2 f}{\partial x_n \partial x_n} \\ \end{bmatrix}. \tag{22.2.6}

Entry (i,j)(i, j) measures how fast the jj-th slope changes as we move along coordinate xix_i. The Hessian is also written ∇2f\nabla^2 f, and when the function and point are clear from context we simply write H\mathbf{H}.

For log-sum-exp, let us write (x1,x2)=(x,y)(x_1, x_2) = (x, y) and differentiate the softmax entries pi=exi/(ex1+ex2)p_i = e^{x_i}/(e^{x_1}+e^{x_2}) once more. Applying the quotient rule gives ∂pi/∂xj=piδij−pipj\partial p_i/\partial x_j = p_i\delta_{ij} - p_ip_j, where δij\delta_{ij} is 11 when i=ji = j and 00 otherwise. In matrix form,

Hf=diag⁡(p)−pp⊤,Hf(0,log⁡2)=[13−19−29−2923−49]=29[1−1−11].(22.2.7)\begin{aligned} \mathbf{H}_f &= \operatorname{diag}(\mathbf{p}) - \mathbf{p}\mathbf{p}^\top, \\ \mathbf{H}_f(0, \log 2) &= \begin{bmatrix} \tfrac13 - \tfrac19 & -\tfrac29 \\ -\tfrac29 & \tfrac23 - \tfrac49 \end{bmatrix} = \frac{2}{9}\begin{bmatrix} 1 & -1 \\ -1 & 1 \end{bmatrix}. \end{aligned} \tag{22.2.7}

This 2×22 \times 2 matrix has eigenvalue 00 along (1,1)(1, 1) and eigenvalue 49\tfrac49 along (1,−1)(1, -1). The zero eigenvalue matches what we already saw: along the diagonal (1,1)(1, 1), f(x+t,y+t)=f(x,y)+tf(x+t, y+t) = f(x, y) + t is completely linear and has no curvature at all. We will meet this positive semidefinite, singular Hessian again in the second-derivative test.

The n2n^2 entries of a Hessian are not independent. Whenever ff is twice continuously differentiable, the order of differentiation does not matter and the Hessian is symmetric, a classical result known as the Clairaut–Schwarz theorem (Rudin, 1976). That symmetry is crucial: it guarantees real eigenvalues and orthogonal eigenvectors via the spectral theorem (Section 21.3), which makes the second-derivative test possible.

Proposition (symmetry of the Hessian; Clairaut–Schwarz). Suppose the first partial derivatives of ff and the mixed partials ∂2f∂xi∂xj\frac{\partial^2 f}{\partial x_i \partial x_j} and ∂2f∂xj∂xi\frac{\partial^2 f}{\partial x_j \partial x_i} exist near x\mathbf{x}, and suppose the mixed partials are continuous at x\mathbf{x}. Then

∂2f∂xi∂xj(x)=∂2f∂xj∂xi(x).\frac{\partial^2 f}{\partial x_i \partial x_j}(\mathbf{x}) = \frac{\partial^2 f}{\partial x_j \partial x_i}(\mathbf{x}).

When this holds for all i,ji, j, the Hessian is symmetric: Hf=Hf⊤\mathbf{H}_f = \mathbf{H}_f^\top.

Proof. The idea is to realize both mixed partials as limits of the same quantity, the symmetric second difference

Δh=f(x+hei+hej)−f(x+hei)−f(x+hej)+f(x)h2,(22.2.8)\Delta_h = \frac{f(\mathbf{x}+h\mathbf{e}_i+h\mathbf{e}_j) - f(\mathbf{x}+h\mathbf{e}_i) - f(\mathbf{x}+h\mathbf{e}_j) + f(\mathbf{x})}{h^2}, \tag{22.2.8}

which is visibly unchanged if we swap ii and jj. Our task is to express Δh\Delta_h as a mixed partial evaluated at a nearby point. Define the one-variable function φ(t)=f(x+tei+hej)−f(x+tei)\varphi(t) = f(\mathbf{x}+t\mathbf{e}_i+h\mathbf{e}_j) - f(\mathbf{x}+t\mathbf{e}_i), so that h2Δh=φ(h)−φ(0)h^2\Delta_h = \varphi(h)-\varphi(0). Applying the mean value theorem (Section 22.1.3) twice, first to φ\varphi and then along xjx_j to the difference of first partials inside φ′\varphi', gives numbers τ\tau and σ\sigma between 00 and hh such that

φ(h)−φ(0)=h φ′(τ)=h[∂f∂xi(x+τei+hej)−∂f∂xi(x+τei)]=h2 ∂2f∂xj∂xi(x+τei+σej).\begin{aligned} \varphi(h)-\varphi(0) &= h\,\varphi'(\tau) = h\Bigl[\frac{\partial f}{\partial x_i}(\mathbf{x}+\tau\mathbf{e}_i+h\mathbf{e}_j) - \frac{\partial f}{\partial x_i}(\mathbf{x}+\tau\mathbf{e}_i)\Bigr] \\ &= h^2\,\frac{\partial^2 f}{\partial x_j \partial x_i}(\mathbf{x}+\tau\mathbf{e}_i+\sigma\mathbf{e}_j). \end{aligned}

Thus Δh=∂2f∂xj∂xi(ξh)\Delta_h = \frac{\partial^2 f}{\partial x_j \partial x_i}(\boldsymbol{\xi}_h) at a point ξh\boldsymbol{\xi}_h inside the square with corners x\mathbf{x} and x+hei+hej\mathbf{x} + h\mathbf{e}_i + h\mathbf{e}_j, at distance at most 2 ∣h∣\sqrt{2}\,|h| from x\mathbf{x}. Swapping the roles of ii and jj leaves Δh\Delta_h unchanged and yields Δh=∂2f∂xi∂xj(ξh′)\Delta_h = \frac{\partial^2 f}{\partial x_i \partial x_j}(\boldsymbol{\xi}'_h) at another point of the same square. Letting h→0h \to 0, continuity of the mixed partials at x\mathbf{x} sends the two expressions to the two mixed partials at x\mathbf{x}. Because they agree for every hh, their limits must agree as well. ■\blacksquare

The continuity hypothesis is strictly needed: there exist functions whose mixed partials exist everywhere yet fail to be continuous at the origin, where they disagree.

22.2.3.2 The Second-Order Taylor Approximation#

Just as the gradient supplies the best linear approximation to ff, the Hessian supplies the best quadratic approximation. To see where the coefficients come from, it helps to read them off an exact quadratic first. Take f(x1,x2)=a+b1x1+b2x2+c11x12+c12x1x2+c22x22f(x_1, x_2) = a + b_1x_1 + b_2x_2 + c_{11}x_1^{2} + c_{12}x_1x_2 + c_{22}x_2^{2}. Evaluating its value, gradient, and Hessian (22.2.6) at the origin gives

f(0,0)=a,∇f(0,0)=[b1b2],Hf(0,0)=[2c11c12c122c22],f(0,0) = a, \qquad \nabla f (0,0) = \begin{bmatrix}b_1 \\ b_2\end{bmatrix}, \qquad \mathbf{H}_f (0,0) = \begin{bmatrix}2 c_{11} & c_{12} \\ c_{12} & 2c_{22}\end{bmatrix},

and assembling these pieces recovers the polynomial exactly: f(x)=f(0)+∇f(0)⋅x+12x⊤Hf(0) xf(\mathbf{x}) = f(\mathbf{0}) + \nabla f(\mathbf{0}) \cdot \mathbf{x} + \tfrac12\mathbf{x}^\top \mathbf{H}_f(\mathbf{0})\, \mathbf{x}. The factor of 12\tfrac12 simply cancels the factor of 22 produced when we differentiate a square.

For a general function ff, this quadratic is no longer exact, but restricting ff to a line segment shows how accurate it is. Suppose ff is twice continuously differentiable near the segment connecting x0\mathbf{x}_0 to x\mathbf{x}. Write the displacement as δ=x−x0\boldsymbol{\delta} = \mathbf{x} - \mathbf{x}_0, and consider the single-variable slice φ(t)=f(x0+tδ)\varphi(t) = f(\mathbf{x}_0 + t\boldsymbol{\delta}). By the linear model (22.2.3), its first derivative is φ′(t)=∑i∂f∂xi(x0+tδ) δi\varphi'(t) = \sum_i \frac{\partial f}{\partial x_i}(\mathbf{x}_0 + t\boldsymbol{\delta})\,\delta_i. Because each partial derivative in this sum is itself differentiable, applying the same step once more gives the second derivative: φ′′(t)=∑i,jδj∂2f∂xj∂xi(x0+tδ) δi=δ⊤Hf(x0+tδ) δ\varphi''(t) = \sum_{i,j} \delta_j\frac{\partial^2 f}{\partial x_j\partial x_i}(\mathbf{x}_0 + t\boldsymbol{\delta})\,\delta_i = \boldsymbol{\delta}^\top \mathbf{H}_f(\mathbf{x}_0 + t\boldsymbol{\delta})\,\boldsymbol{\delta}.

Now apply the one-variable Taylor theorem with Lagrange remainder (Section 22.1.5.2) of degree one to φ\varphi between 00 and 11: there is some τ∈(0,1)\tau \in (0, 1) such that φ(1)=φ(0)+φ′(0)+12φ′′(τ)\varphi(1) = \varphi(0) + \varphi'(0) + \tfrac12\varphi''(\tau). Translating back to ff gives

f(x)=f(x0)+∇f(x0)⋅δ+12δ⊤Hf(ξ) δ,ξ=x0+τδ.f(\mathbf{x}) = f(\mathbf{x}_0) + \nabla f(\mathbf{x}_0)\cdot\boldsymbol{\delta} + \tfrac{1}{2}\boldsymbol{\delta}^\top \mathbf{H}_f(\boldsymbol{\xi})\,\boldsymbol{\delta}, \qquad \boldsymbol{\xi} = \mathbf{x}_0 + \tau\boldsymbol{\delta}.

This identity is exact, at the cost of evaluating the Hessian at an unknown intermediate point ξ\boldsymbol{\xi} on the segment rather than at x0\mathbf{x}_0. Because the second partials are continuous, replacing Hf(ξ)\mathbf{H}_f(\boldsymbol{\xi}) by Hf(x0)\mathbf{H}_f(\mathbf{x}_0) changes the quadratic term by at most 12∥Hf(ξ)−Hf(x0)∥ ∥δ∥2=o(∥δ∥2)\tfrac12\|\mathbf{H}_f(\boldsymbol{\xi}) - \mathbf{H}_f(\mathbf{x}_0)\|\,\|\boldsymbol{\delta}\|^2 = o(\|\boldsymbol{\delta}\|^2). That yields the second-order Taylor approximation:

f(x)=f(x0)+∇f(x0)⋅(x−x0)+12(x−x0)⊤Hf(x0)(x−x0)+o(∥x−x0∥2).(22.2.9)\begin{aligned} f(\mathbf{x}) &= f(\mathbf{x}_0) + \nabla f (\mathbf{x}_0) \cdot (\mathbf{x}-\mathbf{x}_0) \\ &\quad + \frac{1}{2}(\mathbf{x}-\mathbf{x}_0)^\top \mathbf{H}_f (\mathbf{x}_0) (\mathbf{x}-\mathbf{x}_0) + o(\|\mathbf{x}-\mathbf{x}_0\|^2). \end{aligned} \tag{22.2.9}

This quadratic model misses ff only by an error that vanishes faster than the squared step size, and it is the unique quadratic with that property. Whenever ff has three continuous derivatives, the error is of third order in the step.

Along any single direction v\mathbf{v}, a step tvt\mathbf{v} produces a quadratic term of t22v⊤Hv\tfrac{t^2}{2}\mathbf{v}^\top\mathbf{H}\mathbf{v}. The number v⊤Hv=d2dt2f(x0+tv)∣t=0\mathbf{v}^\top\mathbf{H}\mathbf{v} = \tfrac{d^2}{dt^2}f(\mathbf{x}_0 + t\mathbf{v})\big|_{t=0} is the second directional derivative: it measures the curvature of the slice of ff along v\mathbf{v}.

We can now explain the gap left by the linear model in our first code cell. For the step ϵ=(0.01,−0.03)\boldsymbol{\epsilon} = (0.01, -0.03) from (0,log⁡2)(0, \log 2), the Hessian (22.2.7) predicts a second-order correction of 12ϵ⊤Hϵ=19(ϵ1−ϵ2)2=19(0.04)2≈1.78×10−4\tfrac12\boldsymbol{\epsilon}^\top\mathbf{H}\boldsymbol{\epsilon} = \tfrac19(\epsilon_1 - \epsilon_2)^2 = \tfrac19 (0.04)^2 \approx 1.78 \times 10^{-4}, which closely matches the measured gap of 1.786×10−41.786 \times 10^{-4}. Let us verify both the eigenvalues of H\mathbf{H} and the predicted gaps in code.

p = grad_lse(xy0)                # the softmax at (0, log 2)
H = np.diag(p) - np.outer(p, p)  # Hessian of log-sum-exp
print('9 H =', (9 * H).round(6).tolist())
print('eigenvalues:', np.linalg.eigvalsh(H).round(6) + 0.0)  # no '-0.'
for scale in [1, 0.1]:
    eps = scale * np.array([0.01, -0.03])
    print(f'|eps| {np.linalg.norm(eps):.1e}: '
          f'predicted gap {0.5 * eps @ H @ eps:.4e}')
9 H = [[2.0, -2.0], [-2.0, 2.0]]
eigenvalues: [0.       0.444444]
|eps| 3.2e-02: predicted gap 1.7778e-04
|eps| 3.2e-03: predicted gap 1.7778e-06

Both the matrix and its eigenvalues, 00 and 49\tfrac49, match (22.2.7). The predicted gaps of 1.7778×10−41.7778 \times 10^{-4} and 1.7778×10−61.7778 \times 10^{-6} agree with the measured 1.786×10−41.786 \times 10^{-4} and 1.779×10−61.779 \times 10^{-6} to two or three significant digits. The tiny leftover of about 10−610^{-6} in the first gap comes from the third-order term, and when the step shrinks by a factor of ten, that leftover drops by roughly a thousandfold, disappearing below the printed digits.

In the log-sum-exp example, one direction was completely flat. Let us look at a function that bends in both directions: ψ(x,y)=xe−x2−y2\psi(x, y) = xe^{-x^2-y^2} at the base point x0=(−1,0)\mathbf{x}_0 = (-1, 0). From the partial derivatives we computed earlier, ψ(−1,0)=−e−1\psi(-1, 0) = -e^{-1} and ∇ψ(−1,0)=(−e−1,0)\nabla \psi(-1, 0) = (-e^{-1}, 0), and differentiating once more gives Hψ(−1,0)=2e−1I\mathbf{H}_\psi(-1, 0) = 2e^{-1}\mathbf{I}. Substituting these into (22.2.9) yields the quadratic model q(x,y)=e−1(−1−(x+1)+(x+1)2+y2)q(x, y) = e^{-1}\bigl(-1 - (x+1) + (x+1)^2 + y^2\bigr). As Figure 22.2.3 shows, the surface and its quadratic approximation are nearly indistinguishable near (−1,0)(-1, 0) before pulling apart farther away.

Figure 22.2.3:

The surface z=xe−x2−y2z = xe^{-x^2-y^2} (blue) and its second-order Taylor quadratic at the base point (−1,0)(-1, 0) (orange). The two agree in value, slope, and curvature there, so they are nearly indistinguishable near the base point and separate farther out.

If the error of this quadratic model is indeed third order, doubling the step size should multiply the gap by about eight. The next cell evaluates ψ\psi and qq at steps of dd in each coordinate from (−1,0)(-1, 0) to check.

def psi(x, y):
    return x * np.exp(-x**2 - y**2)

def quad(x, y):  # second-order Taylor model of psi at (-1, 0)
    return np.exp(-1) * (-1 - (x + 1) + (x + 1)**2 + y**2)

for d in [0.0, 0.05, 0.1, 0.3]:  # step d in each coordinate from (-1, 0)
    x, y = -1 + d, d
    print(f'step {d:.2f}: psi = {psi(x, y):.6f}, quadratic = {quad(x, y):.6f}, '
          f'gap = {abs(psi(x, y) - quad(x, y)):.6f}')
step 0.00: psi = -0.367879, quadratic = -0.367879, gap = 0.000000
step 0.05: psi = -0.384315, quadratic = -0.384434, gap = 0.000119
step 0.10: psi = -0.396388, quadratic = -0.397310, gap = 0.000921
step 0.30: psi = -0.391929, quadratic = -0.412025, gap = 0.020096

As expected, the gap vanishes at the base point, and doubling the step from 0.050.05 to 0.10.1 multiplies it by just under eight (from 0.0001190.000119 to 0.0009210.000921), matching a third-order remainder. Fitting this local quadratic and jumping directly to its minimum at each step is Newton's method, which Section 22.1.5.5 introduced in one variable and Section 9.1.5.1 develops as a multivariable optimizer.

22.2.3.3 The Second-Derivative Test#

At a critical point x0\mathbf{x}_0, the linear term in (22.2.9) disappears. Near x0\mathbf{x}_0, the function therefore behaves like its quadratic term up to an error of o(∥x−x0∥2)o(\|\mathbf{x} - \mathbf{x}_0\|^2), so whether ff rises or falls as we move away in a direction v\mathbf{v} is governed by the sign of v⊤Hv\mathbf{v}^\top\mathbf{H}\mathbf{v}, provided that curvature is nonzero.

The eigenvalues of H\mathbf{H} organize these signs cleanly. Because H\mathbf{H} is symmetric, the spectral theorem (Section 21.3) guarantees an orthonormal basis of eigenvectors qi\mathbf{q}_i with real eigenvalues λi\lambda_i. Expanded in this basis, the quadratic form becomes a simple weighted sum of squares:

v⊤Hv=∑i=1nλi (qi⊤v)2.(22.2.10)\mathbf{v}^\top \mathbf{H}\mathbf{v} = \sum_{i=1}^n \lambda_i \,(\mathbf{q}_i^\top \mathbf{v})^2. \tag{22.2.10}

From this formula we can read the local geometry at a glance. If every λi>0\lambda_i > 0, the curvature is strictly positive in every direction and is at least λmin⁡∥v∥2\lambda_{\min}\|\mathbf{v}\|^2. If the eigenvalues have mixed signs, the surface bends upward along some eigenvectors and downward along others.

Proposition (second-order conditions). Let ff be twice continuously differentiable near a critical point x0\mathbf{x}_0, and write H=Hf(x0)\mathbf{H} = \mathbf{H}_f(\mathbf{x}_0).

  1. If x0\mathbf{x}_0 is a local minimum, then H⪰0\mathbf{H} \succeq 0 (all eigenvalues are ≥0\ge 0).
  2. If H≻0\mathbf{H} \succ 0 (all eigenvalues are >0> 0), then x0\mathbf{x}_0 is a strict local minimum.
  3. If H\mathbf{H} has eigenvalues of both signs, then x0\mathbf{x}_0 is neither a local minimum nor a local maximum, regardless of any zero eigenvalues: it is a saddle point.

The corresponding statements for maxima follow by applying the proposition to −f-f. When H\mathbf{H} is singular and semidefinite, neither case 2 nor case 3 applies, and the second-derivative test is inconclusive.

Proof. (1) Suppose instead that v⊤Hv<0\mathbf{v}^\top\mathbf{H}\mathbf{v} \lt 0 for some direction v\mathbf{v}. The one-variable slice φ(t)=f(x0+tv)\varphi(t) = f(\mathbf{x}_0 + t\mathbf{v}) has φ′(0)=∇f(x0)⋅v=0\varphi'(0) = \nabla f(\mathbf{x}_0)\cdot\mathbf{v} = 0 and φ′′(0)=v⊤Hv<0\varphi''(0) = \mathbf{v}^\top\mathbf{H}\mathbf{v} \lt 0. By the single-variable second-derivative test, φ\varphi has a strict local maximum at t=0t = 0, so ff takes values strictly below f(x0)f(\mathbf{x}_0) arbitrarily close to x0\mathbf{x}_0, contradicting the assumption that x0\mathbf{x}_0 is a local minimum.

(2) This is the step that requires care, because we must control the remainder uniformly in all directions at once. Using the exact Taylor identity with ∇f(x0)=0\nabla f(\mathbf{x}_0) = \mathbf{0}, we have f(x0+δ)−f(x0)=12δ⊤Hf(ξ)δf(\mathbf{x}_0 + \boldsymbol{\delta}) - f(\mathbf{x}_0) = \tfrac12 \boldsymbol{\delta}^\top\mathbf{H}_f(\boldsymbol{\xi})\boldsymbol{\delta} for some ξ\boldsymbol{\xi} on the segment from x0\mathbf{x}_0 to x0+δ\mathbf{x}_0 + \boldsymbol{\delta}. Split the Hessian as Hf(ξ)=H+(Hf(ξ)−H)\mathbf{H}_f(\boldsymbol{\xi}) = \mathbf{H} + \bigl(\mathbf{H}_f(\boldsymbol{\xi}) - \mathbf{H}\bigr). By (22.2.10), the leading term satisfies δ⊤Hδ≥λmin⁡∥δ∥2\boldsymbol{\delta}^\top\mathbf{H}\boldsymbol{\delta} \ge \lambda_{\min}\|\boldsymbol{\delta}\|^2. By continuity of the second partials, ∥Hf(ξ)−H∥≤12λmin⁡\|\mathbf{H}_f(\boldsymbol{\xi}) - \mathbf{H}\| \le \tfrac12\lambda_{\min} for all sufficiently small δ\boldsymbol{\delta}. Combining the two bounds gives f(x0+δ)−f(x0)≥12(λmin⁡−12λmin⁡)∥δ∥2=14λmin⁡∥δ∥2>0f(\mathbf{x}_0 + \boldsymbol{\delta}) - f(\mathbf{x}_0) \ge \tfrac12\bigl(\lambda_{\min} - \tfrac12\lambda_{\min}\bigr)\|\boldsymbol{\delta}\|^2 = \tfrac14\lambda_{\min}\|\boldsymbol{\delta}\|^2 > 0 for every sufficiently small δ≠0\boldsymbol{\delta} \neq \mathbf{0}.

(3) Along an eigenvector with λ>0\lambda > 0, the slice φ\varphi satisfies φ′(0)=0\varphi'(0) = 0 and φ′′(0)=λ>0\varphi''(0) = \lambda > 0, so ff takes strictly larger values than f(x0)f(\mathbf{x}_0) arbitrarily close to x0\mathbf{x}_0. Along an eigenvector with λ<0\lambda \lt 0, it takes strictly smaller values. ■\blacksquare

Of the three statements, the second is the one to remember, and the only one whose proof takes real work. Notice also that the inconclusive case is not just a theoretical footnote: along a zero eigenvector the quadratic model is completely flat, leaving higher-order terms in charge. For example, x2+y4x^2 + y^4 and x2−y4x^2 - y^4 share the same Hessian diag⁡(2,0)\operatorname{diag}(2, 0) at the origin, yet the first has a strict minimum there while the second has a saddle (Exercise 3 pushes this phenomenon even further). Figure 22.2.4 illustrates all four cases on the quadratic models from our running examples.

Figure 22.2.4:

Contours of the quadratic model 12v⊤Hv\tfrac12\mathbf{v}^\top\mathbf{H}\mathbf{v} (gray), its eigenvector directions with their eigenvalues (dashed), and descent arrows −Hv-\mathbf{H}\mathbf{v} (red). (a) H≻0\mathbf{H}\succ 0: a minimum, every descent arrow points in. (b) H≺0\mathbf{H}\prec 0: a maximum. (c) Indefinite: a saddle; descent flows in along one eigenvector and out along the other. (d) Singular and semidefinite: the quadratic model is flat along the zero eigenvector, and second order is inconclusive.

In Figure 22.2.4, panel (a) shows the Hessian of ψ\psi at (−1/2,0)(-1/\sqrt{2}, 0), which equals e−1/2diag⁡(22,2)e^{-1/2}\operatorname{diag}(2\sqrt{2}, \sqrt{2}), while panel (b) shows its negative at (+1/2,0)(+1/\sqrt{2}, 0). Panel (c) shows the origin of x4+y4−4xyx^4 + y^4 - 4xy, whose Hessian is (0−4−40)\left(\begin{smallmatrix} 0 & -4 \\ -4 & 0 \end{smallmatrix}\right). Panel (d) reuses the log-sum-exp Hessian (22.2.7) purely as an example matrix: log-sum-exp itself has no critical point, because its gradient, the softmax, never vanishes.

What happens when we implement the second-derivative test numerically and run it on a flat direction? A Hessian built from finite differences almost never produces an exact zero eigenvalue, so we must choose a tolerance below which an eigenvalue is treated as zero. In the next cell, the centered mixed difference fxy is the second difference (22.2.8) with step 2h2h anchored at (x−h,y−h)(x-h, y-h).

def hessian(f, x, y, h=1e-4):  # 2x2 Hessian from second differences
    fxx = (f(x + h, y) - 2 * f(x, y) + f(x - h, y)) / h**2
    fyy = (f(x, y + h) - 2 * f(x, y) + f(x, y - h)) / h**2
    fxy = (f(x + h, y + h) - f(x + h, y - h)
           - f(x - h, y + h) + f(x - h, y - h)) / (4 * h**2)
    return np.array([[fxx, fxy], [fxy, fyy]])

def classify(lo, hi, tol=1e-6):  # from the smallest, largest eigenvalue
    if lo > tol:
        return 'minimum'
    if hi < -tol:
        return 'maximum'
    if lo < -tol < tol < hi:
        return 'saddle'
    return 'inconclusive'

quartic = lambda x, y: x**4 + y**4 - 4 * x * y
trough = lambda x, y: x**2 + y**4
for fn, x0 in [(psi, -1 / np.sqrt(2)), (psi, 1 / np.sqrt(2)),
               (quartic, 0.0), (trough, 0.0)]:
    lo, hi = np.linalg.eigvalsh(hessian(fn, x0, 0.0))
    print(f'({x0:+.4f}, 0): eigenvalues {lo:+.3f}, {hi:+.3f} '
          f'-> {classify(lo, hi)}')
(-0.7071, 0): eigenvalues +0.858, +1.716 -> minimum
(+0.7071, 0): eigenvalues -1.716, -0.858 -> maximum
(+0.0000, 0): eigenvalues -4.000, +4.000 -> saddle
(+0.0000, 0): eigenvalues +0.000, +2.000 -> inconclusive

At (−1/2,0)(-1/\sqrt{2}, 0), the eigenvalues come out to 0.8580.858 and 1.7161.716 (matching 2e−1/2\sqrt{2}e^{-1/2} and 22e−1/22\sqrt{2}e^{-1/2}), confirming the global minimum we found earlier. At (+1/2,0)(+1/\sqrt{2}, 0), both flip sign, confirming a maximum. At the origin of x4+y4−4xyx^4 + y^4 - 4xy, the eigenvalues are ±4\pm 4, giving a saddle whose directions of rise and fall, (1,−1)(1, -1) and (1,1)(1, 1), are rotated away from the coordinate axes. The fourth point is the instructive one. At the origin of x2+y4x^2 + y^4, finite differences return 2h2=2×10−82h^2 = 2 \times 10^{-8} along the flat direction; because this sits below our tolerance, the program rightly reports "inconclusive" even though the origin is a strict minimum. Second-order information simply cannot see the quartic rise, and only the tolerance prevents the numerical test from claiming otherwise.

22.2.3.4 Saddles in High Dimension#

In nn dimensions, a local minimum requires all nn eigenvalues of the Hessian to be nonnegative, and a nondegenerate minimum requires all nn to be strictly positive. If the eigenvalue signs at a random critical point behaved like independent coin flips, all nn would land positive with probability 2−n2^{-n}, already vanishingly small when nn is large.

Surprisingly, this coin-flip heuristic actually overestimates the chance of finding a minimum. Consider random symmetric matrices from the Gaussian orthogonal ensemble, whose diagonal entries have twice the variance of the off-diagonal entries. Even at n=2n = 2, the exact probability that both eigenvalues are positive is (1−1/2)/2≈0.146(1 - 1/\sqrt{2})/2 \approx 0.146 rather than 0.250.25 (Exercise 4). For large nn, the probability decays far faster than exponentially, like exp⁡(−ln⁡34n2)\exp\bigl(-\tfrac{\ln 3}{4}n^2\bigr) (Dean and Majumdar, 2006), because the eigenvalues of a random symmetric matrix repel one another and almost never crowd onto one side of zero.

In random high-dimensional landscapes, then, critical points at typical (high) function values are overwhelmingly saddles. Only at low function values does the Hessian shift toward positive eigenvalues so that minima begin to dominate (Bray and Dean, 2007). Neural networks exhibit the same behavior: when Newton's method locates critical points on the loss surfaces of small networks, the high-loss critical points are saddles (Dauphin et al., 2014). Practically, when an optimizer stalls at high loss, a poor local minimum is the least likely explanation. The optimizer may be lingering near a saddle or, more often still, crossing a poorly conditioned region in which the gradient is not small at all.

22.2.4 Constrained Optimization and Lagrange Multipliers#

Until now, our variables were free to move in any direction. Many machine learning problems instead restrict the parameters to a surface: weights normalized to unit length, probabilities constrained to sum to one, or the closest point on a curve to the origin. In all of these, we want to minimize f(x)f(\mathbf{x}) subject to a constraint g(x)=cg(\mathbf{x}) = c. The unconstrained condition ∇f=0\nabla f = \mathbf{0} no longer holds, because at the best feasible point ∇f\nabla f need not vanish; it only has to produce no first-order decrease along moves that stay on the constraint surface. Remarkably, what replaces ∇f=0\nabla f = \mathbf{0} follows directly from the geometry of level sets, without any second derivatives at all.

Suppose ff and gg are differentiable. At a feasible point, the admissible infinitesimal moves are the directions v\mathbf{v} tangent to the constraint surface {g=c}\{g = c\}. At a constrained local minimizer x⋆\mathbf{x}^\star, no admissible move can decrease ff to first order, so v⋅∇f(x⋆)≥0\mathbf{v}\cdot\nabla f(\mathbf{x}^\star) \ge 0 for every tangent direction v\mathbf{v}. Because −v-\mathbf{v} is tangent as well, we must have equality: ∇f(x⋆)\nabla f(\mathbf{x}^\star) is orthogonal to every tangent direction. By our level-set proposition, ∇g(x⋆)\nabla g(\mathbf{x}^\star) is also orthogonal to every tangent direction, which forces the two gradients to align.

Proposition (Lagrange condition). Let x⋆\mathbf{x}^\star be a local minimizer of ff on {x:g(x)=c}\{\mathbf{x} : g(\mathbf{x}) = c\}. Assume that ff is differentiable at x⋆\mathbf{x}^\star, that gg is continuously differentiable near x⋆\mathbf{x}^\star, and that ∇g(x⋆)≠0\nabla g(\mathbf{x}^\star) \neq \mathbf{0}. Then there exists a scalar μ\mu, called the Lagrange multiplier, such that

∇f(x⋆)=μ ∇g(x⋆).(22.2.11)\nabla f(\mathbf{x}^\star) = \mu\,\nabla g(\mathbf{x}^\star). \tag{22.2.11}

Proof. The proof relies on one geometric fact about the constraint set. Under the last two hypotheses, {g=c}\{g = c\} is a smooth surface near x⋆\mathbf{x}^\star, and every vector v\mathbf{v} satisfying ∇g(x⋆)⋅v=0\nabla g(\mathbf{x}^\star)\cdot\mathbf{v} = 0 is the velocity γ′(0)\boldsymbol{\gamma}'(0) of a differentiable curve γ\boldsymbol{\gamma} lying in {g=c}\{g = c\} with γ(0)=x⋆\boldsymbol{\gamma}(0) = \mathbf{x}^\star (Rudin, 1976). Along such a curve, the one-variable function t↦f(γ(t))t \mapsto f(\boldsymbol{\gamma}(t)) has a local minimum at t=0t = 0, so its derivative there must vanish. Just as in the level-set proof, that derivative equals v⋅∇f(x⋆)\mathbf{v}\cdot\nabla f(\mathbf{x}^\star). Consequently, ∇f(x⋆)\nabla f(\mathbf{x}^\star) is orthogonal to the entire hyperplane of vectors v\mathbf{v} orthogonal to ∇g(x⋆)\nabla g(\mathbf{x}^\star). The only vectors orthogonal to that hyperplane are scalar multiples of ∇g(x⋆)\nabla g(\mathbf{x}^\star), so ∇f(x⋆)=μ∇g(x⋆)\nabla f(\mathbf{x}^\star) = \mu\nabla g(\mathbf{x}^\star). ■\blacksquare

Geometrically, at a constrained optimum the gradients of ff and gg are parallel, meaning the level set of ff through x⋆\mathbf{x}^\star is tangent to the constraint surface. Algebraically, pairing the nn equations of (22.2.11) with the constraint g(x)=cg(\mathbf{x}) = c gives n+1n + 1 equations in the n+1n + 1 unknowns x\mathbf{x} and μ\mu.

As a concrete example, let us find the points on the hyperbola xy=1xy = 1 closest to the origin: we want to minimize f(x,y)=x2+y2f(x, y) = x^2 + y^2 subject to g(x,y)=xy=1g(x, y) = xy = 1. The gradients are ∇f=(2x,2y)\nabla f = (2x, 2y) and ∇g=(y,x)\nabla g = (y, x), and ∇g≠0\nabla g \neq \mathbf{0} everywhere on the hyperbola. The Lagrange condition gives 2x=μy2x = \mu y and 2y=μx2y = \mu x. Substituting the second equation into the first yields 4x=μ2x4x = \mu^2 x, or x(4−μ2)=0x(4 - \mu^2) = 0. Since x=0x = 0 is impossible on xy=1xy = 1, we must have μ=±2\mu = \pm 2. Choosing μ=−2\mu = -2 forces y=−xy = -x and hence xy=−x2=1xy = -x^2 = 1, which has no real solution. That leaves μ=2\mu = 2 and x=yx = y, giving the two candidates (1,1)(1, 1) and (−1,−1)(-1, -1), both with f=2f = 2. Because f=x2+1/x2f = x^2 + 1/x^2 grows without bound as x→0x \to 0 or ∣x∣→∞|x| \to \infty on each branch, a global minimum must exist, so these two points are indeed the closest ones. At (1,1)(1, 1), the circle x2+y2=2x^2 + y^2 = 2 kisses the hyperbola tangently, and ∇f=(2,2)=2 ∇g\nabla f = (2, 2) = 2\,\nabla g (Figure 22.2.5).

Figure 22.2.5:

The closest point of xy=1xy = 1 to the origin. At (1,1)(1, 1) the circle x2+y2=2x^2+y^2=2 is tangent to the hyperbola and ∇f=(2,2)=2∇g\nabla f = (2,2) = 2\nabla g, so μ=2\mu = 2; the mirror solution (−1,−1)(-1,-1) is off the frame. At a feasible point that is not optimal the two gradients point in different directions, and ∇f\nabla f keeps a component along the constraint.

The hyperbola makes the geometry easy to draw, but the same tool brings us straight back to our running example. Consider maximizing z⋅p−∑ipilog⁡pi\mathbf{z}\cdot\mathbf{p} - \sum_i p_i\log p_i over probability vectors p\mathbf{p} subject to ∑ipi=1\sum_i p_i = 1. Writing out the Lagrange condition gives zi−log⁡pi−1=μz_i - \log p_i - 1 = \mu for each coordinate ii, which implies pi∝ezip_i \propto e^{z_i}. The optimal distribution is therefore the softmax, and the maximum value attained is the log-sum-exp (Section 23.7).

The regularity hypothesis ∇g(x⋆)≠0\nabla g(\mathbf{x}^\star) \neq \mathbf{0} cannot be dropped: without it, a Lagrange multiplier need not exist at all (Exercise 6 gives a clean counterexample). Later, Section 23.6 extends this condition to inequality constraints through the KKT conditions, and Section 23.7 develops the dual problem.

Every result in this section took the gradient as already known. For a two-variable formula on a blackboard, computing it by hand is effortless. For a neural network with a million weights, obtaining the gradient efficiently is the hard part.

22.2.5 Summary#

A differentiable function changes, to first order, by the dot product of the step with its gradient; merely having partial derivatives does not guarantee this. Geometrically, the negative gradient points in the direction of steepest descent, and the gradient stands normal to every level set. One order higher, the symmetric Hessian defines the local quadratic approximation: at a critical point, the signs of its eigenvalues distinguish minima, maxima, and saddles, while a singular semidefinite Hessian leaves the test inconclusive. When the variables are restricted to a constraint surface g(x)=cg(\mathbf{x}) = c, the geometry of level sets replaces ∇f=0\nabla f = \mathbf{0} with the Lagrange condition ∇f=μ∇g\nabla f = \mu\nabla g.

22.2.6 Exercises#

  1. Directional derivatives without a gradient. Let f(x,y)=x2y/(x2+y2)f(x, y) = x^2 y / (x^2 + y^2) for (x,y)≠(0,0)(x, y) \neq (0, 0) and f(0,0)=0f(0, 0) = 0.

    1. Show that ff is continuous at the origin.
    2. Compute the two partial derivatives of ff at the origin and the directional derivative there along every unit vector u=[cos⁡θ,sin⁡θ]⊤\mathbf{u} = [\cos\theta, \sin\theta]^\top.
    3. Show that no vector g\mathbf{g} gives these directional derivatives as u⋅g\mathbf{u}\cdot\mathbf{g}, so that ff is not differentiable at the origin. Which hypothesis of the sufficient condition for differentiability in Section 22.2.1.2 fails? What does this function show that the counterexample 2xy/(x2+y2)2xy/(x^2+y^2) there does not?
  2. Gradients of an elongated bowl. Let f(x,y)=x2+κy2f(x, y) = x^2 + \kappa y^2 with κ≥1\kappa \ge 1. Its minimizer is the origin, and κ\kappa measures how much more strongly ff curves along yy than along xx.

    1. Find a direction tangent to the level curve of ff through (1,1)(1, 1), check that it is orthogonal to ∇f(1,1)\nabla f(1, 1), and compute the angle between −∇f(1,1)-\nabla f(1, 1) and the direction −[1,1]⊤-[1, 1]^\top from (1,1)(1, 1) to the minimizer. At which points (x,y)≠(0,0)(x, y) \neq (0, 0) does the negative gradient point at the minimizer?
    2. Find the smallest value of the cosine of this angle over all points (x,y)≠(0,0)(x, y) \neq (0, 0), and the points where it is attained. (Hint: set ρ=y/x\rho = y/x and minimize over ρ\rho.) Evaluate it for κ=10\kappa = 10. What does the result imply for a gradient-descent step on such a loss as κ\kappa grows?
  3. Flat directions.

    1. Give three functions of (x,y)(x, y) that have a critical point at the origin with Hessian diag⁡(2,0)\operatorname{diag}(2, 0) there: one with a strict local minimum, one with a local minimum that is not strict, and one without a local minimum.
    2. The function f(x,y)=(x−y2)(x−2y2)f(x, y) = (x - y^2)(x - 2y^2) also has Hessian diag⁡(2,0)\operatorname{diag}(2, 0) at the origin. Show that its restriction to every line through the origin has a strict local minimum there. Sketch the region of the plane where f<0f \lt 0, and show that the origin is nevertheless not a local minimum of ff. What does this imply for testing a critical point by probing the loss along a few directions?
    3. The monkey saddle f(x,y)=x3−3xy2f(x, y) = x^3 - 3xy^2 has a critical point at the origin. Compute its Hessian there, write ff in polar coordinates, and find the directions along which ff decreases. How does ∥∇f∥\|\nabla f\| scale with the distance to the origin, compared with the saddle x2−y2x^2 - y^2? What does this imply for gradient descent started near each of the two saddles?
  4. [code] Random Hessians. ● A local minimum requires all nn eigenvalues of the Hessian to be nonnegative, and a nondegenerate one requires them all positive; the section's coin-flip heuristic puts the latter at 2−n2^{-n}. Test this heuristic on random symmetric matrices A=(G+G⊤)/2\mathbf{A} = (\mathbf{G} + \mathbf{G}^\top)/\sqrt{2}, where the n×nn \times n matrix G\mathbf{G} has independent standard normal entries.

    1. For n=2n = 2, show that s=(a11+a22)/2s = (a_{11} + a_{22})/2, d=(a11−a22)/2d = (a_{11} - a_{22})/2, and a12a_{12} are independent standard normal variables, and that A≻0\mathbf{A} \succ 0 exactly when s>d2+a122s > \sqrt{d^2 + a_{12}^2}. Use the rotational symmetry of the standard normal distribution in three dimensions to compute P(A≻0)P(\mathbf{A} \succ 0) exactly, and compare it with 2−22^{-2}.
    2. Estimate P(A≻0)P(\mathbf{A} \succ 0) by Monte Carlo for n=1,…,6n = 1, \ldots, 6, with 10610^6 draws for n≤5n \le 5 and 10710^7 draws, generated in batches, for n=6n = 6. Plot log⁡P\log P against nn together with log⁡2−n\log 2^{-n}, and fit a quadratic in nn to your estimates. Dean and Majumdar (2006) prove that log⁡P≈−ln⁡34n2\log P \approx -\tfrac{\ln 3}{4} n^2 for large nn. Compare this coefficient with the quadratic coefficient of your fit. Does the heuristic over- or underestimate the probability of a minimum, and which property of the eigenvalues does it ignore?
    3. For large nn the smallest eigenvalue of A\mathbf{A} lies close to −2n-2\sqrt{n}. For n=5,10,20n = 5, 10, 20, find the shift β\beta at which half of the matrices A+βI\mathbf{A} + \beta\mathbf{I} are positive definite, and compare it with 2n2\sqrt{n}. In the random landscapes of Bray and Dean (2007), the Hessian at a critical point behaves like such a shifted matrix, with a shift that grows as the value of the random function at the critical point decreases. What does your result suggest about critical points of low loss?
  5. [extended] Saddles of a linear network. ●● Let A\mathbf{A} be a symmetric n×nn \times n matrix with eigenvalues λ1>λ2>⋯>λn>0\lambda_1 > \lambda_2 > \cdots > \lambda_n > 0 and orthonormal eigenvectors q1,…,qn\mathbf{q}_1, \ldots, \mathbf{q}_n. A linear network with one hidden unit, input weights v\mathbf{v}, and output weights u\mathbf{u} maps x\mathbf{x} to uv⊤x\mathbf{u}\mathbf{v}^\top\mathbf{x}. Trained on whitened inputs (E[xx⊤]=I\mathbb{E}[\mathbf{x}\mathbf{x}^\top] = \mathbf{I}) with targets Ax\mathbf{A}\mathbf{x}, half its expected squared error is

ℓ(u,v)=12∥A−uv⊤∥F2.\ell(\mathbf{u}, \mathbf{v}) = \tfrac12 \|\mathbf{A} - \mathbf{u}\mathbf{v}^\top\|_F^2.

Baldi and Hornik (1989) showed that the local minima of such linear networks are global. This problem derives the complete set of critical points and compares it with the relation between loss and index that Dauphin et al. (2014) measured for nonlinear networks; the index of a critical point is the fraction of negative eigenvalues of its Hessian.

  1. Compute ∇uℓ\nabla_{\mathbf{u}} \ell and ∇vℓ\nabla_{\mathbf{v}} \ell. Show that the critical points are the origin and the points u=αqi\mathbf{u} = \alpha\mathbf{q}_i, v=(λi/α)qi\mathbf{v} = (\lambda_i / \alpha)\mathbf{q}_i with α≠0\alpha \neq 0, and compute ℓ\ell at each of them.

  2. Compute the eigenvalues of the 2n×2n2n \times 2n Hessian at the balanced point u=v=λi qi\mathbf{u} = \mathbf{v} = \sqrt{\lambda_i}\,\mathbf{q}_i and at the origin. (In the eigenvector basis, the Hessian splits into 2×22 \times 2 blocks, one for each pair of coordinates along qj\mathbf{q}_j in u\mathbf{u} and in v\mathbf{v}.) How many eigenvalues are negative at each critical point? Explain the zero eigenvalue by a symmetry of ℓ\ell, and conclude that every local minimum is global.

  3. Take n=4n = 4, (λ1,…,λ4)=(4,3,2,1)(\lambda_1, \ldots, \lambda_4) = (4, 3, 2, 1), and a random orthonormal basis of eigenvectors. Run Newton's method from many random starting points of different scales, and record the loss and the index of every critical point it reaches. The Hessian is singular at every critical point other than the origin, so compute each Newton step by least squares. Plot the loss against the index, as in Figure 1 of Dauphin et al. (2014). How often does Newton's method end at each kind of critical point, and where does gradient descent from small random initializations end?

  4. Replace uv⊤\mathbf{u}\mathbf{v}^\top by UV⊤\mathbf{U}\mathbf{V}^\top with two hidden units, so that U\mathbf{U} and V\mathbf{V} are 4×24 \times 2 matrices. Predict the loss values of the critical points from the rank-one analysis, and confirm them with Newton's method. How many zero eigenvalues does the Hessian have at the critical points, and which symmetry explains them? Is the index a monotone function of the loss?

  5. Lagrange multipliers and the Rayleigh quotient. Let A\mathbf{A} be a symmetric n×nn \times n matrix. Maximize f(x)=x⊤Axf(\mathbf{x}) = \mathbf{x}^\top\mathbf{A}\mathbf{x} subject to g(x)=∥x∥2=1g(\mathbf{x}) = \|\mathbf{x}\|^2 = 1.

    1. Write the Lagrange condition and show that it reads Ax=μx\mathbf{A}\mathbf{x} = \mu\mathbf{x}: every constrained critical point is a unit eigenvector, and its multiplier is the eigenvalue.
    2. Show that f(x)=μf(\mathbf{x}) = \mu at every constrained critical point. Why does a constrained maximum exist? Conclude that the maximum is λmax⁡(A)\lambda_{\max}(\mathbf{A}) and the minimum λmin⁡(A)\lambda_{\min}(\mathbf{A}).
    3. For A=(2112)\mathbf{A} = \left(\begin{smallmatrix} 2 & 1 \\ 1 & 2 \end{smallmatrix}\right) find the maximizers and minimizers and their values, and check at a maximizer that the level set of ff through it is tangent to the unit circle.
    4. Which hypothesis of the Lagrange proposition does g(x)=∥x∥2g(\mathbf{x}) = \|\mathbf{x}\|^2 satisfy at every point of the unit sphere? Now minimize the linear function c⊤x\mathbf{c}^\top\mathbf{x}, c≠0\mathbf{c} \neq \mathbf{0}, subject to ∥x∥2=0\|\mathbf{x}\|^2 = 0. What is the minimizer, and why does no multiplier μ\mu satisfy ∇f=μ∇g\nabla f = \mu\nabla g there?

Discussions