08 / 16 · Calculus
Gradients, Jacobians and Hessians
Derivatives of functions of many variables: the gradient as the direction of steepest ascent across the level sets, the Jacobian and the chain rule as a product of matrices, and the Hessian that tells minima from saddles.
Derivatives and Taylor series · Inner products, norms and orthogonality · Symmetric matrices and quadratic forms
On this page 9
Stand at the point of the function
Walking along the -axis, rises at the rate ; along the -axis, at the rate . These are the partial derivatives and : the ordinary derivatives of at , where are the standard basis vectors. But a loss is minimized by stepping in some direction, and almost never along an axis. How fast does change along ? Which direction is steepest?
A loss in machine learning is a function of a whole vector of weights, and a layer of a network maps a vector to a vector. The previous note approximated a function of one variable by its tangent line; the same idea, with vectors and matrices in place of numbers, answers these questions.
The gradient: the best linear approximation#
Partial derivatives alone do not describe a function near a point. The function , extended by , vanishes on both axes, so both of its partial derivatives at the origin are 0. Yet on the diagonal it equals : is not even continuous at the origin, and no plane approximates it there.
The definition that works is the one of the previous note, with the increment now a vector. A function is differentiable at when, near , it equals a linear function of plus an error small compared with the length . A linear function of is an inner product with a fixed vector : by linearity , so . That vector is the gradient :
We write . Taking shows that the -th entry of is , so the gradient is the column of partial derivatives, . For the quadratic , .
Differentiability asks for more than the existence of the partial derivatives, as shows. A convenient sufficient condition is that all partial derivatives exist near and are continuous at . Every polynomial in this note, and every smooth loss, meets it.
Proof: continuous partial derivatives give differentiability
Change one coordinate at a time. With and , the one-variable mean value theorem gives, for some ,
Each evaluation point is within of , so by continuity at each there differs from by at most any once is small. The error against is then at most , which is .
Directional derivatives#
The directional derivative along a unit vector is the rate of change of when walking from along , . Put into the definition of differentiability and divide by :
The remainder term vanishes because for a unit . So
Example. For at and , . A central difference with , , gives to twelve digits. For a quadratic the central difference is exact up to rounding: is a quadratic in , its third derivative is 0, and so is the error term of the central difference.
The gradient points uphill, across the level sets#
Two geometric facts make the gradient the central object of optimization, and both come from the formula : an inner product with a fixed vector is largest along that vector and zero across it.
Steepest ascent. Assume . For every unit vector , by Cauchy–Schwarz,
Equality in Cauchy–Schwarz needs ; then equals only for , which for a unit vector means . So the gradient points in the direction of steepest ascent, and its length is the rate of ascent. The same argument with shows that the steepest descent is along , at rate : the step direction of gradient descent.
Perpendicular to the level sets. A level set of is , a contour line in two dimensions. Let be a differentiable curve that stays in the level set, with and velocity , a tangent vector of the level set at . Since is constant along the curve,
The second line is differentiability with . In the limit the difference quotient of tends to , and the remainder term tends to 0, because stays bounded while . So the gradient is orthogonal to every tangent direction of the level set.
Example. The level set passes through . The gradient there is , with length , the largest rate of increase in any direction; the direction of the previous example, close to the gradient’s direction , gave a little less, . The tangent direction gives : to first order does not change along the contour.
Level sets and gradients
The figure also shows why plain gradient descent can be slow. The descent direction at points across the elongated ellipse and misses the minimum at the origin: is away from . The more elongated the level sets, the larger that angle can be; the gradient descent note shows how the eigenvalues of the Hessian govern the resulting zigzag.
The Jacobian of a vector function#
A vector function , with components , is differentiable at when it is approximated by a linear map, now an matrix :
Row of the Jacobian is , the gradient of the -th output; column says how all outputs respond to the -th input. The shape is outputs × inputs, as for the matrix of any linear map in the linear maps note. For a scalar function the Jacobian is the row .
Two Jacobians make up a neural network. A linear layer has Jacobian with respect to , and an elementwise activation has the diagonal Jacobian .
Example. The map , the squaring of the complex number , has
The second matrix is times a rotation by , with determinant 5. Near , therefore turns a small square by , stretches it by and multiplies its area by 5, the factor of the determinant as volume.
For the square of side centred at the exact area of the curved image is , against for the linear map. The exact area is the integral of over the square, by the change of variables for the map , one-to-one there. For side the ratio of areas is . It is the average of the continuous over the square, so it tends to as the square shrinks. This local area factor is the of the change of variables in the multiple integrals note.
The Jacobian as the local linear map
The chain rule: a product of Jacobians#
Composing two maps composes their linear approximations, and the composition of linear maps is the product of their matrices. For differentiable at and differentiable at :
To prove it, let be the step that causes in the input of , with both Jacobians at their points. Differentiability of at , then the substitution of , give
The first term is linear in , and the other two are . The second is at most , where is the largest stretch of the matrix, its spectral norm. For the third, , so stays bounded and , while (the term is 0 when ). The linear part of the composition is therefore .
When the last function is a scalar loss , its Jacobian is the row , and transposing the chain rule gives
For a network, a chain of layers, the gradient of the loss is the gradient at the output multiplied by the transposed Jacobians of the layers, from the last to the first. Multiplying in that order keeps every intermediate result a vector and never forms a Jacobian as a matrix; this is reverse-mode differentiation. The backpropagation note writes it out for linear layers and activations, with shapes, and explains why it costs about one forward pass; autograd in PyTorch records the chain as a graph and runs it automatically.
Example. Take from the previous section and . At , and , so
The direct route agrees. The composition is , with partial derivatives and .
The Hessian and the second-order Taylor expansion#
The Hessian collects the second partial derivatives, ; it is the Jacobian of the gradient. When the second partial derivatives are continuous, the order of differentiation does not matter (Schwarz’s theorem), and the Hessian is symmetric. Continuity is needed. For , extended by 0 at the origin, and , so the two mixed partial derivatives at the origin are and (Merkulov, 2024, lecture 2).
Proof: Schwarz’s theorem
Fix all coordinates but and , write , and take the double difference
With , . The mean value theorem in , then in the second argument, gives , with within of in each coordinate. Grouping the four terms the other way, with , gives . Dividing by and letting , continuity of both mixed derivatives makes them equal at .
For with continuous second derivatives, the expansion adds a quadratic form to the linear approximation:
To see why, restrict to the segment from to , , and use the one-variable theorem. The chain rule gives , and applied once more to each ,
Taylor with gives for some , that is,
Replacing the Hessian at by the one at changes the last term by at most , and the norm of the difference tends to 0 with because is continuous. That error is .
A quadratic with symmetric has and the constant Hessian , and its expansion is exact. Multiplying out, with because a number equals its transpose and :
The Hessians of the two standard losses are of this kind or close to it: for least squares and for logistic regression; the matrix calculus note derives both.
Example. The cubic has
At , take the step :
| quantity | value |
|---|---|
| and | and |
| linear approximation | |
| quadratic term | |
| second-order approximation | |
| exact |
The linear approximation is off by , the quadratic one by , which is : expanding leaves exactly that term beyond the second order.
Classifying critical points by the Hessian’s eigenvalues#
At a critical point , where , the linear term vanishes and the quadratic form decides what does nearby. By the spectral theorem, the symmetric Hessian is with orthonormal eigenvectors and real eigenvalues , so
Along each eigenvector, curves up or down according to the sign of its eigenvalue. The signs classify the point:
| eigenvalues of | is |
|---|---|
| all positive | a strict local minimum |
| all negative | a strict local maximum |
| some positive, some negative | a saddle point |
| some zero, the others of one sign | undecided by this test |
For the minimum, let be the smallest eigenvalue. The second-order expansion at , the spectral decomposition, and for an orthogonal give
For small the remainder is below , so the difference is positive. The maximum is the same argument for . At a saddle, the step along an eigenvector with changes by , and a step along an eigenvector with a negative eigenvalue changes it by a negative amount, so is neither a minimum nor a maximum.
With a zero eigenvalue the quadratic term is flat in some direction and higher-order terms decide: and both have the Hessian at the origin, and the first has a minimum there, the second a saddle.
Example. The cubic has where and : at and . At the Hessian is , both eigenvalues positive: a strict local minimum, with . At it is : a saddle with , a maximum along and a minimum along . The minimum is only local, since as .
A bowl and a saddle of one function
A Hessian that is positive semidefinite everywhere makes the loss convex (second-order condition), and then every critical point is a global minimum: the tangent plane lies below a convex function (first-order condition), and at a critical point that plane is flat. The logistic loss, with Hessian , is the standard example. The eigenvalues also set the speed of first-order methods. On a quadratic, gradient descent needs a step below and converges at a rate set by , and Newton’s method rescales by the inverse Hessian, as the unconstrained optimization note shows.
The losses of neural networks are not convex. Dauphin et al. (2014) argue, from statistical physics, random matrix theory and experiments, that the main difficulty of local methods in high dimension is the proliferation of saddle points, which create plateaus that slow training and can look like minima.
Where it breaks: flat directions#
The second-order test is silent exactly where overparameterized models live. Take the smallest such model, a product of two weights fitted to one target: . Every point of the hyperbola is a global minimum, with . The Hessian is
At it is , with eigenvalues 4 and 0. The zero eigenvalue points along , the direction of the hyperbola, where rescaling , leaves the product, and the loss, unchanged. At the eigenvalues are and 0. On the whole hyperbola , and the determinant is : the test says “undecided” at every minimum. A ReLU network has the same symmetry. Since for , scaling the weights and the bias into a unit by and the weights out of it by leaves the function unchanged, so its minima come in flat families and are never strict.
The Hessian is also too big to use directly. A network with weights has a Hessian with entries, 8 terabytes in double precision. Second-order methods work with Hessian–vector products instead, which cost about as much as a few gradients (Pearlmutter, 1994). The Hessian is the Jacobian of , so is the directional derivative of along , and a central difference of two gradients approximates it; the Code section computes one. And at a kink of a ReLU, a hinge loss or an norm, the gradient does not exist at all; the convexity note handles such points with subgradients.
What you should remember#
- ; partial derivatives alone do not guarantee differentiability.
- : the gradient points uphill most steeply, with rate , and is perpendicular to the level sets.
- The Jacobian is outputs × inputs; is the local factor by which the map scales volume.
- Chain rule: ; for a scalar loss, , evaluated from the loss backwards.
- ; at a critical point the signs of the Hessian’s eigenvalues tell minimum, maximum or saddle.
- A zero eigenvalue leaves the test undecided, and overparameterized models have such flat directions at every minimum.
Code#
Every derivative of the note is checked against central differences: the gradient and the directional derivative of , the Jacobian and the chain rule for , the area of the image of a small square, the second-order expansion and the critical points of , the flat minimum of , and a Hessian–vector product from two gradients. Digits in the last places may vary across platforms.
import numpy as np
from scipy import integrate
def num_grad(f, x, h=1e-6):
"""Central differences, one coordinate at a time."""
E = np.eye(len(x))
return np.array([(f(x + h * e) - f(x - h * e)) / (2 * h) for e in E])
def num_jac(F, x, h=1e-6):
"""Column j is the central difference of F along e_j."""
return np.column_stack([(F(x + h * e) - F(x - h * e)) / (2 * h) for e in np.eye(len(x))])
# the quadratic q: gradient, directional derivative, steepest ascent, the tangent of the level set
q = lambda x: x[0] ** 2 + x[0] * x[1] + 2 * x[1] ** 2
grad_q = lambda x: np.array([2 * x[0] + x[1], x[0] + 4 * x[1]])
x = np.array([1.0, 1.0])
u = np.array([0.6, 0.8]); tangent = np.array([5.0, -3.0]) / np.sqrt(34)
print(q(x), grad_q(x), num_grad(q, x).round(8), round(grad_q(x) @ u, 6), round(np.linalg.norm(grad_q(x)), 3), grad_q(x) @ tangent)
# 4.0 [3. 5.] [3. 5.] 5.8 5.831 0.0
angle = np.degrees(np.arccos(grad_q(x) @ x / np.linalg.norm(grad_q(x)) / np.linalg.norm(x)))
print(round(angle, 1)) # 14.0: the descent direction does not point at the minimum
# the Jacobian of F(x) = (x1^2 - x2^2, 2 x1 x2) and the chain rule with l(v) = v1 + v2^2
F = lambda x: np.array([x[0] ** 2 - x[1] ** 2, 2 * x[0] * x[1]])
J_F = lambda x: np.array([[2 * x[0], -2 * x[1]], [2 * x[1], 2 * x[0]]])
ell = lambda v: v[0] + v[1] ** 2
p = np.array([1.0, 0.5])
print(J_F(p).tolist(), np.abs(num_jac(F, p) - J_F(p)).max() < 1e-8, round(np.linalg.det(J_F(p)), 6)) # [[2.0, -1.0], [1.0, 2.0]] True 5.0
print(J_F(p).T @ np.array([1, 2 * F(p)[1]]), num_grad(lambda x: ell(F(x)), p).round(8)) # [4. 3.] [4. 3.]
# the image of a square of side s centred at p has area integral of |det J| = 4(x1^2 + x2^2) over the square
for s in (0.2, 0.1):
area = integrate.dblquad(lambda y, x: 4 * (x * x + y * y), 1 - s / 2, 1 + s / 2, 0.5 - s / 2, 0.5 + s / 2)[0]
print(s, round(area, 4), round(area / s ** 2, 3)) # 0.2 0.2011 5.027 | 0.1 0.0501 5.007
# the cubic c: second-order Taylor at (1.2, 0.5) with step (0.1, -0.2), then its critical points
c = lambda x: x[0] ** 3 - 3 * x[0] + x[1] ** 2
grad_c = lambda x: np.array([3 * x[0] ** 2 - 3, 2 * x[1]])
hess_c = lambda x: np.array([[6 * x[0], 0.0], [0.0, 2.0]])
x0, h = np.array([1.2, 0.5]), np.array([0.1, -0.2])
lin = c(x0) + grad_c(x0) @ h; quad = lin + 0.5 * h @ hess_c(x0) @ h
print(round(c(x0), 3), round(lin, 3), round(quad, 3), round(c(x0 + h), 3), round(c(x0 + h) - lin, 3), round(c(x0 + h) - quad, 6))
# -1.622 -1.69 -1.614 -1.613 0.077 0.001
print(np.abs(num_jac(grad_c, x0) - hess_c(x0)).max() < 1e-6) # True: the Hessian is the Jacobian of the gradient
for xs in (np.array([1.0, 0.0]), np.array([-1.0, 0.0])):
lam = np.linalg.eigvalsh(hess_c(xs))
kind = 'minimum' if lam.min() > 0 else 'maximum' if lam.max() < 0 else 'saddle' if lam.min() < 0 < lam.max() else 'undecided'
print(xs, grad_c(xs), lam, c(xs), kind)
# [1. 0.] [0. 0.] [2. 6.] -2.0 minimum | [-1. 0.] [0. 0.] [-6. 2.] 2.0 saddle
# a flat minimum: L(a, b) = (ab - 1)^2 has a zero Hessian eigenvalue along the hyperbola ab = 1
L = lambda w: (w[0] * w[1] - 1) ** 2
grad_L = lambda w: np.array([2 * (w[0] * w[1] - 1) * w[1], 2 * (w[0] * w[1] - 1) * w[0]])
for w in (np.array([1.0, 1.0]), np.array([2.0, 0.5])):
H = num_jac(grad_L, w)
print(w, L(w), np.linalg.eigvalsh(H).round(6) + 0.0)
# [1. 1.] 0.0 [0. 4.] | [2. 0.5] 0.0 [0. 8.5]
# a Hessian-vector product from two gradients, without forming the Hessian
v = np.array([0.3, -0.7]); eps = 1e-6
print(((grad_c(x0 + eps * v) - grad_c(x0 - eps * v)) / (2 * eps)).round(6), hess_c(x0) @ v) # [ 2.16 -1.4 ] [ 2.16 -1.4 ]
Next#
The examples so far were differentiated coordinate by coordinate. That stops working for the expressions of machine learning, which are written in whole vectors and matrices: , , . The next note fixes a layout convention and introduces the differential, a way to differentiate such expressions without writing an index, and uses it to derive the gradients that the machine learning notes quote.
References#
- D. Merkulov. Optimization for ML, lecture course, HSE University, 2024. Course page; lecture 2 (gradient, Hessian and Jacobian, Schwarz’s theorem and its counterexample, differentials).
- Y. N. Dauphin, R. Pascanu, C. Gulcehre, K. Cho, S. Ganguli, Y. Bengio. Identifying and attacking the saddle point problem in high-dimensional non-convex optimization. NeurIPS, 2014.
- B. A. Pearlmutter. Fast exact multiplication by the Hessian. Neural Computation, 6(1), 1994.