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 evaluated at . 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 , the loss becomes a function of a single variable. Its ordinary derivative is the partial derivative from Section 1.4: geometrically, it is the slope of the one-dimensional slice of the graph of obtained by varying only . Just as in single-variable calculus, this slope predicts the effect of a small change in alone,
Let us compute the partial derivatives of our running example . Holding fixed and differentiating with respect to gives , and by symmetry . At the point , we have and , so , , and . In other words, nudging alone raises twice as fast as nudging 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 by . It is tempting to guess that the two coordinate-wise changes simply add, giving . That guess is actually a strong claim about how behaves near the point, and it requires a hypothesis.
The hypothesis is that near , the function looks linear up to an error that vanishes faster than the step size. Formally, we say that is differentiable at if there exists a linear map such that
where denotes any remainder that, when divided by , tends to zero as .
Whenever such a linear map exists, the partial derivatives determine it completely. Setting in (22.2.2), dividing both sides by , and letting forces . Because is linear, its action on any joint step is then fixed:
We call this column vector of partial derivatives the gradient of . Substituting it back into (22.2.2) gives the multivariable linear approximation
Compare this with the one-variable approximation : 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 . 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 , we have . Plugging into (22.2.3) predicts . Notice that at every point , the two entries of are positive and sum to one: the gradient of log-sum-exp is the softmax , with entries and .
It is worth pausing to see why differentiability asks for more than the mere existence of partial derivatives. Consider with . Along both coordinate axes is identically zero, so both partial derivatives at the origin are , leaving the constant function as the only possible linear model. Yet along the diagonal , we have no matter how close we get to the origin, so no linear approximation can hold there. Here 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 and are continuous at (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 , meaning it shrinks faster than . 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 by a factor of ten. The experiment below uses plain NumPy to check.
import numpy as np
import torchdef 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 , the linear model misses the true value by (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 , substitute into (22.2.3), divide by , and let . The remainder vanishes, leaving
The limit on the left is the directional derivative of along ; the right side says it is simply the projection of the gradient onto . A single vector therefore encodes the slope in every possible direction at once.
Three directions for our running example at illustrate the full range of behavior. Along the diagonal , the slope is . In fact, this slope is the same at every point, because : moving a distance along the diagonal always raises by . Pointing directly against the gradient, along , gives the slope . Finally, along , the slope is , so to first order 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 whose projection is as negative as possible. Section 1.4 identified this direction from the cosine of the angle between 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 , among all unit vectors , the directional derivative is maximized by and minimized by . Thus is the direction of steepest ascent and is the direction of steepest descent.
Proof. The Cauchy–Schwarz inequality (Section 21.1) states that , with equality if and only if and are collinear. For a unit vector and , this reads
Each bound is attained uniquely by a unit vector collinear with : the upper bound by and the lower bound by .
In our running example at , the steepest descent direction is , with slope , the most negative of the three slopes we computed a moment ago. Taking a step along gives the familiar gradient-descent update
Notice that the update does not normalize the gradient. Its step length is , 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 applied coordinate by coordinate. At , that step is , with slope . 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 is the collection of all points where takes a fixed value . Because moving along a level set keeps constant, the directional derivative along any tangent direction should vanish.
Proposition (gradients are normal to level sets). Let be differentiable at . Then is orthogonal to every direction tangent at to the level set passing through .
Proof. A vector is tangent to the level set at if for some differentiable curve lying inside the level set with . Along such a curve, for all , so the derivative of at must be zero. To first order, , so (22.2.3) tells us that this derivative equals . Hence .
Let us check this on our running example. The level set of passing through is the curve . Differentiating along it gives , so the tangent direction at is . Taking the dot product with the gradient confirms , 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 and sit a distance apart, the slope across them is roughly , so the gradient is longest wherever the contours are packed most tightly (Figure 22.2.1).
Contours of a loss (gray) with 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 , we obtain the tangent plane to the graph of at ,
For our running example at , this plane is . Rewriting (22.2.5) as shows immediately that the vector is normal to the tangent plane in -space. Dropping its height coordinate leaves , which is the normal to the level curve in the base plane (Figure 22.2.2).
A surface (blue) with its tangent plane at a point (orange). The vector , the negative of , is normal to the plane (black arrow). Dropping the height coordinate leaves a multiple of , 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 is defined on all of and differentiable at .
If , we can step against it by setting with . By (22.2.3), the resulting change in is , which is strictly negative for every sufficiently small . Thus cannot be a local minimum; repeating the argument with shows it cannot be a local maximum either. Therefore, at any local minimum or maximum, . 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 , a surface with a positive hill for and a matching negative pit for . Its partial derivatives are
Setting the second partial to zero forces either or . Since makes the first partial equal to , we must have , and then gives . The two critical points have values .
To conclude that is the global minimum, however, we also need to know that a global minimum exists at all. Outside the disc of radius , the exponential decay forces , whereas inside the disc . Because is continuous, it attains its minimum on the closed disc; since that minimum is below , it cannot lie on the boundary and must be a global minimum of on all of , hence a critical point. Comparing our two candidates identifies as the global minimum, and the same argument identifies as the global maximum. Skip the existence check and the logic breaks down: 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 variables has second partial derivatives,
which we collect into the Hessian matrix
Entry measures how fast the -th slope changes as we move along coordinate . The Hessian is also written , and when the function and point are clear from context we simply write .
For log-sum-exp, let us write and differentiate the softmax entries once more. Applying the quotient rule gives , where is when and otherwise. In matrix form,
This matrix has eigenvalue along and eigenvalue along . The zero eigenvalue matches what we already saw: along the diagonal , is completely linear and has no curvature at all. We will meet this positive semidefinite, singular Hessian again in the second-derivative test.
The entries of a Hessian are not independent. Whenever 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 and the mixed partials and exist near , and suppose the mixed partials are continuous at . Then
When this holds for all , the Hessian is symmetric: .
Proof. The idea is to realize both mixed partials as limits of the same quantity, the symmetric second difference
which is visibly unchanged if we swap and . Our task is to express as a mixed partial evaluated at a nearby point. Define the one-variable function , so that . Applying the mean value theorem (Section 22.1.3) twice, first to and then along to the difference of first partials inside , gives numbers and between and such that
Thus at a point inside the square with corners and , at distance at most from . Swapping the roles of and leaves unchanged and yields at another point of the same square. Letting , continuity of the mixed partials at sends the two expressions to the two mixed partials at . Because they agree for every , their limits must agree as well.
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 , 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 . Evaluating its value, gradient, and Hessian (22.2.6) at the origin gives
and assembling these pieces recovers the polynomial exactly: . The factor of simply cancels the factor of produced when we differentiate a square.
For a general function , this quadratic is no longer exact, but restricting to a line segment shows how accurate it is. Suppose is twice continuously differentiable near the segment connecting to . Write the displacement as , and consider the single-variable slice . By the linear model (22.2.3), its first derivative is . Because each partial derivative in this sum is itself differentiable, applying the same step once more gives the second derivative: .
Now apply the one-variable Taylor theorem with Lagrange remainder (Section 22.1.5.2) of degree one to between and : there is some such that . Translating back to gives
This identity is exact, at the cost of evaluating the Hessian at an unknown intermediate point on the segment rather than at . Because the second partials are continuous, replacing by changes the quadratic term by at most . That yields the second-order Taylor approximation:
This quadratic model misses only by an error that vanishes faster than the squared step size, and it is the unique quadratic with that property. Whenever has three continuous derivatives, the error is of third order in the step.
Along any single direction , a step produces a quadratic term of . The number is the second directional derivative: it measures the curvature of the slice of along .
We can now explain the gap left by the linear model in our first code cell. For the step from , the Hessian (22.2.7) predicts a second-order correction of , which closely matches the measured gap of . Let us verify both the eigenvalues of 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, and , match (22.2.7). The predicted gaps of and agree with the measured and to two or three significant digits. The tiny leftover of about 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: at the base point . From the partial derivatives we computed earlier, and , and differentiating once more gives . Substituting these into (22.2.9) yields the quadratic model . As Figure 22.2.3 shows, the surface and its quadratic approximation are nearly indistinguishable near before pulling apart farther away.
The surface (blue) and its second-order Taylor quadratic at the base point (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 and at steps of in each coordinate from 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 to multiplies it by just under eight (from to ), 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 , the linear term in (22.2.9) disappears. Near , the function therefore behaves like its quadratic term up to an error of , so whether rises or falls as we move away in a direction is governed by the sign of , provided that curvature is nonzero.
The eigenvalues of organize these signs cleanly. Because is symmetric, the spectral theorem (Section 21.3) guarantees an orthonormal basis of eigenvectors with real eigenvalues . Expanded in this basis, the quadratic form becomes a simple weighted sum of squares:
From this formula we can read the local geometry at a glance. If every , the curvature is strictly positive in every direction and is at least . If the eigenvalues have mixed signs, the surface bends upward along some eigenvectors and downward along others.
Proposition (second-order conditions). Let be twice continuously differentiable near a critical point , and write .
- If is a local minimum, then (all eigenvalues are ).
- If (all eigenvalues are ), then is a strict local minimum.
- If has eigenvalues of both signs, then 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 . When is singular and semidefinite, neither case 2 nor case 3 applies, and the second-derivative test is inconclusive.
Proof. (1) Suppose instead that for some direction . The one-variable slice has and . By the single-variable second-derivative test, has a strict local maximum at , so takes values strictly below arbitrarily close to , contradicting the assumption that 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 , we have for some on the segment from to . Split the Hessian as . By (22.2.10), the leading term satisfies . By continuity of the second partials, for all sufficiently small . Combining the two bounds gives for every sufficiently small .
(3) Along an eigenvector with , the slice satisfies and , so takes strictly larger values than arbitrarily close to . Along an eigenvector with , it takes strictly smaller values.
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, and share the same Hessian 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.
Contours of the quadratic model (gray), its eigenvector directions with their eigenvalues (dashed), and descent arrows (red). (a) : a minimum, every descent arrow points in. (b) : 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 at , which equals , while panel (b) shows its negative at . Panel (c) shows the origin of , whose Hessian is . 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 anchored at .
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 , the eigenvalues come out to and (matching and ), confirming the global minimum we found earlier. At , both flip sign, confirming a maximum. At the origin of , the eigenvalues are , giving a saddle whose directions of rise and fall, and , are rotated away from the coordinate axes. The fourth point is the instructive one. At the origin of , finite differences return 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 dimensions, a local minimum requires all eigenvalues of the Hessian to be nonnegative, and a nondegenerate minimum requires all to be strictly positive. If the eigenvalue signs at a random critical point behaved like independent coin flips, all would land positive with probability , already vanishingly small when 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 , the exact probability that both eigenvalues are positive is rather than (Exercise 4). For large , the probability decays far faster than exponentially, like (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 subject to a constraint . The unconstrained condition no longer holds, because at the best feasible point need not vanish; it only has to produce no first-order decrease along moves that stay on the constraint surface. Remarkably, what replaces follows directly from the geometry of level sets, without any second derivatives at all.
Suppose and are differentiable. At a feasible point, the admissible infinitesimal moves are the directions tangent to the constraint surface . At a constrained local minimizer , no admissible move can decrease to first order, so for every tangent direction . Because is tangent as well, we must have equality: is orthogonal to every tangent direction. By our level-set proposition, is also orthogonal to every tangent direction, which forces the two gradients to align.
Proposition (Lagrange condition). Let be a local minimizer of on . Assume that is differentiable at , that is continuously differentiable near , and that . Then there exists a scalar , called the Lagrange multiplier, such that
Proof. The proof relies on one geometric fact about the constraint set. Under the last two hypotheses, is a smooth surface near , and every vector satisfying is the velocity of a differentiable curve lying in with (Rudin, 1976). Along such a curve, the one-variable function has a local minimum at , so its derivative there must vanish. Just as in the level-set proof, that derivative equals . Consequently, is orthogonal to the entire hyperplane of vectors orthogonal to . The only vectors orthogonal to that hyperplane are scalar multiples of , so .
Geometrically, at a constrained optimum the gradients of and are parallel, meaning the level set of through is tangent to the constraint surface. Algebraically, pairing the equations of (22.2.11) with the constraint gives equations in the unknowns and .
As a concrete example, let us find the points on the hyperbola closest to the origin: we want to minimize subject to . The gradients are and , and everywhere on the hyperbola. The Lagrange condition gives and . Substituting the second equation into the first yields , or . Since is impossible on , we must have . Choosing forces and hence , which has no real solution. That leaves and , giving the two candidates and , both with . Because grows without bound as or on each branch, a global minimum must exist, so these two points are indeed the closest ones. At , the circle kisses the hyperbola tangently, and (Figure 22.2.5).
The closest point of to the origin. At the circle is tangent to the hyperbola and , so ; the mirror solution is off the frame. At a feasible point that is not optimal the two gradients point in different directions, and 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 over probability vectors subject to . Writing out the Lagrange condition gives for each coordinate , which implies . The optimal distribution is therefore the softmax, and the maximum value attained is the log-sum-exp (Section 23.7).
The regularity hypothesis 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 , the geometry of level sets replaces with the Lagrange condition .
22.2.6 Exercises#
-
Directional derivatives without a gradient. Let for and .
- Show that is continuous at the origin.
- Compute the two partial derivatives of at the origin and the directional derivative there along every unit vector .
- Show that no vector gives these directional derivatives as , so that 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 there does not?
-
Gradients of an elongated bowl. Let with . Its minimizer is the origin, and measures how much more strongly curves along than along .
- Find a direction tangent to the level curve of through , check that it is orthogonal to , and compute the angle between and the direction from to the minimizer. At which points does the negative gradient point at the minimizer?
- Find the smallest value of the cosine of this angle over all points , and the points where it is attained. (Hint: set and minimize over .) Evaluate it for . What does the result imply for a gradient-descent step on such a loss as grows?
-
Flat directions.
- Give three functions of that have a critical point at the origin with Hessian there: one with a strict local minimum, one with a local minimum that is not strict, and one without a local minimum.
- The function also has Hessian 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 , and show that the origin is nevertheless not a local minimum of . What does this imply for testing a critical point by probing the loss along a few directions?
- The monkey saddle has a critical point at the origin. Compute its Hessian there, write in polar coordinates, and find the directions along which decreases. How does scale with the distance to the origin, compared with the saddle ? What does this imply for gradient descent started near each of the two saddles?
-
[code] Random Hessians. ● A local minimum requires all 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 . Test this heuristic on random symmetric matrices , where the matrix has independent standard normal entries.
- For , show that , , and are independent standard normal variables, and that exactly when . Use the rotational symmetry of the standard normal distribution in three dimensions to compute exactly, and compare it with .
- Estimate by Monte Carlo for , with draws for and draws, generated in batches, for . Plot against together with , and fit a quadratic in to your estimates. Dean and Majumdar (2006) prove that for large . 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?
- For large the smallest eigenvalue of lies close to . For , find the shift at which half of the matrices are positive definite, and compare it with . 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?
-
[extended] Saddles of a linear network. ●● Let be a symmetric matrix with eigenvalues and orthonormal eigenvectors . A linear network with one hidden unit, input weights , and output weights maps to . Trained on whitened inputs () with targets , half its expected squared error is
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.
-
Compute and . Show that the critical points are the origin and the points , with , and compute at each of them.
-
Compute the eigenvalues of the Hessian at the balanced point and at the origin. (In the eigenvector basis, the Hessian splits into blocks, one for each pair of coordinates along in and in .) How many eigenvalues are negative at each critical point? Explain the zero eigenvalue by a symmetry of , and conclude that every local minimum is global.
-
Take , , 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?
-
Replace by with two hidden units, so that and are 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?
-
Lagrange multipliers and the Rayleigh quotient. Let be a symmetric matrix. Maximize subject to .
- Write the Lagrange condition and show that it reads : every constrained critical point is a unit eigenvector, and its multiplier is the eigenvalue.
- Show that at every constrained critical point. Why does a constrained maximum exist? Conclude that the maximum is and the minimum .
- For find the maximizers and minimizers and their values, and check at a maximizer that the level set of through it is tangent to the unit circle.
- Which hypothesis of the Lagrange proposition does satisfy at every point of the unit sphere? Now minimize the linear function , , subject to . What is the minimizer, and why does no multiplier satisfy there?