22.4 Matrix Calculus

In the last two sections we treated a loss as a function of scalar variables. In Section 22.2 we assembled its gradient as a column of partial derivatives, and in Section 22.3 we computed that column by a backward pass through a graph with one number per node. A neural network, however, is not written in scalars: each layer maps a vector to a vector, and its weights form a matrix. What is the derivative of a loss with respect to a vector or a matrix, and how do we compute it for a whole layer at once?

A network small enough to work by hand shows what is needed. Consider a network with two inputs, two ReLU hidden units, and one output,

g(x)=w2⊤φ(W1x+b),W1=(123−1),b=(0−4),w2=(2−1),g(\mathbf x)=\mathbf w_2^\top\boldsymbol\varphi(\mathbf W_1\mathbf x+\mathbf b),\qquad \mathbf W_1=\begin{pmatrix}1&2\\3&-1\end{pmatrix},\quad \mathbf b=\begin{pmatrix}0\\-4\end{pmatrix},\quad \mathbf w_2=\begin{pmatrix}2\\-1\end{pmatrix},

where φ\boldsymbol\varphi applies max⁡(0,⋅)\max(0,\cdot) to each entry. At x=(1,1)\mathbf x=(1,1) the pre-activations are W1x+b=(3,−2)\mathbf W_1\mathbf x+\mathbf b=(3,-2), so the second hidden unit is off, the hidden vector is (3,0)(3,0), and the output is g=6g=6. A training step raises three questions about this output. First, if the input moves by a small δ\boldsymbol\delta, the output changes by 2δ1+4δ22\delta_1+4\delta_2, a row of two numbers that is the transpose of the column gradient. Second, if the weight matrix moves by ΔW1\Delta\mathbf W_1, the output changes by 2 ΔW11+2 ΔW122\,\Delta W_{11}+2\,\Delta W_{12} and not at all through the second row, so the derivative with respect to a matrix is itself a matrix, (2200)\left(\begin{smallmatrix}2&2\\0&0\end{smallmatrix}\right). Third, the hidden layer x↦φ(W1x+b)\mathbf x\mapsto\boldsymbol\varphi(\mathbf W_1\mathbf x+\mathbf b) maps a vector to a vector. Neither a scalar slope nor a gradient vector describes its derivative, yet the output depends on W1\mathbf W_1 only through that layer.

Derivatives like these are surprisingly easy to get wrong by hand. If you drop a transpose on a square weight matrix, the dimensions still match, no error is raised, and training simply goes astray. Reference tables of matrix derivatives run to hundreds of entries, yet looking up formulas does little to protect against that kind of slip.

This section answers all three questions with a single object and a single principle. The derivative of a vector-valued map is a matrix, the Jacobian, defined as the map's best linear approximation. Composing maps multiplies their Jacobians, so the derivative of a network becomes a product of matrices, one per layer. Every gradient a layer needs (linear and quadratic forms, least squares, matrix products, and softmax) then follows from one method: write down the first-order change of the function and read off the gradient as its coefficient. That same method produces the backward pass of each layer used in Section 4.3, as well as p−y\mathbf p-\mathbf y, the classifier gradient of Section 3.1.2.2.

Three results are worth remembering: the product of Jacobians (22.4.6), the rule that a gradient always has the shape of its variable, and the backward rule (22.4.9) for a matrix product. You can skip the proof of the chain rule on a first reading, but not the differential method (Section 22.4.3.1), since everything that follows relies on it.

We use the following imports throughout this section.

import numpy as np
import torch

22.4.1 The Jacobian#

22.4.1.1 The Best Linear Approximation#

Near x=(1,1)\mathbf x=(1,1) the hidden layer of our network is affine, so its linear approximation is exact there and leaves no error to study. Let us therefore begin with a curved map that we will reuse as a running example here and in the next section, returning to the network once the definition is in place:

f(x,y)=(x+sin⁡yy+x2/2),x0=(0.5, 0.5).\mathbf f(x,y)=\begin{pmatrix}x+\sin y\\ y+x^2/2\end{pmatrix},\qquad \mathbf x_0=(0.5,\ 0.5).

At x0\mathbf x_0, the map evaluates to f(x0)=(0.9794, 0.6250)\mathbf f(\mathbf x_0)=(0.9794,\ 0.6250). Each of the two outputs has two partial derivatives: ∂f1/∂x=1\partial f_1/\partial x=1, ∂f1/∂y=cos⁡y=0.8776\partial f_1/\partial y=\cos y=0.8776, ∂f2/∂x=x=0.5\partial f_2/\partial x=x=0.5, and ∂f2/∂y=1\partial f_2/\partial y=1. We arrange these four numbers in a matrix with one row per output and one column per input,

J(x0)=(1cos⁡0.50.51)=(10.87760.51).\mathbf J(\mathbf x_0)=\begin{pmatrix}1&\cos 0.5\\0.5&1\end{pmatrix} =\begin{pmatrix}1&0.8776\\0.5&1\end{pmatrix}.

Column jj records how both outputs respond when input jj moves. This matrix is the derivative of f\mathbf f at x0\mathbf x_0, in the sense that f(x0+δ)≈f(x0)+Jδ\mathbf f(\mathbf x_0+\boldsymbol\delta)\approx\mathbf f(\mathbf x_0)+\mathbf J\boldsymbol\delta for small δ\boldsymbol\delta, and no other matrix approximates f\mathbf f as closely.

In one variable, the derivative is the slope of the best straight-line fit, f(x+δ)≈f(x)+f′(x) δf(x+\delta)\approx f(x)+f'(x)\,\delta. The vector-valued generalization rests on the same local approximation. We say that f:Rn→Rm\mathbf f:\mathbb R^n\to\mathbb R^m is differentiable at x\mathbf x if there is a matrix J∈Rm×n\mathbf J\in\mathbb R^{m\times n} such that

f(x+δ)=f(x)+J δ+o(∥δ∥),(22.4.1)\mathbf f(\mathbf x+\boldsymbol\delta) = \mathbf f(\mathbf x) + \mathbf J\,\boldsymbol\delta + o(\|\boldsymbol\delta\|), \tag{22.4.1}

meaning that the error of the linear model f(x)+Jδ\mathbf f(\mathbf x)+\mathbf J\boldsymbol\delta divided by ∥δ∥\|\boldsymbol\delta\| tends to zero as δ→0\boldsymbol\delta\to\mathbf 0. Whenever such a matrix exists, it is unique. We call it the Jacobian Jf(x)\mathbf J_{\mathbf f}(\mathbf x), and its entries are simply the partial derivatives:

[Jf]ij=∂fi∂xj.(22.4.2)[\mathbf J_{\mathbf f}]_{ij} = \frac{\partial f_i}{\partial x_j}. \tag{22.4.2}

To see why, substitute the perturbation δ=t ej\boldsymbol\delta=t\,\mathbf e_j (a small step along coordinate axis jj) into (22.4.1) and look at component ii. Dividing by tt and letting t→0t\to0 leaves ∂fi/∂xj\partial f_i/\partial x_j in the (i,j)(i,j) slot, regardless of which matrix J\mathbf J we started with. The partial derivatives therefore supply the entries of J\mathbf J, while the linear approximation is what defines it.

The existence of partial derivatives alone does not guarantee differentiability. Consider the function f(x,y)=2xy/(x2+y2)f(x,y)=2xy/(x^2+y^2) with f(0,0)=0f(0,0)=0 from Section 22.2.1.2: both partials are 00 at the origin, yet ff equals 11 everywhere along the diagonal x=yx=y. The only candidate Jacobian is the zero row vector, whose approximation error along the diagonal remains 11 no matter how small δ\boldsymbol\delta is, so ff has no Jacobian at the origin. Continuity of the partial derivatives is sufficient to rule out such behavior: if every partial ∂fi/∂xj\partial f_i/\partial x_j exists in a neighborhood of x\mathbf x and is continuous at x\mathbf x, then f\mathbf f is differentiable at x\mathbf x (Rudin, 1976).

Figure 22.4.1 illustrates the definition geometrically: near x0\mathbf x_0, the map acts like its Jacobian. A circle of radius rr around x0\mathbf x_0 maps nearly onto the ellipse f(x0)+Jδ\mathbf f(\mathbf x_0)+\mathbf J\boldsymbol\delta (∥δ∥=r\|\boldsymbol\delta\|=r), whose semi-axes are rr times the singular values of J\mathbf J (as shown in Section 21.5, any matrix maps the unit circle to an ellipse with these semi-axes). Here the singular values are 1.7061.706 and 0.3290.329, so the circle of radius 0.350.35 becomes an ellipse with semi-axes 0.600.60 and 0.120.12. The largest gap between the true image and the ellipse is 0.0610.061 at r=0.35r=0.35 and 0.0150.015 at r=0.175r=0.175: halving the radius cuts the gap fourfold.

Figure 22.4.1:

A differentiable map is locally its Jacobian. Two circles of radius 0.350.35 and 0.1750.175 around x0=(0.5,0.5)\mathbf x_0=(0.5,0.5) (left) and their images under f(x,y)=(x+sin⁡y, y+x2/2)\mathbf f(x,y)=(x+\sin y,\ y+x^2/2) (right, blue) against the ellipses f(x0)+J(x0)δ\mathbf f(\mathbf x_0)+\mathbf J(\mathbf x_0)\boldsymbol\delta (orange, dashed). The semi-axes of each ellipse are the radius times the singular values 1.711.71 and 0.330.33 of J\mathbf J. Halving the radius cuts the largest gap between image and ellipse from 0.0610.061 to 0.0150.015, the o(∥δ∥)o(\|\boldsymbol\delta\|) remainder.

The definition guarantees that the error of the linear model divided by ∥δ∥\|\boldsymbol\delta\| tends to zero, but it does not say how fast. Let us shrink a perturbation tenfold at a time and inspect that ratio.

def f(v):                                   # the running map, R^2 -> R^2
    x, y = v
    return np.array([x + np.sin(y), y + x**2 / 2])

def J(v):                                   # its Jacobian, entry by entry
    x, y = v
    return np.array([[1.0, np.cos(y)], [x, 1.0]])

x0 = np.array([0.5, 0.5])
for s in [1, 0.1, 0.01, 0.001]:
    delta = s * np.array([0.2, 0.1])
    err = np.linalg.norm(f(x0 + delta) - f(x0) - J(x0) @ delta)
    print(f'|delta| = {np.linalg.norm(delta):.1e}   '
          f'error / |delta| = {err / np.linalg.norm(delta):.1e}')
|delta| = 2.2e-01   error / |delta| = 9.0e-02
|delta| = 2.2e-02   error / |delta| = 9.0e-03
|delta| = 2.2e-03   error / |delta| = 9.0e-04
|delta| = 2.2e-04   error / |delta| = 9.0e-05

The ratio drops from 0.090.09 to 0.0090.009, 0.00090.0009, and 0.000090.00009. It tends to zero, confirming the o(∥δ∥)o(\|\boldsymbol\delta\|) remainder in the definition. Notice that it also falls tenfold for every tenfold reduction in ∥δ∥\|\boldsymbol\delta\|, which means the error itself falls a hundredfold and is O(∥δ∥2)O(\|\boldsymbol\delta\|^2). The definition promises only the first property; the faster quadratic decay holds because f\mathbf f has continuous second derivatives.

22.4.1.2 Gradients, Hessians, and the Shape of a Derivative#

Both the gradient and the Hessian from Section 22.2 are special cases of the Jacobian. Viewing them this way settles a shape question that arises in every hand derivation: whether a derivative is a row or a column, and how a derivative with respect to a matrix should be arranged.

For a scalar-valued function f:Rn→Rf:\mathbb R^n\to\mathbb R (m=1m=1), the Jacobian is a single row, ∂f/∂x=[∂f/∂x1,…,∂f/∂xn]\partial f/\partial\mathbf x=[\partial f/\partial x_1,\ldots,\partial f/\partial x_n], and (22.4.1) becomes the first-order expansion f(x+δ)≈f(x)+(∂f/∂x) δf(\mathbf x+\boldsymbol\delta)\approx f(\mathbf x)+(\partial f/\partial\mathbf x)\,\boldsymbol\delta. In Section 22.2 we wrote the gradient as a column vector. The two are simply transposes of each other,

∇xf=(∂f∂x) ⁣⊤,(22.4.3)\nabla_{\mathbf x} f = \Bigl(\frac{\partial f}{\partial\mathbf x}\Bigr)^{\!\top}, \tag{22.4.3}

and we use both in this book, each for its own purpose. Jacobians of vector-valued maps are m×nm\times n, with one row per output, so that the chain rule below composes cleanly without transposes. Gradients of scalars are column vectors, ∇xf\nabla_{\mathbf x}f, matching the shape of x\mathbf x so an optimizer can subtract them directly. For our opening network, ∂g/∂x=(2, 4)\partial g/\partial\mathbf x=(2,\ 4) is a 1×21\times2 Jacobian, while ∇xg=(2,4)⊤\nabla_{\mathbf x}g=(2,4)^\top is the column gradient.

A scalar function of a matrix W∈Rp×q\mathbf W\in\mathbb R^{p\times q} needs one more convention. We define its gradient ∇Wf\nabla_{\mathbf W}f as the p×qp\times q matrix with entries ∂f/∂Wij\partial f/\partial W_{ij}, matching the shape of W\mathbf W. The first-order expansion then reads

f(W+E)=f(W)+⟨∇Wf, E⟩+o(∥E∥),⟨A,B⟩=tr⁡(A⊤B)=∑ijAijBij,(22.4.4)f(\mathbf W+\mathbf E)=f(\mathbf W)+\langle\nabla_{\mathbf W}f,\ \mathbf E\rangle+o(\|\mathbf E\|), \qquad \langle\mathbf A,\mathbf B\rangle=\operatorname{tr}(\mathbf A^\top\mathbf B)=\sum_{ij}A_{ij}B_{ij}, \tag{22.4.4}

where the inner product ⟨⋅,⋅⟩\langle\cdot,\cdot\rangle multiplies two matrices of the same shape entry by entry and sums the products, just like the ordinary dot product of the matrices flattened into vectors. In words, the first-order change in ff is the sum over all entries of "sensitivity times nudge". In our opening example, ∇W1g\nabla_{\mathbf W_1}g is the 2×22\times2 matrix (2200)\left(\begin{smallmatrix}2&2\\0&0\end{smallmatrix}\right), and ⟨∇W1g,ΔW1⟩=2 ΔW11+2 ΔW12\langle\nabla_{\mathbf W_1}g,\Delta\mathbf W_1\rangle=2\,\Delta W_{11}+2\,\Delta W_{12} recovers the change we found earlier. This gives a single sanity check for every formula in the section: a gradient always has the shape of its variable. If a derived gradient does not, a transpose is missing.

Differentiating once more brings in the Hessian. The gradient field ∇f:Rn→Rn\nabla f:\mathbb R^n\to\mathbb R^n is itself a vector-valued map, and its Jacobian is the matrix of second partials, the Hessian Hf\mathbf H_f, whose entries are [Hf]ij=∂2f/∂xi∂xj[\mathbf H_f]_{ij}=\partial^2 f/\partial x_i\partial x_j. Strictly speaking, [J∇f]ij=∂2f/∂xj∂xi[\mathbf J_{\nabla f}]_{ij}=\partial^2 f/\partial x_j\partial x_i takes the two derivatives in the opposite order, but the two agree, and Hf\mathbf H_f is symmetric, whenever the mixed partials are continuous (the Clairaut–Schwarz theorem of Section 22.2).

22.4.2 The Chain Rule for Jacobians#

A neural network is a composition of layers. On a graph of scalars, the chain rule summed the product of derivatives over every path from an input to an output (Section 22.3.1). When the layers are vector-valued maps, that sum over paths becomes a matrix product.

22.4.2.1 Composition as a Matrix Product#

Proposition (chain rule). If f:Rn→Rp\mathbf f:\mathbb R^n\to\mathbb R^p is differentiable at x\mathbf x and g:Rp→Rm\mathbf g:\mathbb R^p\to\mathbb R^m is differentiable at f(x)\mathbf f(\mathbf x), then g∘f\mathbf g\circ\mathbf f is differentiable at x\mathbf x and

Jg∘f(x)=Jg ⁣(f(x)) Jf(x).(22.4.5)\mathbf J_{\mathbf g\circ\mathbf f}(\mathbf x) = \mathbf J_{\mathbf g}\!\bigl(\mathbf f(\mathbf x)\bigr)\,\mathbf J_{\mathbf f}(\mathbf x). \tag{22.4.5}

Proof. Write y=f(x)\mathbf y=\mathbf f(\mathbf x), A=Jf(x)\mathbf A=\mathbf J_{\mathbf f}(\mathbf x), and B=Jg(y)\mathbf B=\mathbf J_{\mathbf g}(\mathbf y). The idea is simply to substitute the linear model for f\mathbf f into the linear model for g\mathbf g. By (22.4.1), f(x+δ)=y+Aδ+o(∥δ∥)\mathbf f(\mathbf x+\boldsymbol\delta)=\mathbf y+\mathbf A\boldsymbol\delta +o(\|\boldsymbol\delta\|). Calling that displacement η=Aδ+o(∥δ∥)\boldsymbol\eta=\mathbf A\boldsymbol\delta+o(\|\boldsymbol\delta\|) and passing it to g\mathbf g gives

g(f(x+δ))=g(y)+B η+o(∥η∥)=g(y)+BA δ+o(∥δ∥).\mathbf g\bigl(\mathbf f(\mathbf x+\boldsymbol\delta)\bigr) = \mathbf g(\mathbf y) + \mathbf B\,\boldsymbol\eta + o(\|\boldsymbol\eta\|) = \mathbf g(\mathbf y) + \mathbf B\mathbf A\,\boldsymbol\delta + o(\|\boldsymbol\delta\|).

The second equality relies on two facts. First, multiplying an o(∥δ∥)o(\|\boldsymbol\delta\|) remainder by the fixed matrix B\mathbf B leaves it o(∥δ∥)o(\|\boldsymbol\delta\|). Second, because ∥η∥≤∥A∥ ∥δ∥+o(∥δ∥)\|\boldsymbol\eta\|\le\|\mathbf A\|\,\|\boldsymbol\delta\|+o(\|\boldsymbol\delta\|) is bounded by a constant multiple of ∥δ∥\|\boldsymbol\delta\|, the remainder o(∥η∥)o(\|\boldsymbol\eta\|) from g\mathbf g is also o(∥δ∥)o(\|\boldsymbol\delta\|); this is the one step that is not purely algebraic. The coefficient of δ\boldsymbol\delta is therefore a matrix satisfying (22.4.1), and by uniqueness it is the Jacobian of the composite: Jg∘f=BA\mathbf J_{\mathbf g\circ\mathbf f}=\mathbf B\mathbf A. ■\blacksquare

Looking at a single entry of the product recovers the scalar sum over paths: [BA]ik=∑j(∂gi/∂yj)(∂fj/∂xk)[\mathbf B\mathbf A]_{ik}=\sum_j (\partial g_i/\partial y_j)(\partial f_j/\partial x_k) sums, over all intermediate variables yjy_j, the product of derivatives along each path from xkx_k to gig_i.

22.4.2.2 The Jacobian of a Network#

Returning to our opening network, we can view it as a composition of three maps: the affine transformation a=W1x+b\mathbf a=\mathbf W_1\mathbf x+\mathbf b, the ReLU activation h=φ(a)\mathbf h=\boldsymbol\varphi(\mathbf a), and the linear output g=w2⊤hg=\mathbf w_2^\top\mathbf h. The first map is already affine, so its Jacobian is W1\mathbf W_1; the bias shifts the value without changing the slope. The ReLU acts on each entry independently, with slope 11 where ai>0a_i>0 and 00 where ai<0a_i\lt 0, so its Jacobian is the diagonal matrix diag⁡(m)\operatorname{diag}(\mathbf m) formed from the mask m\mathbf m of these slopes. Finally, the output map has Jacobian w2⊤\mathbf w_2^\top. At x=(1,1)\mathbf x=(1,1), where a=(3,−2)\mathbf a=(3,-2) and m=(1,0)\mathbf m=(1,0), the chain rule multiplies the three factors:

Jg(x)=w2⊤diag⁡(m) W1=(2−1)(1000)(123−1)=(20)(123−1)=(24).\mathbf J_g(\mathbf x)=\mathbf w_2^\top\operatorname{diag}(\mathbf m)\,\mathbf W_1 =\begin{pmatrix}2&-1\end{pmatrix}\begin{pmatrix}1&0\\0&0\end{pmatrix}\begin{pmatrix}1&2\\3&-1\end{pmatrix} =\begin{pmatrix}2&0\end{pmatrix}\begin{pmatrix}1&2\\3&-1\end{pmatrix} =\begin{pmatrix}2&4\end{pmatrix}.

The mask zeroes out the second entry of w2⊤\mathbf w_2^\top, so the second row of W1\mathbf W_1 never reaches the output: the weights of an inactive unit contribute nothing to the derivative (Figure 22.4.2). The resulting row (2,4)(2,4) matches the change 2δ1+4δ22\delta_1+4\delta_2 from the opening. At a different input, the mask changes and so does the Jacobian. For instance, at x=(2,−3)\mathbf x=(2,-3) the pre-activations are (−4,5)(-4,5), the mask flips to (0,1)(0,1), and Jg=(0, −1) W1=(−3, 1)\mathbf J_g=(0,\ -1)\,\mathbf W_1=(-3,\ 1). Because ReLU is piecewise linear, a finite difference along each axis reproduces these entries exactly for any step small enough to keep the mask fixed (exercise 1).

Figure 22.4.2:

The Jacobian of the 2-2-1 ReLU network at x=(1,1)\mathbf x=(1,1) is the product of three matrices. The second unit's pre-activation is −2-2, so its mask entry is 00 and the second row of W1\mathbf W_1 never reaches the output: Jg=w2⊤diag⁡(1,0) W1=(2, 4)\mathbf J_g=\mathbf w_2^\top\operatorname{diag}(1,0)\,\mathbf W_1=(2,\ 4).

Every multilayer perceptron is built from the same two kinds of factors. A dense layer x↦Wx\mathbf x\mapsto\mathbf W\mathbf x has Jacobian W\mathbf W. An elementwise activation φ(x)=(φ(x1),…,φ(xn))\boldsymbol\varphi(\mathbf x)=(\varphi(x_1),\ldots,\varphi(x_n)) does not couple distinct coordinates, so its Jacobian is diagonal: Jφ(x)=diag⁡(φ′(x1),…,φ′(xn))\mathbf J_{\boldsymbol\varphi}(\mathbf x)=\operatorname{diag}\bigl(\varphi'(x_1),\ldots,\varphi'(x_n)\bigr). This assumes that φ\varphi is differentiable at every xix_i; ReLU has no derivative at 00, where frameworks supply a fixed value by convention (Section 22.1.6). A network of depth KK is a composition f=fK∘⋯∘f1\mathbf f=\mathbf f_K\circ\cdots\circ\mathbf f_1, and iterating (22.4.5) turns its derivative into a single product,

J=JK JK−1⋯J1,(22.4.6)\mathbf J = \mathbf J_K\,\mathbf J_{K-1}\cdots\mathbf J_1, \tag{22.4.6}

with each factor evaluated at the input of its own layer. For alternating dense layers and activations, this becomes J=diag⁡(φK′) WK⋯diag⁡(φ1′) W1\mathbf J=\operatorname{diag}(\boldsymbol\varphi_K')\,\mathbf W_K\cdots \operatorname{diag}(\boldsymbol\varphi_1')\,\mathbf W_1: weight matrices interleaved with diagonal matrices. Because multiplying a vector by a diagonal matrix simply scales each entry, each activation factor costs O(n)O(n) operations rather than O(n2)O(n^2).

Let us now define the 2-2-1 network in code, which we will reuse later in the section, and compare the product w2⊤diag⁡(m)W1\mathbf w_2^\top\operatorname{diag}(\mathbf m)\mathbf W_1 against the gradient returned by automatic differentiation.

W1, b = torch.tensor([[1.0, 2.0], [3.0, -1.0]]), torch.tensor([0.0, -4.0])
w2, x = torch.tensor([2.0, -1.0]), torch.tensor([1.0, 1.0])

def g(x, W1, b, w2):                         # the 2-2-1 ReLU network
    return w2 @ torch.relu(W1 @ x + b)

m = (W1 @ x + b > 0).float()                 # the ReLU mask
print('by hand    :', (w2 @ torch.diag(m) @ W1).numpy())
print('by autograd:', torch.func.grad(g)(x, W1, b, w2).numpy())
by hand    : [2. 4.]
by autograd: [2. 4.]

Both lines print (2,4)(2,4), as expected.

The product (22.4.6) also tells us how large or small a derivative can grow through a deep network. When every factor is the same matrix W\mathbf W (as in a recurrent network applying one weight matrix at every step, ignoring the activations), the product simplifies to WK\mathbf W^K. For a diagonalizable matrix W=VΛV−1\mathbf W=\mathbf V\boldsymbol\Lambda\mathbf V^{-1} we have WK=VΛKV−1\mathbf W^K=\mathbf V\boldsymbol\Lambda^K\mathbf V^{-1}, so for large KK its norm grows or shrinks like ∣λmax⁡∣K|\lambda_{\max}|^K, where λmax⁡\lambda_{\max} is the eigenvalue of largest magnitude: 0.950≈0.0050.9^{50}\approx0.005, whereas 1.150≈1171.1^{50}\approx117. This exponential scaling is the vanishing and exploding gradient problem of deep and recurrent networks (Section 4.4, Section 8.5). Keep in mind that ∣λmax⁡∣K|\lambda_{\max}|^K describes only the long-run rate. When the eigenvectors in V\mathbf V are far from orthogonal, the product can grow for many steps before eventually decaying (Section 21.4.2.3), and a product of distinct factors is governed by singular values rather than eigenvalues (Section 21.4.2.5).

Notice, however, an important limitation of (22.4.6) for training: it gives the derivative with respect to the input. The weight matrices Wk\mathbf W_k appear in it as fixed factors rather than variables, so it does not yet tell us how the output changes when a weight changes. Computing weight gradients requires one more rule per layer, which Section 22.4.3.2 derives and applies to this same network.

22.4.2.3 The Order of Multiplication#

Because matrix multiplication is associative, we may bracket the product (22.4.6) in any order and obtain the exact same matrix. Yet different bracketings differ enormously in cost, by a factor that grows with the width of the network. In training we want the gradient of a scalar loss ℓ\ell, so the chain starts on the left with a row vector: the 1×h1\times h Jacobian u⊤=∂ℓ/∂hK\mathbf u^\top=\partial\ell/\partial\mathbf h_K of the loss with respect to the last layer's output hK\mathbf h_K. Multiplying from the left keeps every intermediate result a row vector, so every step is a matrix–vector product. Multiplying from the right instead forms expensive matrix–matrix products all the way across until the row vector finally arrives at the end. The cheap order is the one that keeps every step a matrix–vector product.

A quick operation count makes the gap concrete. Consider u⊤J3J2J1\mathbf u^\top\mathbf J_3\mathbf J_2\mathbf J_1 with shapes 1×h1\times h, h×hh\times h, h×hh\times h, and h×nh\times n, taking h=n=1000h=n=1000 and recalling that multiplying a p×qp\times q matrix by a q×rq\times r matrix costs pqrpqr multiplications. From the left, we perform three matrix–vector products for a total of h2+h2+hn=3×106h^2+h^2+hn=3\times10^6 multiplications. From the right, forming J2J1\mathbf J_2\mathbf J_1 and then J3(J2J1)\mathbf J_3(\mathbf J_2\mathbf J_1) costs h2n=109h^2n=10^9 multiplications each, and the final product with u⊤\mathbf u^\top adds hn=106hn=10^6, totaling 2.001×1092.001\times10^9. Three million against two billion is a factor of about 670670, or 2h/32h/3 (Figure 22.4.3).

Figure 22.4.3:

Two orders for u⊤J3J2J1\mathbf u^\top\mathbf J_3\mathbf J_2\mathbf J_1 with h=n=1000h=n=1000. From the left every intermediate is a 1×h1\times h row and every step is a matrix–vector product: 3×1063\times10^6 multiplications. From the right the first two steps are matrix–matrix products of 10910^9 multiplications each. The shapes, not the depth, decide the cost.

These two orders correspond to two directions through the network. Multiplying from the left propagates the sensitivity of the output backward through the layers, at the cost of one matrix–vector product per layer. Multiplying from the right is the cheap order when a column vector v\mathbf v stands at the right end of the chain: it propagates a single input direction forward and yields Jv\mathbf J\mathbf v. Algorithms that automate these two orders are called reverse-mode and forward-mode automatic differentiation (Section 22.5).

The count above assumed layers of equal width. When the factors have varying shapes, neither end-to-end order need be optimal. For a chain, the cheapest parenthesization can be found by dynamic programming (exercise 2); for a general computation graph, the problem is NP-complete (Naumann, 2008).

22.4.3 Derivatives with Respect to Vectors and Matrices#

Training a layer requires the gradient of a scalar loss with respect to vectors and matrices alike: its input, its weights, and its bias. In this section we derive every gradient we need with a single method, one that automatically returns each result in the shape of its variable.

22.4.3.1 The Differential Method#

Write dxd\mathbf x for a small perturbation of the variable and dfdf for the part of the resulting change in ff that is linear in dxd\mathbf x—simply the term Jδ\mathbf J\boldsymbol\delta of (22.4.1) with δ\boldsymbol\delta renamed dxd\mathbf x. By (22.4.1) and (22.4.4), this linear part is an inner product with the gradient,

df=⟨∇f, dx⟩,(22.4.7)df=\langle\nabla f,\ d\mathbf x\rangle, \tag{22.4.7}

for both vector variables (⟨a,b⟩=a⊤b\langle\mathbf a,\mathbf b\rangle=\mathbf a^\top\mathbf b) and matrix variables. We can read (22.4.7) in two ways. Given the gradient, it tells us how ff responds to a nudge. Given ff, it gives a direct recipe for the gradient: compute dfdf using the ordinary rules of differentiation, rearrange it into the form ⟨M, dx⟩\langle\mathbf M,\,d\mathbf x\rangle, and read off ∇f=M\nabla f=\mathbf M. This reading is unambiguous because a linear function of dxd\mathbf x can be written as ⟨M,dx⟩\langle\mathbf M,d\mathbf x\rangle for only one M\mathbf M: setting dxd\mathbf x to the matrix with a single 11 in position (i,j)(i,j) and zeros elsewhere isolates MijM_{ij}.

Four familiar rules suffice to compute dfdf. First, the differential is linear. Second, it obeys the product rule d(AB)=dA B+A dBd(\mathbf A\mathbf B)=d\mathbf A\,\mathbf B+\mathbf A\,d\mathbf B, because expanding (A+dA)(B+dB)(\mathbf A+d\mathbf A)(\mathbf B+d\mathbf B) differs from AB+dA B+A dB\mathbf A\mathbf B+d\mathbf A\,\mathbf B+\mathbf A\,d\mathbf B only by the second-order term dA dBd\mathbf A\,d\mathbf B. Third, it commutes with transposition, d(A⊤)=(dA)⊤d(\mathbf A^\top)=(d\mathbf A)^\top. Fourth, a scalar function applied entry by entry obeys the scalar chain rule in every entry, dφ(X)=φ′(X)⊙dXd\varphi(\mathbf X)=\varphi'(\mathbf X)\odot d\mathbf X, where ⊙\odot denotes elementwise multiplication.

To rearrange dfdf into the form ⟨M,dx⟩\langle\mathbf M,d\mathbf x\rangle, we need just one more tool. The move rule shifts a factor standing next to dxd\mathbf x across to the other side of the inner product:

⟨A, BC⟩=⟨B⊤A, C⟩=⟨AC⊤, B⟩,\langle\mathbf A,\ \mathbf B\mathbf C\rangle =\langle\mathbf B^\top\mathbf A,\ \mathbf C\rangle =\langle\mathbf A\mathbf C^\top,\ \mathbf B\rangle,

which follows directly from the cyclic property of the trace, tr⁡(XY)=tr⁡(YX)\operatorname{tr}(\mathbf X\mathbf Y)=\operatorname{tr}(\mathbf Y\mathbf X): tr⁡(A⊤BC)=tr⁡((B⊤A)⊤C)=tr⁡(CA⊤B)=tr⁡((AC⊤)⊤B)\operatorname{tr}(\mathbf A^\top\mathbf B\mathbf C)=\operatorname{tr}\bigl((\mathbf B^\top\mathbf A)^\top\mathbf C\bigr) =\operatorname{tr}(\mathbf C\mathbf A^\top\mathbf B)=\operatorname{tr}\bigl((\mathbf A\mathbf C^\top)^\top\mathbf B\bigr). In words, a factor to the left of the variable moves across as its transpose on the left, while a factor to the right moves across as its transpose on the right. An elementwise factor moves across unchanged, ⟨A,B⊙C⟩=⟨A⊙B,C⟩\langle\mathbf A,\mathbf B\odot\mathbf C\rangle=\langle\mathbf A\odot\mathbf B,\mathbf C\rangle, since both sides equal ∑ijAijBijCij\sum_{ij}A_{ij}B_{ij}C_{ij}.

The two simplest cases take one line each. For a linear form, d(a⊤x)=a⊤dx=⟨a,dx⟩d(\mathbf a^\top\mathbf x)=\mathbf a^\top d\mathbf x=\langle\mathbf a,d\mathbf x\rangle, so ∇x a⊤x=a\nabla_{\mathbf x}\,\mathbf a^\top\mathbf x=\mathbf a. For a quadratic form, the product rule hits both copies of x\mathbf x:

d(x⊤Ax)=dx⊤Ax+x⊤A dx=x⊤A⊤dx+x⊤A dx=⟨(A+A⊤)x, dx⟩.\begin{aligned} d(\mathbf x^\top\mathbf A\mathbf x) &=d\mathbf x^\top\mathbf A\mathbf x+\mathbf x^\top\mathbf A\,d\mathbf x =\mathbf x^\top\mathbf A^\top d\mathbf x+\mathbf x^\top\mathbf A\,d\mathbf x \\ &=\bigl\langle(\mathbf A+\mathbf A^\top)\mathbf x,\ d\mathbf x\bigr\rangle. \end{aligned}

In the second equality we transposed a 1×11\times1 matrix: dx⊤Axd\mathbf x^\top\mathbf A\mathbf x is a scalar, so it equals its own transpose x⊤A⊤dx\mathbf x^\top\mathbf A^\top d\mathbf x. Reading off the coefficient yields ∇x x⊤Ax=(A+A⊤)x\nabla_{\mathbf x}\,\mathbf x^\top\mathbf A\mathbf x=(\mathbf A+\mathbf A^\top)\mathbf x, which simplifies to 2Ax2\mathbf A\mathbf x whenever A\mathbf A is symmetric.

Writing out indices offers a second route. Entry by entry, the same derivative is ∂(∑ijxiAijxj)/∂xk=∑jAkjxj+∑ixiAik\partial\bigl(\sum_{ij}x_iA_{ij}x_j\bigr)/\partial x_k=\sum_jA_{kj}x_j+\sum_ix_iA_{ik}, recovering the kk-th entry of (A+A⊤)x(\mathbf A+\mathbf A^\top)\mathbf x. Index derivations are longer, but they leave no doubt about transposes; Section 4.3 uses them to derive the matrix-product rule.

A fast sanity check on any matrix identity is to set every matrix to 1×11\times1, in which case the formula must reduce to the familiar scalar rule. Our quadratic-form gradient passes, since ddx(ax2)=2ax=(a+a)x\frac{d}{dx}(ax^2)=2ax=(a+a)x. This 1×11\times1 check reliably catches a wrong coefficient or a missing term, but it is blind to transposes and factor order because 1×11\times1 matrices commute and equal their own transposes. The shape rule catches most transpose errors, though unfortunately not when the factor is square—the exact pitfall we warned about at the start of the section. For square factors, only a numerical check will catch the mistake. Take A=(0100)\mathbf A=\left(\begin{smallmatrix}0&1\\0&0\end{smallmatrix}\right) and x=(1,2)\mathbf x=(1,2). Then x⊤Ax=x1x2\mathbf x^\top\mathbf A\mathbf x=x_1x_2, whose true gradient (x2,x1)=(2,1)(x_2,x_1)=(2,1) equals (A+A⊤)x(\mathbf A+\mathbf A^\top)\mathbf x. The naive guess 2Ax=(4,0)2\mathbf A\mathbf x=(4,0), suggested by the scalar rule 2ax2ax, passes the 1×11\times1 check, has the right shape, and is still wrong.

The differential method handles matrix variables with no extra effort. For the least-squares loss ℓ=∥Wx−y∥2\ell=\|\mathbf W\mathbf x-\mathbf y\|^2 with residual r=Wx−y\mathbf r=\mathbf W\mathbf x-\mathbf y, varying W\mathbf W gives dr=dW xd\mathbf r=d\mathbf W\,\mathbf x, and the move rule shifts x\mathbf x to the other side: dℓ=2r⊤dr=⟨2r, dW x⟩=⟨2rx⊤, dW⟩d\ell=2\mathbf r^\top d\mathbf r=\langle 2\mathbf r,\ d\mathbf W\,\mathbf x\rangle =\langle2\mathbf r\mathbf x^\top,\ d\mathbf W\rangle. Therefore,

∇W∥Wx−y∥2=2 (Wx−y) x⊤,(22.4.8)\nabla_{\mathbf W}\|\mathbf W\mathbf x-\mathbf y\|^2 = 2\,(\mathbf W\mathbf x-\mathbf y)\,\mathbf x^\top, \tag{22.4.8}

a rank-one outer product of the residual with the input, automatically in the shape of W\mathbf W. When x\mathbf x varies instead, dr=W dxd\mathbf r=\mathbf W\,d\mathbf x and ∇xℓ=2W⊤r\nabla_{\mathbf x}\ell=2\mathbf W^\top\mathbf r. In both cases, the gradient is twice the residual multiplied by the transpose of whichever factor multiplies the variable.

22.4.3.2 Backward Rules of a Layer#

Inside a network, a layer Y=F(X)\mathbf Y=\mathbf F(\mathbf X) is one step in a long computation ending in a scalar loss ℓ\ell. Forming its full Jacobian is out of the question: a 1000×10001000\times1000 weight matrix applied to a minibatch of 10001000 examples produces 10610^6 outputs from 10610^6 weights, so the Jacobian of outputs with respect to weights would have 101210^{12} entries. Fortunately, backpropagation needs far less. All a layer must do is turn the gradient of the loss with respect to its output into the gradients with respect to its inputs and weights. Following Section 22.3.2, we write Yˉ=∇Yℓ\bar{\mathbf Y}=\nabla_{\mathbf Y}\ell for the adjoint of Y\mathbf Y—now a matrix of the same shape as Y\mathbf Y holding the total derivative of the loss with respect to each entry of Y\mathbf Y.

Proposition (backward rule of a layer). Let Y=F(X)\mathbf Y=\mathbf F(\mathbf X) be differentiable at X\mathbf X and let ℓ\ell be a differentiable scalar function of Y\mathbf Y. Then the adjoint Xˉ\bar{\mathbf X} of the composite ℓ(F(X))\ell(\mathbf F(\mathbf X)) is the unique matrix satisfying

⟨Xˉ, dX⟩=⟨Yˉ, dY⟩for every dX,\langle\bar{\mathbf X},\ d\mathbf X\rangle=\langle\bar{\mathbf Y},\ d\mathbf Y\rangle \quad\textit{for every } d\mathbf X,

where dYd\mathbf Y is the first-order change of F\mathbf F caused by dXd\mathbf X.

Proof. By the chain rule (22.4.5) (viewing matrices as flattened vectors), the linear part of the composite is the linear part of ℓ\ell applied to the linear part of F\mathbf F: dℓ=⟨Yˉ,dY⟩d\ell=\langle\bar{\mathbf Y},d\mathbf Y\rangle. Because dYd\mathbf Y is linear in dXd\mathbf X, so is dℓd\ell, which means it can be written as ⟨M,dX⟩\langle\mathbf M,d\mathbf X\rangle for a unique matrix M\mathbf M. By (22.4.7), M=Xˉ\mathbf M=\bar{\mathbf X}. ■\blacksquare

In practice, applying this proposition comes down to applying the move rule. For a vector layer with dy=J dxd\mathbf y=\mathbf J\,d\mathbf x, it gives ⟨yˉ,J dx⟩=⟨J⊤yˉ,dx⟩\langle\bar{\mathbf y},\mathbf J\,d\mathbf x\rangle=\langle\mathbf J^\top\bar{\mathbf y},d\mathbf x\rangle, so xˉ=J⊤yˉ\bar{\mathbf x}=\mathbf J^\top\bar{\mathbf y}: the backward rule of a layer is simply the transpose of its linearization. The transpose of a linear map is also called its adjoint, which is where the name comes from. Written as xˉ⊤=yˉ⊤J\bar{\mathbf x}^\top=\bar{\mathbf y}^\top\mathbf J, this is just one step of the left-to-right order in (22.4.6). A row vector times a Jacobian is called a vector–Jacobian product. The proposition lets us compute it for matrix variables without ever forming the Jacobian.

The single most frequent derivative in deep learning is that of a matrix product. Depending on whether we process a minibatch or a single vector, the weights stand on the right or the left of the data, so let us derive both layouts together. A minibatch X∈Rn×d\mathbf X\in\mathbb R^{n\times d} with one example per row (the convention throughout the main text) multiplies the weight matrix W∈Rd×q\mathbf W\in\mathbb R^{d\times q} to produce Y=XW\mathbf Y=\mathbf X\mathbf W. The product rule gives dY=dX W+X dWd\mathbf Y=d\mathbf X\,\mathbf W+\mathbf X\,d\mathbf W, and the move rule splits the inner product into one term per variable: ⟨Yˉ,dX W⟩+⟨Yˉ,X dW⟩=⟨YˉW⊤,dX⟩+⟨X⊤Yˉ,dW⟩\langle\bar{\mathbf Y},d\mathbf X\,\mathbf W\rangle+\langle\bar{\mathbf Y},\mathbf X\,d\mathbf W\rangle =\langle\bar{\mathbf Y}\mathbf W^\top,d\mathbf X\rangle+\langle\mathbf X^\top\bar{\mathbf Y},d\mathbf W\rangle. Reading off both coefficients gives

Xˉ=Yˉ W⊤,Wˉ=X⊤Yˉ.(22.4.9)\bar{\mathbf X}=\bar{\mathbf Y}\,\mathbf W^\top,\qquad \bar{\mathbf W}=\mathbf X^\top\bar{\mathbf Y}. \tag{22.4.9}

For a single example written as a column vector, y=Wx\mathbf y=\mathbf W\mathbf x, the exact same calculation yields

Wˉ=yˉ x⊤,xˉ=W⊤yˉ,\bar{\mathbf W}=\bar{\mathbf y}\,\mathbf x^\top,\qquad \bar{\mathbf x}=\mathbf W^\top\bar{\mathbf y},

matching the pattern of (22.4.8): the weight gradient is the outer product of the output adjoint with the input. The two layouts are simply transposes of each other. If xi⊤\mathbf x_i^\top and yˉi⊤\bar{\mathbf y}_i^\top are the rows of X\mathbf X and Yˉ\bar{\mathbf Y}, the minibatch formula X⊤Yˉ=∑ixiyˉi⊤\mathbf X^\top\bar{\mathbf Y}=\sum_i\mathbf x_i\bar{\mathbf y}_i^\top sums one such outer product per example.

The backward pass of a linear layer therefore consists of two matrix products, each the same size as the forward product: the forward pass costs ndqndq multiplications and the backward pass costs 2ndq2ndq. Checking shapes confirms both transposes: YˉW⊤\bar{\mathbf Y}\mathbf W^\top is n×dn\times d like X\mathbf X, and X⊤Yˉ\mathbf X^\top\bar{\mathbf Y} is d×qd\times q like W\mathbf W. Backward rules for more elaborate matrix operations (inverses, determinants, and decompositions) follow from the very same method (Giles, 2008).

Two more layers complete a multilayer perceptron. An elementwise activation Y=φ(X)\mathbf Y=\boldsymbol\varphi(\mathbf X) has dY=φ′(X)⊙dXd\mathbf Y=\varphi'(\mathbf X)\odot d\mathbf X, so moving φ′(X)\varphi'(\mathbf X) across the inner product gives Xˉ=φ′(X)⊙Yˉ\bar{\mathbf X}=\varphi'(\mathbf X)\odot\bar{\mathbf Y}—the diagonal Jacobian from earlier, applied directly as a mask. A bias addition y=z+b\mathbf y=\mathbf z+\mathbf b has dy=dbd\mathbf y=d\mathbf b, so bˉ=yˉ\bar{\mathbf b}=\bar{\mathbf y}. For a minibatch, the bias is broadcast across rows via Z=XW+1b⊤\mathbf Z=\mathbf X\mathbf W+\mathbf 1\mathbf b^\top, which is just another matrix product and gives bˉ=Zˉ⊤1\bar{\mathbf b}=\bar{\mathbf Z}^\top\mathbf 1, summing the adjoint over all examples. These three local rules are the building blocks from which Section 4.3 assembles the full backward pass of a multilayer perceptron.

They also let us derive the weight-gradient matrix from the opening. Running the network of Figure 22.4.2 backward from gˉ=1\bar g=1, one layer at a time, at x=(1,1)\mathbf x=(1,1):

  1. The output g=w2⊤hg=\mathbf w_2^\top\mathbf h gives hˉ=w2=(2,−1)\bar{\mathbf h}=\mathbf w_2=(2,-1) and wˉ2=h=(3,0)\bar{\mathbf w}_2=\mathbf h=(3,0).
  2. The ReLU gives aˉ=m⊙hˉ=(2,0)\bar{\mathbf a}=\mathbf m\odot\bar{\mathbf h}=(2,0), and the bias gives bˉ=aˉ=(2,0)\bar{\mathbf b}=\bar{\mathbf a}=(2,0).
  3. The affine map a=W1x+b\mathbf a=\mathbf W_1\mathbf x+\mathbf b gives Wˉ1=aˉ x⊤=(2200)\bar{\mathbf W}_1=\bar{\mathbf a}\,\mathbf x^\top=\left(\begin{smallmatrix}2&2\\0&0\end{smallmatrix}\right) and xˉ=W1⊤aˉ=(2,4)\bar{\mathbf x}=\mathbf W_1^\top\bar{\mathbf a}=(2,4).

Notice that xˉ\bar{\mathbf x} is the transpose of the Jacobian row (2,4)(2,4) we found earlier, and Wˉ1\bar{\mathbf W}_1 is the matrix we obtained in the opening by nudging the weights. Differentiating g with respect to W1\mathbf W_1, b\mathbf b, and w2\mathbf w_2 in code confirms all three arrays.

gW1, gb, gw2 = torch.func.grad(g, argnums=(1, 2, 3))(x, W1, b, w2)
h = torch.relu(W1 @ x + b)
show = lambda t: (t.numpy() + 0.0).tolist()     # + 0.0 turns -0.0 into 0.0
print('dg/dW1 = (w2*m) x^T:', show(torch.outer(w2 * m, x)),
      '  autograd:', show(gW1))
print('dg/db  = w2*m      :', show(w2 * m), '  autograd:', show(gb))
print('dg/dw2 = h         :', show(h), '  autograd:', show(gw2))
dg/dW1 = (w2*m) x^T: [[2.0, 2.0], [0.0, 0.0]]   autograd: [[2.0, 2.0], [0.0, 0.0]]
dg/db  = w2*m      : [2.0, 0.0]   autograd: [2.0, 0.0]
dg/dw2 = h         : [3.0, 0.0]   autograd: [3.0, 0.0]

It is worth noting where the zeros land. The inactive hidden unit leaves three zeros behind: a zero row in Wˉ1\bar{\mathbf W}_1, a zero in bˉ\bar{\mathbf b}, and a zero in wˉ2\bar{\mathbf w}_2 (because its output h2=0h_2=0 is what w2,2w_{2,2} multiplies). A training step on this input leaves all four of that unit's parameters untouched.

We still owe the numerical test that catches a misplaced transpose on a square factor. A test that cannot fail proves nothing, so we design this one to expose the mistake: every factor below is a random square (and hence nonsymmetric) matrix, and we print each correct rule beside a plausible wrong guess of the same shape. We test both the quadratic form and the matrix product. For the product, we differentiate the scalar ⟨Yˉ,XW⟩\langle\bar{\mathbf Y},\mathbf X\mathbf W\rangle for a random Yˉ\bar{\mathbf Y}; by our backward-rule proposition, its gradients with respect to X\mathbf X and W\mathbf W are precisely Xˉ\bar{\mathbf X} and Wˉ\bar{\mathbf W}.

A, x = torch.tensor(np.random.randn(3, 3)), torch.tensor(np.random.randn(3))
X, W, Ybar = (torch.tensor(np.random.randn(3, 3)) for _ in range(3))  # square
ok = lambda u, v: torch.allclose(u, v, atol=1e-5)
grad = torch.func.grad
gx = grad(lambda x: x @ A @ x)(x)
gX, gW = grad(lambda X, W: (Ybar * (X @ W)).sum(), argnums=(0, 1))(X, W)
print('grad x^T A x: (A + A^T) x', ok(gx, (A + A.T) @ x),
      '| wrong guess 2 A x       ', ok(gx, 2 * A @ x))
print('Xbar        : Ybar W^T   ', ok(gX, Ybar @ W.T),
      '| wrong guess Ybar W      ', ok(gX, Ybar @ W))
print('Wbar        : X^T Ybar   ', ok(gW, X.T @ Ybar),
      '| wrong guess (X^T Ybar)^T', ok(gW, (X.T @ Ybar).T))
grad x^T A x: (A + A^T) x True | wrong guess 2 A x        False
Xbar        : Ybar W^T    True | wrong guess Ybar W       False
Wbar        : X^T Ybar    True | wrong guess (X^T Ybar)^T False

The derived rules print True and the wrong guesses print False. Here the design of the test matters even more than its outcome. With rectangular factors, say X\mathbf X of shape 3×43\times4 and W\mathbf W of shape 4×24\times2, the two wrong guesses for the product would not even execute: a misplaced transpose would trigger a shape error before any number is compared, which is the shape rule doing its job. Likewise, with a symmetric A\mathbf A, the wrong guess 2Ax2\mathbf A\mathbf x would have matched the true gradient and slipped past the test. The treacherous case is a square, nonsymmetric factor, so that is what a numerical check must draw.

The matrix-product rule handles losses in which both factors of a product are unknown just as easily, such as the matrix-factorization loss ∥X−UV∥F2\|\mathbf X-\mathbf U\mathbf V\|_F^2 in exercise 3. In every case, the backward rule multiplies the incoming adjoint by the transposes of whatever multiplied the variable on the forward pass. Notice also which forward values each rule requires: X\mathbf X and W\mathbf W for the matrix product, φ′(X)\varphi'(\mathbf X) for the activation, and nothing at all for the bias. A backward pass must retain those intermediate values from the forward pass, a memory cost that Section 22.5 measures directly.

22.4.3.3 Softmax and Cross-Entropy#

The derivative a classifier evaluates most often is that of softmax composed with cross-entropy loss. Softmax converts a vector of scores z\mathbf z, the logits, into a probability vector: setting S=∑kezkS=\sum_k e^{z_k}, we have pi=ezi/Sp_i=e^{z_i}/S. The same quotient rule that gave the log-sum-exp Hessian in Section 22.2 for two logits yields the softmax Jacobian for any number of classes. Writing δij=1\delta_{ij}=1 if i=ji=j and 00 otherwise,

∂pi∂zj=δijeziS−eziezjS2=pi(δij−pj),Jsoftmax⁡=diag⁡(p)−pp⊤.(22.4.10)\frac{\partial p_i}{\partial z_j} =\frac{\delta_{ij}e^{z_i}S-e^{z_i}e^{z_j}}{S^2} =p_i(\delta_{ij}-p_j), \qquad \mathbf J_{\operatorname{softmax}} = \operatorname{diag}(\mathbf p) - \mathbf p\mathbf p^\top. \tag{22.4.10}

In words, increasing logit ii raises pip_i at rate pi(1−pi)p_i(1-p_i) and lowers every other probability pjp_j at rate pipjp_ip_j. As a quick check, J1=p−p(p⊤1)=0\mathbf J\mathbf 1=\mathbf p-\mathbf p(\mathbf p^\top\mathbf 1)=\mathbf 0 because the probabilities sum to one. This must hold, since adding the same constant to every logit leaves p\mathbf p unchanged; consequently, the softmax Jacobian is always singular.

Notice that Jsoftmax⁡\mathbf J_{\operatorname{softmax}} is also symmetric, a property an arbitrary Jacobian need not have. The reason is that it is actually a Hessian: softmax is the gradient of the log-sum-exp function LSE⁡(z)=log⁡∑kezk\operatorname{LSE}(\mathbf z)=\log\sum_k e^{z_k}, our chapter's running example, because ∂LSE⁡/∂zi=ezi/S=pi\partial\operatorname{LSE}/\partial z_i=e^{z_i}/S=p_i, and the Jacobian of a gradient is its Hessian. What (22.4.10) adds to that two-logit formula is a clean statistical reading of the matrix. It is the covariance matrix of a one-hot vector drawn with probabilities p\mathbf p, so for every z\mathbf z and every vector v\mathbf v the quadratic form v⊤Jv=∑ipivi2−(∑ipivi)2\mathbf v^\top\mathbf J\mathbf v=\sum_ip_iv_i^2-\bigl(\sum_ip_iv_i\bigr)^2 is the variance of the entries of v\mathbf v under the distribution p\mathbf p. Because a variance is never negative, this Hessian is positive semidefinite everywhere, proving that log-sum-exp is convex. A constant vector v\mathbf v has zero variance, recovering the null vector 1\mathbf 1 once again.

Now compose softmax with the cross-entropy loss ℓ=−∑iyilog⁡pi\ell=-\sum_i y_i\log p_i against a target distribution y\mathbf y. The chain rule multiplies the row ∂ℓ/∂p=(−yi/pi)i\partial\ell/\partial\mathbf p=(-y_i/p_i)_i by (22.4.10), and the algebra collapses dramatically:

∂ℓ∂zj=−∑iyipi pi(δij−pj)=−yj+pj∑iyi=pj−yj,that is,∇zℓ=p−y.(22.4.11)\frac{\partial\ell}{\partial z_j} = -\sum_i \frac{y_i}{p_i}\,p_i(\delta_{ij}-p_j) = -y_j + p_j\sum_i y_i = p_j - y_j, \qquad\text{that is,}\qquad \nabla_{\mathbf z}\ell=\mathbf p-\mathbf y. \tag{22.4.11}

The gradient with respect to the logits is simply predicted probability minus target, the formula written as y^−y\hat{\mathbf y}-\mathbf y in Section 3.1.2.2. Because the final step used only ∑iyi=1\sum_iy_i=1, the result holds for any probability vector y\mathbf y, not just one-hot labels—so label smoothing and distillation targets obey the exact same formula. For a target that does not sum to one, the gradient is instead (∑iyi) p−y(\sum_iy_i)\,\mathbf p-\mathbf y. At z=(1,−0.5,2)\mathbf z=(1,-0.5,2), for example, we have p=(0.254, 0.057, 0.690)\mathbf p=(0.254,\ 0.057,\ 0.690); with the second class as the target, the gradient is (0.254, −0.943, 0.690)(0.254,\ -0.943,\ 0.690).

In practice, libraries fuse softmax and cross-entropy into a single primitive for numerical stability (Section 3.3.5.2, Section 23.8.2). Below, we compute the softmax Jacobian at z\mathbf z by automatic differentiation and print its eigenvalues, which our variance argument predicts must be nonnegative with one zero. We then differentiate the fused loss for both the one-hot target above and the two-hot target y=(1,1,0)\mathbf y=(1,1,0), whose entries do not sum to one.

z = torch.tensor([1.0, -0.5, 2.0])
p = torch.softmax(z, 0)
J = torch.func.jacrev(lambda z: torch.softmax(z, 0))(z)   # the Jacobian, by autograd
print('eigenvalues of J:', torch.linalg.eigvalsh(J).numpy().round(3) + 0.0)
loss = lambda z, y: -(y * torch.log_softmax(z, 0)).sum()
for y in [torch.tensor([0.0, 1.0, 0.0]), torch.tensor([1.0, 1.0, 0.0])]:
    print(f'y = {y.numpy()}: d loss / d z = {torch.func.grad(loss)(z, y).numpy().round(4)}, '
          f'p - y = {(p - y).numpy().round(4)}')
eigenvalues of J: [0.    0.079 0.378]
y = [0. 1. 0.]: d loss / d z = [ 0.2537 -0.9434  0.6897], p - y = [ 0.2537 -0.9434  0.6897]
y = [1. 1. 0.]: d loss / d z = [-0.4926 -0.8868  1.3793], p - y = [-0.7463 -0.9434  0.6897]

The eigenvalues are 00, 0.0790.079, and 0.3780.378: one zero, corresponding to the direction 1\mathbf 1, and two positive values. For the one-hot target, the gradient of the fused loss is p−y=(0.2537,−0.9434,0.6897)\mathbf p-\mathbf y=(0.2537,-0.9434,0.6897), matching our hand calculation. For the two-hot target, however, it returns (−0.4926,−0.8868,1.3793)(-0.4926,-0.8868,1.3793), which is 2p−y2\mathbf p-\mathbf y rather than the p−y\mathbf p-\mathbf y printed beside it. "Prediction minus target" is a property of targets that sum to one, not of the loss alone.

Here we multiplied JK⋯J1\mathbf J_K\cdots\mathbf J_1 by hand for a simple three-layer chain. In practice, a program must handle arbitrary computation graphs that branch and merge, retain the forward values that each backward rule needs, and compute all gradients at a cost that stays a small constant multiple of evaluating the network, no matter how many parameters it has. That program is automatic differentiation, the subject of Section 22.5.

22.4.4 Summary#

The Jacobian of a map f:Rn→Rm\mathbf f:\mathbb R^n\to\mathbb R^m is the m×nm\times n matrix of its best linear approximation, with entries [Jf]ij=∂fi/∂xj[\mathbf J_{\mathbf f}]_{ij}=\partial f_i/\partial x_j; both the gradient (a single row, written as a column) and the Hessian (the Jacobian of the gradient) are special cases of it. A network's derivative with respect to its input is the product of its layers' Jacobians, JK⋯J1\mathbf J_K\cdots\mathbf J_1, and the order of multiplication governs the cost: three million versus two billion multiplications for three layers of width 10001000. The differential rule df=⟨∇f,dx⟩df=\langle\nabla f,d\mathbf x\rangle derives every gradient a layer needs automatically in the shape of its variable, including the matrix-product backward rules Xˉ=YˉW⊤\bar{\mathbf X}=\bar{\mathbf Y}\mathbf W^\top and Wˉ=X⊤Yˉ\bar{\mathbf W}=\mathbf X^\top\bar{\mathbf Y}, as well as the collapse of softmax with cross-entropy to p−y\mathbf p-\mathbf y. While the shape rule and the 1×11\times1 check catch most slips in a hand derivation, a misplaced transpose on a square factor escapes both and requires a numerical test on a nonsymmetric matrix.

22.4.5 Exercises#

  1. Jacobian of a ReLU network. Let g(x)=W2 φ(W1x+b)\mathbf g(\mathbf x)=\mathbf W_2\,\boldsymbol\varphi(\mathbf W_1\mathbf x+\mathbf b) with W1∈Rh×n\mathbf W_1\in\mathbb R^{h\times n}, b∈Rh\mathbf b\in\mathbb R^h, W2∈Rm×h\mathbf W_2\in\mathbb R^{m\times h}, and the elementwise ReLU φ\boldsymbol\varphi. Assume that no entry of the pre-activation W1x+b\mathbf W_1\mathbf x+\mathbf b is zero. By (22.4.5), Jg(x)=W2M(x)W1\mathbf J_{\mathbf g}(\mathbf x)=\mathbf W_2\mathbf M(\mathbf x)\mathbf W_1, where the diagonal matrix M(x)\mathbf M(\mathbf x) has the entry 11 for each active hidden unit and 00 for each inactive one.

    1. Show that g(x+δ)=g(x)+Jg(x) δ\mathbf g(\mathbf x+\boldsymbol\delta)=\mathbf g(\mathbf x)+\mathbf J_{\mathbf g}(\mathbf x)\,\boldsymbol\delta holds exactly for every sufficiently small δ\boldsymbol\delta, so that the remainder in (22.4.1) vanishes identically. For the 2-2-1 network of this section at x=(1,1)\mathbf x=(1,1), find the largest rr such that this holds for all δ\boldsymbol\delta with ∥δ∥∞<r\|\boldsymbol\delta\|_\infty\lt r. For n=m=2n=m=2, how does the image of a small circle under g\mathbf g differ from the one in Figure 22.4.1?
    2. Let kk hidden units be active at x\mathbf x. Show that rank⁡Jg(x)≤k\operatorname{rank}\mathbf J_{\mathbf g}(\mathbf x)\le k. For n=m=2n=m=2 and k=1k=1, what is the image of a small circle around x\mathbf x?
    3. Describe the set of inputs at which some pre-activation is zero. What happens to Jg\mathbf J_{\mathbf g} when x\mathbf x crosses this set?
  2. [code] Cheapest chain order. ● By (22.4.6) the Jacobian of a chain of KK maps is JK⋯J1\mathbf J_K\cdots\mathbf J_1 with Jk∈Rdk×dk−1\mathbf J_k\in\mathbb R^{d_k\times d_{k-1}}. Multiplying a p×qp\times q matrix by a q×rq\times r matrix costs pqrpqr multiplications.

    1. Give the costs of the forward order, which multiplies from the right, and of the reverse order, which multiplies from the left, as functions of d0,…,dKd_0,\ldots,d_K. Evaluate both for (d0,…,d4)=(1000,10,1000,10,1000)(d_0,\ldots,d_4)=(1000,10,1000,10,1000), a map whose layers alternate between wide and narrow, and compare with the section's count for (1×h)(h×h)(h×h)(h×n)(1\times h)(h\times h)(h\times h)(h\times n).
    2. Write a dynamic program over the sub-chains Jj⋯Ji\mathbf J_j\cdots\mathbf J_i that finds the cheapest parenthesization, and run it on the dimensions of (a). Which order does it choose, and how much cheaper is it than the better of the two orders of (a)?
    3. For a scalar output, dK=1d_K=1, compare the optimum with the reverse order on a few thousand random dimension vectors, with KK between 22 and 66 and each of d0,…,dK−1d_0,\ldots,d_{K-1} drawn uniformly from {1,…,10}\{1,\ldots,10\}. Characterize the vectors for which some other order is cheaper.
  1. [code] Backward rules of a matrix product.
    1. For Y=XW\mathbf Y=\mathbf X\mathbf W, derive (22.4.9) by the differential method, then derive it again by indices to confirm the transposes.
    2. Verify both rules with the vector–Jacobian product torch.func.vjp on X∈R3×4\mathbf X\in\mathbb R^{3\times4}, W∈R4×2\mathbf W\in\mathbb R^{4\times2} and a random adjoint Yˉ\bar{\mathbf Y}. Count the multiplications of the forward product and of the two backward products.
    3. For the factorization loss ∥X−UV∥F2\|\mathbf X-\mathbf U\mathbf V\|_F^2 with R=X−UV\mathbf R=\mathbf X-\mathbf U\mathbf V, check ∇U=−2RV⊤\nabla_{\mathbf U}=-2\mathbf R\mathbf V^\top and ∇V=−2U⊤R\nabla_{\mathbf V}=-2\mathbf U^\top\mathbf R numerically. Then write the alternating least-squares step that sets one gradient to zero with the other factor fixed, and show that each step is one linear solve.
  1. Softmax vector–Jacobian product. A backward pass never forms the softmax Jacobian (22.4.10). It maps the adjoint u=pˉ\mathbf u=\bar{\mathbf p} of the probabilities to the adjoint zˉ=Jsoftmax⁡⊤u\bar{\mathbf z}=\mathbf J_{\operatorname{softmax}}^\top\mathbf u of the logits.

    1. Show that Jsoftmax⁡⊤u=p⊙(u−(p⊤u) 1)\mathbf J_{\operatorname{softmax}}^\top\mathbf u=\mathbf p\odot\bigl(\mathbf u-(\mathbf p^\top\mathbf u)\,\mathbf 1\bigr), where ⊙\odot is the elementwise product. For nn classes, count the operations of this formula and those of forming Jsoftmax⁡\mathbf J_{\operatorname{softmax}} and multiplying it by u\mathbf u.
    2. Self-attention applies softmax to each row of an n×nn\times n score matrix S\mathbf S and produces the weights P\mathbf P. How many entries does the Jacobian of P\mathbf P with respect to S\mathbf S have, and how many of them can be nonzero? For n=4096n=4096 tokens in float32, compare the memory of the full Jacobian, of its nonzero entries, and of the adjoint of S\mathbf S that the formula of (a), applied row by row, returns.
  2. [code] The LayerNorm Jacobian. Layer normalization (Ba et al., 2016) maps x∈Rn\mathbf x\in\mathbb R^n to x^=(x−μ1)/σ\hat{\mathbf x}=(\mathbf x-\mu\mathbf 1)/\sigma with μ=1n∑ixi\mu=\frac1n\sum_ix_i and σ2=1n∑i(xi−μ)2>0\sigma^2=\frac1n\sum_i(x_i-\mu)^2>0 (no learned scale and no ϵ\epsilon).

    1. Show by the differential method that J=1σ(I−1n11⊤−1nx^x^⊤)\mathbf J=\frac1\sigma\bigl(\mathbf I-\frac1n\mathbf 1\mathbf 1^\top-\frac1n\hat{\mathbf x}\hat{\mathbf x}^\top\bigr). Hint: dμ=1n1⊤dxd\mu=\frac1n\mathbf 1^\top d\mathbf x and dσ=1nx^⊤dxd\sigma=\frac1n\hat{\mathbf x}^\top d\mathbf x.
    2. Show that 1\mathbf 1 and x^\hat{\mathbf x} are orthogonal and that ∥x^∥2=n\|\hat{\mathbf x}\|^2=n. Conclude that σJ\sigma\mathbf J is the orthogonal projection onto the complement of span⁡{1,x^}\operatorname{span}\{\mathbf 1,\hat{\mathbf x}\} and that rank⁡J=n−2\operatorname{rank}\mathbf J=n-2 for n≥2n\ge2. Which two changes of the input can LayerNorm not see, and why?
    3. Check (a) and the two null vectors against the Jacobian computed by automatic differentiation for a random x∈R5\mathbf x\in\mathbb R^5, and print the eigenvalues of J\mathbf J.
  3. Log-determinant gradient. ● A normalizing flow (Rezende and Mohamed, 2015) passes a random vector X\mathbf X through invertible layers. For one layer Y=g(X)\mathbf Y=\mathbf g(\mathbf X), the log-density of Y\mathbf Y at g(x)\mathbf g(\mathbf x) is log⁡pX(x)−log⁡∣det⁡Jg(x)∣\log p_{\mathbf X}(\mathbf x)-\log|\det\mathbf J_{\mathbf g}(\mathbf x)|, by the change-of-variables formula for densities. For a linear layer x↦Ax\mathbf x\mapsto\mathbf A\mathbf x the correction is −log⁡∣det⁡A∣-\log|\det\mathbf A|, so maximum-likelihood training differentiates log⁡∣det⁡A∣\log|\det\mathbf A| with respect to A\mathbf A.

    1. Expand det⁡(I+tM)\det(\mathbf I+t\mathbf M) to first order in tt and use det⁡(A+dA)=det⁡A det⁡(I+A−1dA)\det(\mathbf A+d\mathbf A)=\det\mathbf A\,\det(\mathbf I+\mathbf A^{-1}d\mathbf A) to derive Jacobi's formula ddet⁡A=det⁡A tr⁡(A−1dA)d\det\mathbf A=\det\mathbf A\,\operatorname{tr}(\mathbf A^{-1}d\mathbf A) for invertible A\mathbf A. Conclude with (22.4.7) that ∇Alog⁡∣det⁡A∣=A−⊤\nabla_{\mathbf A}\log|\det\mathbf A|=\mathbf A^{-\top}. Why does the sign of det⁡A\det\mathbf A not matter?
    2. Check the identity on a random invertible 3×33\times3 matrix by central differences of np.linalg.slogdet.
    3. How does the norm of the gradient behave as A\mathbf A approaches a singular matrix? What does this imply for a flow layer whose weight matrix is nearly singular?
  4. Gradient of the spectral norm. ● Spectral normalization (Miyato et al., 2018) divides each weight matrix W\mathbf W of a network by its largest singular value σ1(W)\sigma_1(\mathbf W), so training differentiates σ1\sigma_1.

    1. Let S\mathbf S be a real symmetric matrix with a simple eigenvalue λ\lambda and unit eigenvector q\mathbf q, and perturb it to S+tE\mathbf S+t\mathbf E with E\mathbf E symmetric. Take as given that λ(t)\lambda(t) and q(t)\mathbf q(t), defined by (S+tE)q=λq(\mathbf S+t\mathbf E)\mathbf q=\lambda\mathbf q and q⊤q=1\mathbf q^\top\mathbf q=1, are differentiable near t=0t=0 (the implicit function theorem gives this because λ\lambda is simple). Differentiate both equations at t=0t=0 to show the Hellmann--Feynman theorem λ′(0)=q⊤E q\lambda'(0)=\mathbf q^\top\mathbf E\,\mathbf q, and give ∇Sλ\nabla_{\mathbf S}\lambda for the inner product tr⁡(A⊤B)\operatorname{tr}(\mathbf A^\top\mathbf B).
    2. Apply (a) to σ1(W)2=λmax⁡(W⊤W)\sigma_1(\mathbf W)^2=\lambda_{\max}(\mathbf W^\top\mathbf W) to show that ∇Wσ1=u1v1⊤\nabla_{\mathbf W}\sigma_1=\mathbf u_1\mathbf v_1^\top when σ1>0\sigma_1>0 is simple, where u1\mathbf u_1 and v1\mathbf v_1 are the top left and right singular vectors. Why is σ1>0\sigma_1>0 needed? Consider W=w∈Rn×1\mathbf W=\mathbf w\in\mathbb R^{n\times1} near w=0\mathbf w=\mathbf 0. Check the formula by central differences on a random 5×35\times3 matrix in NumPy.
    3. Compute σ1(I+tdiag⁡(1,−1))\sigma_1(\mathbf I+t\operatorname{diag}(1,-1)) for small tt of both signs. Is σ1\sigma_1 differentiable at the 2×22\times2 identity, and which hypothesis of (a) fails there?

    Adapted from Alan Edelman and Steven G. Johnson, Matrix Calculus for Machine Learning and Beyond, problem set 2, MIT 18.S096, IAP 2023, Problem 3.

Discussions