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,
where applies to each entry. At the pre-activations are , so the second hidden unit is off, the hidden vector is , and the output is . A training step raises three questions about this output. First, if the input moves by a small , the output changes by , a row of two numbers that is the transpose of the column gradient. Second, if the weight matrix moves by , the output changes by and not at all through the second row, so the derivative with respect to a matrix is itself a matrix, . Third, the hidden layer maps a vector to a vector. Neither a scalar slope nor a gradient vector describes its derivative, yet the output depends on 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 , 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 torch22.4.1 The Jacobian#
22.4.1.1 The Best Linear Approximation#
Near 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:
At , the map evaluates to . Each of the two outputs has two partial derivatives: , , , and . We arrange these four numbers in a matrix with one row per output and one column per input,
Column records how both outputs respond when input moves. This matrix is the derivative of at , in the sense that for small , and no other matrix approximates as closely.
In one variable, the derivative is the slope of the best straight-line fit, . The vector-valued generalization rests on the same local approximation. We say that is differentiable at if there is a matrix such that
meaning that the error of the linear model divided by tends to zero as . Whenever such a matrix exists, it is unique. We call it the Jacobian , and its entries are simply the partial derivatives:
To see why, substitute the perturbation (a small step along coordinate axis ) into (22.4.1) and look at component . Dividing by and letting leaves in the slot, regardless of which matrix we started with. The partial derivatives therefore supply the entries of , while the linear approximation is what defines it.
The existence of partial derivatives alone does not guarantee differentiability. Consider the function with from Section 22.2.1.2: both partials are at the origin, yet equals everywhere along the diagonal . The only candidate Jacobian is the zero row vector, whose approximation error along the diagonal remains no matter how small is, so has no Jacobian at the origin. Continuity of the partial derivatives is sufficient to rule out such behavior: if every partial exists in a neighborhood of and is continuous at , then is differentiable at (Rudin, 1976).
Figure 22.4.1 illustrates the definition geometrically: near , the map acts like its Jacobian. A circle of radius around maps nearly onto the ellipse (), whose semi-axes are times the singular values of (as shown in Section 21.5, any matrix maps the unit circle to an ellipse with these semi-axes). Here the singular values are and , so the circle of radius becomes an ellipse with semi-axes and . The largest gap between the true image and the ellipse is at and at : halving the radius cuts the gap fourfold.
A differentiable map is locally its Jacobian. Two circles of radius and around (left) and their images under (right, blue) against the ellipses (orange, dashed). The semi-axes of each ellipse are the radius times the singular values and of . Halving the radius cuts the largest gap between image and ellipse from to , the remainder.
The definition guarantees that the error of the linear model divided by 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 to , , and . It tends to zero, confirming the remainder in the definition. Notice that it also falls tenfold for every tenfold reduction in , which means the error itself falls a hundredfold and is . The definition promises only the first property; the faster quadratic decay holds because 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 (), the Jacobian is a single row, , and (22.4.1) becomes the first-order expansion . In Section 22.2 we wrote the gradient as a column vector. The two are simply transposes of each other,
and we use both in this book, each for its own purpose. Jacobians of vector-valued maps are , with one row per output, so that the chain rule below composes cleanly without transposes. Gradients of scalars are column vectors, , matching the shape of so an optimizer can subtract them directly. For our opening network, is a Jacobian, while is the column gradient.
A scalar function of a matrix needs one more convention. We define its gradient as the matrix with entries , matching the shape of . The first-order expansion then reads
where the inner product 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 is the sum over all entries of "sensitivity times nudge". In our opening example, is the matrix , and 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 is itself a vector-valued map, and its Jacobian is the matrix of second partials, the Hessian , whose entries are . Strictly speaking, takes the two derivatives in the opposite order, but the two agree, and 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 is differentiable at and is differentiable at , then is differentiable at and
Proof. Write , , and . The idea is simply to substitute the linear model for into the linear model for . By (22.4.1), . Calling that displacement and passing it to gives
The second equality relies on two facts. First, multiplying an remainder by the fixed matrix leaves it . Second, because is bounded by a constant multiple of , the remainder from is also ; this is the one step that is not purely algebraic. The coefficient of is therefore a matrix satisfying (22.4.1), and by uniqueness it is the Jacobian of the composite: .
Looking at a single entry of the product recovers the scalar sum over paths: sums, over all intermediate variables , the product of derivatives along each path from to .
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 , the ReLU activation , and the linear output . The first map is already affine, so its Jacobian is ; the bias shifts the value without changing the slope. The ReLU acts on each entry independently, with slope where and where , so its Jacobian is the diagonal matrix formed from the mask of these slopes. Finally, the output map has Jacobian . At , where and , the chain rule multiplies the three factors:
The mask zeroes out the second entry of , so the second row of never reaches the output: the weights of an inactive unit contribute nothing to the derivative (Figure 22.4.2). The resulting row matches the change from the opening. At a different input, the mask changes and so does the Jacobian. For instance, at the pre-activations are , the mask flips to , and . 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).
The Jacobian of the 2-2-1 ReLU network at is the product of three matrices. The second unit's pre-activation is , so its mask entry is and the second row of never reaches the output: .
Every multilayer perceptron is built from the same two kinds of factors. A dense layer has Jacobian . An elementwise activation does not couple distinct coordinates, so its Jacobian is diagonal: . This assumes that is differentiable at every ; ReLU has no derivative at , where frameworks supply a fixed value by convention (Section 22.1.6). A network of depth is a composition , and iterating (22.4.5) turns its derivative into a single product,
with each factor evaluated at the input of its own layer. For alternating dense layers and activations, this becomes : weight matrices interleaved with diagonal matrices. Because multiplying a vector by a diagonal matrix simply scales each entry, each activation factor costs operations rather than .
Let us now define the 2-2-1 network in code, which we will reuse later in the section, and compare the product 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 , 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 (as in a recurrent network applying one weight matrix at every step, ignoring the activations), the product simplifies to . For a diagonalizable matrix we have , so for large its norm grows or shrinks like , where is the eigenvalue of largest magnitude: , whereas . 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 describes only the long-run rate. When the eigenvectors in 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 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 , so the chain starts on the left with a row vector: the Jacobian of the loss with respect to the last layer's output . 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 with shapes , , , and , taking and recalling that multiplying a matrix by a matrix costs multiplications. From the left, we perform three matrix–vector products for a total of multiplications. From the right, forming and then costs multiplications each, and the final product with adds , totaling . Three million against two billion is a factor of about , or (Figure 22.4.3).
Two orders for with . From the left every intermediate is a row and every step is a matrix–vector product: multiplications. From the right the first two steps are matrix–matrix products of 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 stands at the right end of the chain: it propagates a single input direction forward and yields . 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 for a small perturbation of the variable and for the part of the resulting change in that is linear in —simply the term of (22.4.1) with renamed . By (22.4.1) and (22.4.4), this linear part is an inner product with the gradient,
for both vector variables () and matrix variables. We can read (22.4.7) in two ways. Given the gradient, it tells us how responds to a nudge. Given , it gives a direct recipe for the gradient: compute using the ordinary rules of differentiation, rearrange it into the form , and read off . This reading is unambiguous because a linear function of can be written as for only one : setting to the matrix with a single in position and zeros elsewhere isolates .
Four familiar rules suffice to compute . First, the differential is linear. Second, it obeys the product rule , because expanding differs from only by the second-order term . Third, it commutes with transposition, . Fourth, a scalar function applied entry by entry obeys the scalar chain rule in every entry, , where denotes elementwise multiplication.
To rearrange into the form , we need just one more tool. The move rule shifts a factor standing next to across to the other side of the inner product:
which follows directly from the cyclic property of the trace, : . 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, , since both sides equal .
The two simplest cases take one line each. For a linear form, , so . For a quadratic form, the product rule hits both copies of :
In the second equality we transposed a matrix: is a scalar, so it equals its own transpose . Reading off the coefficient yields , which simplifies to whenever is symmetric.
Writing out indices offers a second route. Entry by entry, the same derivative is , recovering the -th entry of . 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 , in which case the formula must reduce to the familiar scalar rule. Our quadratic-form gradient passes, since . This check reliably catches a wrong coefficient or a missing term, but it is blind to transposes and factor order because 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 and . Then , whose true gradient equals . The naive guess , suggested by the scalar rule , passes the check, has the right shape, and is still wrong.
The differential method handles matrix variables with no extra effort. For the least-squares loss with residual , varying gives , and the move rule shifts to the other side: . Therefore,
a rank-one outer product of the residual with the input, automatically in the shape of . When varies instead, and . 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 is one step in a long computation ending in a scalar loss . Forming its full Jacobian is out of the question: a weight matrix applied to a minibatch of examples produces outputs from weights, so the Jacobian of outputs with respect to weights would have 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 for the adjoint of —now a matrix of the same shape as holding the total derivative of the loss with respect to each entry of .
Proposition (backward rule of a layer). Let be differentiable at and let be a differentiable scalar function of . Then the adjoint of the composite is the unique matrix satisfying
where is the first-order change of caused by .
Proof. By the chain rule (22.4.5) (viewing matrices as flattened vectors), the linear part of the composite is the linear part of applied to the linear part of : . Because is linear in , so is , which means it can be written as for a unique matrix . By (22.4.7), .
In practice, applying this proposition comes down to applying the move rule. For a vector layer with , it gives , so : 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 , 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 with one example per row (the convention throughout the main text) multiplies the weight matrix to produce . The product rule gives , and the move rule splits the inner product into one term per variable: . Reading off both coefficients gives
For a single example written as a column vector, , the exact same calculation yields
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 and are the rows of and , the minibatch formula 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 multiplications and the backward pass costs . Checking shapes confirms both transposes: is like , and is like . 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 has , so moving across the inner product gives —the diagonal Jacobian from earlier, applied directly as a mask. A bias addition has , so . For a minibatch, the bias is broadcast across rows via , which is just another matrix product and gives , 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 , one layer at a time, at :
- The output gives and .
- The ReLU gives , and the bias gives .
- The affine map gives and .
Notice that is the transpose of the Jacobian row we
found earlier, and is the matrix we obtained in the opening
by nudging the weights. Differentiating g with respect to ,
, and 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 , a zero in , and a zero in (because its output is what 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 for a random ; by our backward-rule proposition, its gradients with respect to and are precisely and .
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 of shape and of shape
, 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 ,
the wrong guess 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 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: and for the matrix product, 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 , the logits, into a probability vector: setting , we have . 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 if and otherwise,
In words, increasing logit raises at rate and lowers every other probability at rate . As a quick check, because the probabilities sum to one. This must hold, since adding the same constant to every logit leaves unchanged; consequently, the softmax Jacobian is always singular.
Notice that 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 , our chapter's running example, because , 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 , so for every and every vector the quadratic form is the variance of the entries of under the distribution . Because a variance is never negative, this Hessian is positive semidefinite everywhere, proving that log-sum-exp is convex. A constant vector has zero variance, recovering the null vector once again.
Now compose softmax with the cross-entropy loss against a target distribution . The chain rule multiplies the row by (22.4.10), and the algebra collapses dramatically:
The gradient with respect to the logits is simply predicted probability minus target, the formula written as in Section 3.1.2.2. Because the final step used only , the result holds for any probability vector , 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 . At , for example, we have ; with the second class as the target, the gradient is .
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 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 , 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 , , and : one zero, corresponding to the direction , and two positive values. For the one-hot target, the gradient of the fused loss is , matching our hand calculation. For the two-hot target, however, it returns , which is rather than the printed beside it. "Prediction minus target" is a property of targets that sum to one, not of the loss alone.
Here we multiplied 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 is the matrix of its best linear approximation, with entries ; 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, , and the order of multiplication governs the cost: three million versus two billion multiplications for three layers of width . The differential rule derives every gradient a layer needs automatically in the shape of its variable, including the matrix-product backward rules and , as well as the collapse of softmax with cross-entropy to . While the shape rule and the 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#
-
Jacobian of a ReLU network. Let with , , , and the elementwise ReLU . Assume that no entry of the pre-activation is zero. By (22.4.5), , where the diagonal matrix has the entry for each active hidden unit and for each inactive one.
- Show that holds exactly for every sufficiently small , so that the remainder in (22.4.1) vanishes identically. For the 2-2-1 network of this section at , find the largest such that this holds for all with . For , how does the image of a small circle under differ from the one in Figure 22.4.1?
- Let hidden units be active at . Show that . For and , what is the image of a small circle around ?
- Describe the set of inputs at which some pre-activation is zero. What happens to when crosses this set?
-
[code] Cheapest chain order. ● By (22.4.6) the Jacobian of a chain of maps is with . Multiplying a matrix by a matrix costs multiplications.
- 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 . Evaluate both for , a map whose layers alternate between wide and narrow, and compare with the section's count for .
- Write a dynamic program over the sub-chains 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)?
- For a scalar output, , compare the optimum with the reverse order on a few thousand random dimension vectors, with between and and each of drawn uniformly from . Characterize the vectors for which some other order is cheaper.
- [code] Backward rules of a matrix product.
- For , derive (22.4.9) by the differential method, then derive it again by indices to confirm the transposes.
- Verify both rules with the vector–Jacobian product
torch.func.vjpon , and a random adjoint . Count the multiplications of the forward product and of the two backward products. - For the factorization loss with , check and 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.
-
Softmax vector–Jacobian product. A backward pass never forms the softmax Jacobian (22.4.10). It maps the adjoint of the probabilities to the adjoint of the logits.
- Show that , where is the elementwise product. For classes, count the operations of this formula and those of forming and multiplying it by .
- Self-attention applies softmax to each row of an score matrix and produces the weights . How many entries does the Jacobian of with respect to have, and how many of them can be nonzero? For tokens in float32, compare the memory of the full Jacobian, of its nonzero entries, and of the adjoint of that the formula of (a), applied row by row, returns.
-
[code] The LayerNorm Jacobian. Layer normalization (Ba et al., 2016) maps to with and (no learned scale and no ).
- Show by the differential method that . Hint: and .
- Show that and are orthogonal and that . Conclude that is the orthogonal projection onto the complement of and that for . Which two changes of the input can LayerNorm not see, and why?
- Check (a) and the two null vectors against the Jacobian computed by automatic differentiation for a random , and print the eigenvalues of .
-
Log-determinant gradient. ● A normalizing flow (Rezende and Mohamed, 2015) passes a random vector through invertible layers. For one layer , the log-density of at is , by the change-of-variables formula for densities. For a linear layer the correction is , so maximum-likelihood training differentiates with respect to .
- Expand to first order in and use to derive Jacobi's formula for invertible . Conclude with (22.4.7) that . Why does the sign of not matter?
- Check the identity on a random invertible matrix by
central differences of
np.linalg.slogdet. - How does the norm of the gradient behave as approaches a singular matrix? What does this imply for a flow layer whose weight matrix is nearly singular?
-
Gradient of the spectral norm. ● Spectral normalization (Miyato et al., 2018) divides each weight matrix of a network by its largest singular value , so training differentiates .
- Let be a real symmetric matrix with a simple eigenvalue and unit eigenvector , and perturb it to with symmetric. Take as given that and , defined by and , are differentiable near (the implicit function theorem gives this because is simple). Differentiate both equations at to show the Hellmann--Feynman theorem , and give for the inner product .
- Apply (a) to to show that when is simple, where and are the top left and right singular vectors. Why is needed? Consider near . Check the formula by central differences on a random matrix in NumPy.
- Compute for small of both signs. Is differentiable at the 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.