Every layer of a network is a matrix product, and training needs the gradient of the loss with respect to every weight matrix and bias vector. Matrix calculus is the short list of rules that gives each of these gradients in one line, plus a shape check that catches many mistakes.
State this site's layout (the gradient of a scalar has the shape of the variable, and a Jacobian is m×n), say that books differ, and use the shape check on any gradient
Derive a matrix gradient by nudging the variable, expanding, and keeping the part that is linear in the nudge, then verify it with a central difference
Write the gradients of a⊤x,∥x∥2,∥x∥,x⊤Ax and ∥Xw−y∥2, and say when 2Ax is correct
Write the backward pass of a dense layer (one example and a batch), of an elementwise function, and of softmax with cross-entropy, and recognise the common shape bugs
P1.C7 found that a dense layer sends the gradient back through W⊤, and P1.C5 said that the gradient for a weight matrix is a matrix of the same shape. This lesson keeps both promises, and adds the rest of the short list: the few rules that give the gradients of many of the layers and losses you will meet.
Why a list? A network has millions of weights, and people do not write the sums out one weight at a time. The rules say it in one line, such as W⊤g. A rule is only useful if you can trust it, so each one below comes with the shapes of its pieces and a number check.
Two layout conventions and one habit
Take a scalar loss L that depends on a vector x with n entries. Its gradient has n entries (P1.C5). Should they be written as a column or a row? And for a matrix W, should the gradient be shaped like W or like W⊤? Both choices are in use, and this site picks the following.
Gradient of a scalar: the shape of the variable.∇xL is a column with the same shape as x, and ∇WL is a matrix with the same shape as W, with entry ∂Wij∂L at position (i,j). This is called the denominator layout, because the shape comes from the variable we differentiate by. It makes the update W←W−η∇WL a plain subtraction of two arrays of one shape.
Jacobian of a vector function: m×n. For f:Rn→Rm, the Jacobian has one row per output and one column per input (P1.C7). This is the numerator layout.
Many books use the numerator layout for everything, so the gradient of a scalar becomes a row, and their formulas show a transpose where ours do not. Neither is wrong: the numbers are the same, only the arrangement differs. When you read a formula in another source, find out which layout it uses before comparing.
From the denominator layout comes a habit that catches many mistakes, the shape check:
The check is cheap, and it often forces the right formula. Later we meet a 4×5 matrix W, a vector g with 4 entries and a vector x with 5 entries. Which product of g and x has the shape of W? Only gx⊤(4×1 times 1×5). But the check is not a proof: when the matrices are square, wrong formulas can keep the right shape. So every rule here also gets a numeric check.
The method: nudge, expand, keep the linear part
P1.C5’s first-order approximation says that for a small nudge Δ of the input,
L(x+Δ)≈L(x)+∇L⋅Δ.
For a matrix variable the same holds, if the dot product is taken entry by entry. For two matrices of the same shape write ⟨G,Δ⟩=∑i,jGijΔij: multiply matching entries and add. It is the dot product you would get after listing both matrices’ entries in one long column. Then
L(W+Δ)≈L(W)+⟨∇WL,Δ⟩.
This gives a method that works for every rule below:
Replace the variable by (variable +Δ) and expand.
Drop every term that contains Δ twice (such terms are tiny: halve the nudge and they shrink four times).
Write what remains as ⟨something,Δ⟩. That something is the gradient.
Two warm-ups. First, L=a⊤x (a number: the dot product of P1.B3). Then L(x+Δ)=a⊤x+a⊤Δ, so ∇xL=a, which is the result of P1.C4 and P1.C5. Second, L=x⊤x=∥x∥2:
The two middle terms are equal because a number equals its own transpose: x⊤Δ=Δ⊤x. The last term has Δ twice, so it is dropped. What is left is ⟨2x,Δ⟩, so ∇∥x∥2=2x. Check with x=(3,4) and Δ=(0.01,0.02): the true value is (3.01)2+(4.02)2=25.2205,, and the first-order estimate is 25+2(3⋅0.01+4⋅0.02)=25.22.. The difference is 0.0005=Δ⊤Δ, the dropped term.
The cheat sheet
Here is the whole list. Vectors are columns. In all lines L is a number, and g or G is the gradient that arrives from the rest of the network (the gradient that the layers above send back). Each rule is derived or checked below. The letter y is the layer output in the dense-layer lines and the target in the least-squares and softmax lines.
Linear.L=a⊤x gives ∇xL=a, an n×1 column.
Squared length.L=∥x∥2 gives 2x.
Length.L=∥x∥ gives x/∥x∥, for x=0.
Quadratic form.L=x⊤Ax gives (A+A⊤)x, which equals 2Ax when A is symmetric.
Least squares.L=∥Xw−y∥2 gives 2X⊤(Xw−y), a d×1 column. For the average over N examples the factor is N2.
Dense layer. With y=Wx+b and g=∇yL (an m×1 column):
∇xL=W⊤g, which is n×1;
∇WL=gx⊤, which is m×n;
∇bL=g, which is m×1.
Dense layer on a batch. With Y=XW⊤+b and G=∇YL(N×m):
∇WL=G⊤X, which is m×n;
∇XL=GW, which is N×n;
∇bL= the column sums of G, which is m×1.
Elementwise function. With a=σ(z) applied entry by entry, ∇zL=g⊙σ′(z), where ⊙ multiplies matching entries.
Softmax with cross-entropy.∇zL=p−y, where p=softmax(z) and y is the one-hot target.
Before the derivations, try the shape checker. For each expression it shows the shape of every quantity, the formula with its shape arithmetic, and a check of the formula against a central difference (nudging each entry up and down by 0.00001) on the same numbers.
Shape checker: gradient formula, its shape, and a numeric check
L = gᵀ(Wx)
inputs n3
outputs m2
W2×3weights
x3×1input (the gradient is taken for this one)
g2×1gradient from above, ∂L/∂y
L1×1a single number (scalar)
The gradient must be 3×1, the shape of x.
Formula
∂L/∂x = Wᵀ g
Shapes: 3×2 · 2×1 → 3×1
Formula gives
−2−10
Central difference gives
−2−10
Shape 3×1 matches x. The formula agrees with the central difference: the largest difference is 1.6e-11.
Show the numbers used
W = [[1, 2, 3], [4, 5, 6]]
x = (1, 0, −1)
g = (2, −1)
Start with the lesson numbers, then switch the mistake on for each expression. With square sizes (for example n = m) some mistakes keep the right shape, and only the numbers give them away. The central difference nudges each entry by 0.00001 up and down on the same numbers.
The shape checker. Pick an expression and set the sizes with the − and + buttons. The list shows the shape of every quantity, and the line below it says which shape the gradient must have. The orange box is the formula with the shapes of its pieces. Below it, the formula's numbers (orange) are placed beside the central-difference numbers, and the status line compares them. “Lesson numbers” uses the numbers of this lesson, and “New random numbers” draws new ones between −2 and 2. “Show a common mistake” replaces the formula by a plausible wrong one, and the status says whether the shape check, the numeric check, both or neither catches it.
Things to try with the shape checker:
Start with Wx for x at the lesson numbers: the formula W⊤g gives (−2,−1,0), the shape 3×1 of x, and the central difference agrees.
Switch on the mistake. Wg is not defined, since W is 2×3 and g is 2×1. Now raise m to 3 so that W is square: the product exists, the shape fits, and the numbers are wrong. Only the numeric check catches it.
Choose Wx for W with the mistake on: xg⊤ has the shape 3×2 instead of 2×3. Make n and m equal and the shape fits again.
Choose x⊤Ax with the mistake 2Ax. The shape fits and the numbers are wrong. Tick “Make A symmetric” and the status says the mistake is harmless here, because the two formulas agree for symmetric A.
Choose the batch layer for b at the lesson numbers: the mistaken row sums have the right shape only because N=m=2. Raise N to 3 and see the shape fail.
Dense layer, from components
Take y=Wx+b with W of size m×n (P1.B5), so output i is yi=∑jWijxj+bi. The rest of the network turns y into the loss L, and the gradient g=∇yL with entries gi=∂yi∂L has arrived. We want the gradients for the layer’s own variables. The chain rule (P1.C3) turns each into one product.
For the weights.Wij affects only output i, and it does so by the amount xj:∂Wij∂yi=xj. Therefore
∂Wij∂L=∂yi∂L∂Wij∂yi=gixj.
Entry (i,j) is gixj: a column g times a row x⊤. This matrix is the outer productgx⊤ (P1.B6). In words: the gradient of a weight is (the gradient arriving at its output) times (the input it multiplies).
For the input.xj affects every output, through the weights in column j, so the effects add: ∂xj∂L=∑igiWij. That is entry j of W⊤g.For the bias,∂bi∂yi=1, so ∇bL=g.
The numbers of P1.C7 and P1.B15: W=(142536),x=(1,0,−1), and g=(2,−1), which is the gradient of the made-up loss L=2y1−y2. Then
Check the middle line by nudging. The entry W23 (row 2, column 3) is 6. Raise it by 0.001: then y2 changes by x3⋅0.001=−0.001, and L=2y1−y2 changes by +0.001. So ∂W23∂L=1, which is g2x3=(−1)(−1), the entry in row 2, column 3 of gx⊤. The entries in the middle column are 0 because x2=0: a weight on a zero input cannot change the loss.
The shapes force the formula.W is m×n,g is m×1 and x is n×1. The only way to build an m×n matrix from g and x is gx⊤(xg⊤ is n×m). To build an n×1 vector from W and g you need W⊤g(Wg is not defined unless n=m). The shape check was nearly enough to find both formulas.
The same layer on a batch
Real training handles a batch of N examples at once. Stack them as the rows of X(N×n), as in P1.B15, so the layer is Y=XW⊤+b, with the bias added to every row. The gradient arriving at Y is G(N×m), whose row k is the g of example k. The loss adds the examples, so the weight gradients add:
∇WL=k=1∑Ngkxk⊤=G⊤X.
The right-hand side is one matrix product: its (i,j) entry is ∑kGkiXkj, the same sum. Because the examples are the rows of X and of G, the sum over examples happens inside the matrix product. The other two are ∇XL=GW (row k is (W⊤gk)⊤, the single-example result) and ∇bL=∑kgk, the column sums of G. The bias is shared by all examples, so its gradient is added over them and has the shape of b, not one row per example.
With X=(1201−10) and G=(20−11) (the numbers of P1.B15):
G⊤XGW=(2101−21),=(−24−1506),
and the column sums of G are (2,0).
The first row of GW is the single-example answer (−2,−1,0). The first matrix is the single-example gx⊤ of above plus the second example’s (020100).
Two remarks. If the loss is an average over the batch, the factor N1 is already inside G, because G is the gradient of that loss. And if a library stores the weights the other way round, as an n×m matrix with Y=XW, the formulas change with the shapes (exercise 8). The shape check finds them again.
Quadratics: x⊤Ax, the length, and least squares
The quadratic form. For a square n×n matrix A,L=x⊤Ax=∑i,jAijxixj is a number. Nudge x:
L(x+Δ)=(x+Δ)⊤A(x+Δ)=x⊤Ax+x⊤AΔ+Δ⊤Ax+Δ⊤AΔ.
The last term is dropped. The third term is a number, so it equals its own transpose, Δ⊤Ax=x⊤A⊤Δ (P1.B10). The linear part is therefore x⊤(A+A⊤)Δ=⟨(A+A⊤)x,Δ⟩.. The matrix A+A⊤ is symmetric, so x⊤(A+A⊤)=((A+A⊤)x)⊤.. So
∇x(x⊤Ax)=(A+A⊤)x.
If A is symmetric(A⊤=A, P1.B10), this is 2Ax, which is the familiar-looking “derivative of ax2 is 2ax”. For a non-symmetric A the shortcut is wrong. Take A=(2013) and x=(1,2). Then Ax=(4,6) and x⊤Ax=16. By components, L=2x12+x1x2+3x22, whose partial derivatives are 4x1+x2 and x1+6x2, which are (6,13) at (1,2). The formula agrees:
(A+A⊤)x=(4116)(12)=(613),
while the shortcut gives 2Ax=(8,12). Nudge x1 from 1 to 1.001:L rises from 16 to 16.006002, which is 6×0.001 and not 8×0.001.
The length.∥x∥=x⊤x is a square root of the previous case, so the chain rule (P1.C3) gives 2∥x∥1⋅2x:
∇∥x∥=∥x∥x(x=0).
It is the unit vector along x: for x=(3,4) it is (0.6,0.8). Its length is 1, which makes sense: moving outward along x by a distance h lengthens x by h. At x=0 the length has a corner (a cone), like ∣x∣ in P1.C1, and there is no gradient. The squared length ∥x∥2 has no such problem: its gradient 2x is 0 at the origin.
Least squares. For N examples with features as the rows of X(N×d), targets y(N×1) and weights w(d×1), the predictions are Xw and the residual is r=Xw−y, which has N entries. The loss L=∥r∥2 is built from two rules we have. First, ∇rL=2r (the squared length). Second, r is a linear function of w through X, so the rule “W⊤ times the arriving gradient” applies with X in the role of W and 2r as g:
∇w∥Xw−y∥2=2X⊤(Xw−y).
The shapes are (d×N)(N×1)=d×1, the shape of w. Expanding the bracket gives 2X⊤Xw−2X⊤y, the form used in P1.B11. For the mean squared error (P0.2), the factor is N2.
Use the P0.2 data (1,2),(2,3),(3,7).. Give each example the features (x,1), so that w=(w,b), and write X=123111,y=(2,3,7). At w=(1,0):
The first entry of X⊤r is 1(−1)+2(−1)+3(−4)=−15 and the second is −1−1−4=−6.
The sum of squared residuals is 18 and the mean is 6, the loss of P1.C5. The mean’s gradient is 32X⊤r=(−10,−4), exactly the ∇L(1,0) of P1.C5, and the sum’s gradient is 3 times larger. This agrees with the per-example gradients (−2,−2),(−4,−2),(−24,−8) of P1.C5, which add to (−30,−12).
Setting the gradient to zero gives X⊤Xw=X⊤y, the normal equations of P1.B11, and with these data (14663)w=(29,12) has the solution (2.5,−1), the bottom of the loss in P1.C5. P3.A2 compares this one-step solution with gradient descent.
Elementwise functions and softmax with cross-entropy
An elementwise function. If a=σ(z) applies a function to each entry, output i depends only on input i, so the Jacobian is diagonal (P1.C7) and the vector-Jacobian product is an entry-by-entry product:
∇zL=g⊙σ′(z).
Take the sigmoid layer of P1.C7: W=(21−12),b=(0.5,−1),x=(0.5,0.5), so z=Wx+b=(1,0.5), and the gradient g=(1,−1) arrives at the outputs. The slopes are σ′(z)=(0.1966,0.2350),, so the gradient at z is δ=g⊙σ′(z)=(0.1966,−0.2350).. Now the dense-layer rules apply to δ:
The first line is the (0.158,−0.667) of P1.C7. These three lines are the whole backward step of a dense layer with an activation: scale by the slope, then multiply by W⊤, by x⊤, or keep it for the bias. P4.10 builds a network from this step.
Softmax with cross-entropy. P1.C7 derived the softmax Jacobian diag(p)−pp⊤ and used it to pull back the cross-entropy gradient. We can reach the same result with no Jacobian at all. For scores z and the correct class k, the loss is L=−lnpk, with pk=ezk/∑jezj, so
L=−zk+lnj∑ezj.
The first term has the derivative −1 with respect to zk and 0 with respect to the others. The derivative of the second term with respect to zi is ezi/∑jezj=pi (the chain rule on ln). Therefore
∇zL=p−y,
where y is the one-hot target: 1 at position k,0 elsewhere. For z=(1,2,3) and the third class correct, p=(0.0900,0.2447,0.6652),,L=−ln0.6652=0.4076 and
∇zL=(0.0900,0.2447,−0.3348),
the result that P1.C7’s vector-Jacobian product gave. Read it: the entry for the correct class is negative, so raising that score lowers the loss, and every other entry is positive, so raising a wrong class’s score raises the loss. The entries add up to 0, because adding the same number to every score changes nothing. The size of each entry is the probability error. The gradient is 0 only if p=y, which a softmax with finite scores cannot reach exactly. P3.A8 uses this gradient for softmax regression.
Verifying a gradient numerically
Every rule above can be tested the way P1.C5 tested a gradient: nudge each entry of the variable up and down by a small h and divide the change in L by 2h. A matrix gets the same treatment entry by entry, and costs two evaluations of L per entry, which is too slow for a large model but cheap for a test on small random numbers. The habit has two steps: compare the shape first, then compare the numbers.
With h=10−5 and ordinary floating-point numbers, a correct formula usually agrees to about 10−8 or better. Much larger differences point to a bug. A mistake that is small but not zero, such as a missing N1, shows up as a ratio: if your gradient is exactly a constant times the numeric one, look for a lost factor.
Deep-learning libraries do the same job with automatic differentiation (P1.C10). In PyTorch, each tensor created with requires_grad=True gets a .grad of the same shape as the tensor. This runs in Colab or on your machine, not in the browser here:
The loss is the number 2y1−y2. The two prints show (2−100−21) and (−2,−1,0), which are gx⊤ and W⊤g of this lesson (a zero entry may print as -0., which is the same number). The library has these rules built in, and a library’s gradient is as correct as its rules; when you write your own backward function, the central difference is the test.
Common shape bugs
A missing transpose in the backward pass:Wg in place of W⊤g. For a rectangular W, NumPy raises an error. For a square one it runs and returns wrong numbers (unless W is symmetric).
The outer product the wrong way round:xg⊤(n×m) in place of gx⊤(m×n). The update W−η(⋯) would usually fail, or, for square W, silently use the transposed gradient.
A gradient with the wrong orientation: a row (1×n) in place of a column (n×1), for example because a source uses the numerator layout.
A lost factor. The 2 of ∥x∥2, or the N1 of an average. A gradient that is exactly N times too large still has the right shape and the right direction, and in plain gradient descent it acts like a learning rate N times larger.
2Ax for a non-symmetric A.
Not summing the bias gradient over the batch. It must have the shape of b, not of Y.
Broadcasting a wrong shape into a wrong number. If Xw has shape (N,) and y has shape (N,1), then Xw−y is an N×N array (P1.B14). With the P0.2 data the sum of squares becomes 84 instead of 18, and no error is raised. The second cell below shows it.
Go deeper Why books disagree: numerator and denominator layouts
Take y=f(x) with x a column of n entries. In the numerator layout the derivative ∂x∂y is a row (∂x1∂y,…,∂xn∂y), the 1×n Jacobian, so that the first-order approximation reads Δy≈∂x∂yΔ with no transposes, and the chain rule is a product in the same order as the functions. In the denominator layout it is the column ∇xy, which has the shape of x, so that the update x−η∇y needs no transpose. The two differ by a transpose: ∇xy=(∂x∂y)⊤.
So a book in the numerator layout writes ∂x∂(a⊤x)=a⊤ and ∂x∂(x⊤Ax)=x⊤(A+A⊤),, rows where this lesson has columns. Transposing converts one to the other. The names are used with some variation in the literature, so check a source’s own definition. This site uses the denominator layout for gradients of scalars (the shape of the variable), and the m×n numerator layout for Jacobians, which is why a gradient is the transpose of the one-row Jacobian (P1.C7).
Go deeper The matrix inner product and the trace
The inner product used in this lesson, ⟨A,B⟩=∑i,jAijBij, can be written with the trace (the sum of the diagonal entries): ⟨A,B⟩=tr(A⊤B). The trace has a cyclic property, tr(PQR)=tr(RPQ) whenever the products exist. Together they give the weight gradient in one line. Let L=g⊤Wx (a number) and nudge W by Δ. The change is exactly
g⊤Δx=tr(g⊤Δx)=tr(xg⊤Δ)=tr((gx⊤)⊤Δ)=⟨gx⊤,Δ⟩.
A number is its own trace, the second step moves x round the cycle, and (gx⊤)⊤=xg⊤. So ∇WL=gx⊤, as found from components. The same pattern (bring the nudge to the right end, then read off what is in front) gives many matrix gradients. If it feels like a trick, use the component method: it always works, only more slowly.
Go deeper Only the symmetric part of A matters
Split A=S+K with S=21(A+A⊤) symmetric and K=21(A−A⊤) antisymmetric (K⊤=−K). For an antisymmetric matrix, x⊤Kx is a number equal to its own transpose, x⊤K⊤x=−x⊤Kx, so it is 0. Hence x⊤Ax=x⊤Sx: the antisymmetric part contributes nothing, and the gradient (A+A⊤)x=2Sx only sees S. For A=(0−110) the value is 0 for every x, and so is the gradient. The derivative of the gradient (A+A⊤)x with respect to x is the matrix A+A⊤, which is the Hessian of P1.C8.
Go deeper Why we avoid the full derivative of Wx with respect to W
The Jacobian of y=Wx with respect to x is the matrix W (P1.C7). With respect to the matrix W it is stranger: each of the m outputs depends on each of the m⋅n weights, so the derivative has m⋅m⋅n entries (twelve for a 2×3 matrix), a three-index array with ∂Wkj∂yi=xj when i=k and 0 otherwise. Almost all of it is zeros. A scalar loss avoids the problem: contracting this array with the arriving gradient g leaves a matrix of the shape of W, the outer product gx⊤. That is why the rules in this lesson are stated for a scalar L and an arriving gradient, which is also how automatic differentiation works (the vector-Jacobian product of P1.C7).
Matrix calculus in three depths
Intuition
Backward through a layer, the gradient meets the same matrix as the forward pass, transposed. Output i was built from row i of W. Input j affected every output through column j, so its gradient is collected from column j. A weight’s gradient is (what arrived at its output) times (what went in at its input). A weight on a large input, whose output matters a lot to the loss, gets a large gradient, and a weight on a zero input gets none.
“Blame” is only a picture. The gradient is a slope, how much the loss would change per unit change of that weight, and a weight with a large gradient may be quite right and a different one still needs a bigger move.
When you are stuck, forget the shapes of the answer for a moment and write the sum with indices, as with yi=∑jWijxj. Differentiate one entry. Then arrange the entries back into a matrix and let the shape check confirm the arrangement.
Math
Layout: ∇XL has the shape of X, with entries ∂L/∂Xij. Method: L(X+Δ)−L(X)≈⟨∇XL,Δ⟩=∑ij(∇XL)ijΔij..
∇(a⊤x)∇∥x∥2∇∥x∥∇(x⊤Ax)=a,=2x,=∥x∥x,=(A+A⊤)x,
For least squares, L=∥Xw−y∥2 and
∇wL=2X⊤(Xw−y).
Layers, with g=∇yL and G=∇YL:
y=Wx+b, for x,W,b:W⊤g,gx⊤,g.
Y=XW⊤+b, for X,W,b:GW,G⊤X,G⊤1.
a=σ(z), for z:g⊙σ′(z).
Softmax with cross-entropy, for z:p−y.
Here 1 is a column of N ones, so G⊤1 is the column sums of G. The component derivation of the dense layer is ∂Wij∂L=gixj and ∂xj∂L=∑igiWij.
Code
import numpy as npdef num_grad(f, x, h=1e-5): """Central differences.""" x = np.array(x, dtype=float) g = np.zeros_like(x) for i in np.ndindex(x.shape): up = x.copy() down = x.copy() up[i] += h down[i] -= h fu, fd = f(up), f(down) g[i] = (fu - fd) / (2*h) return g# a non-symmetric AA = np.array([[2, 1], [0, 3]])x = np.array([1, 2])print((A + A.T) @ x) # [ 6 13]f = lambda x: x @ A @ xprint(num_grad(f, x))# about [ 6. 13.]
After backward(), each tensor you created with requires_grad=True has a .grad of its own shape (an intermediate result gets none unless you ask with retain_grad()), so W.grad.shape == W.shape is a one-line shape check.
Try it: verify the rules in code
The first cell uses a num_grad that works for arrays of any shape and checks the rules of this lesson on the lesson’s numbers: a shape check first, then the largest difference from the formula. Predict the output before you run: the differences should be tiny (of the order 10−10 or smaller). The second cell shows the shape bugs: a square matrix that hides a missing transpose, the outer product the wrong way round, and the broadcast that turns a shape error into a wrong number.
Try it: check the gradient rules numerically
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Challenge: check the gradient of x⊤Ax for a random 4×4 matrix A = np.random.rand(4, 4) and a random x. Then replace A by (A + A.T) / 2 and see that 2Ax passes the check too.
Try it: shape bugs that run without an error
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Challenge: write the backward pass of the sigmoid layer of this lesson as three lines of NumPy (delta, then W.T @ delta, then np.outer(delta, x)) and check each with num_grad.
Common mistakes
Check your understanding
Let A=(1023) and L=x⊤Ax. What is ∇xL at x=(1,1)?
The gradient is (A+A⊤)x=(2226)(1,1)=(4,8). The pair (6,6) is 2Ax, which is right only for a symmetric A, and this A is not. The pair (3,3) is Ax and (1,5) is A⊤x, each only half of the sum.
A layer computes y=Wx with W of shape 4×5. The gradient g=∇yL arrives. What is the shape of ∇WL=gx⊤?
The gradient has the shape of the matrix it belongs to, 4×5, and the product has it: g is 4×1 and x⊤ is 1×5, so the outer product is 4×5. The shape 5×4 is what xg⊤ would give, which is the transposed (and wrong) arrangement. The square shapes would need g and x to have the same length.
A batch of 32 examples goes through Y=XW⊤+b, where b has 4 entries. What shape does ∇bL have?
A gradient has the shape of the variable, and the bias has 4 entries. It is shared by all 32 examples, so their per-example gradients are added: the column sums of G. A 32×4 array is the shape of G itself, before the sum, and the other two shapes do not match the bias.
A classifier with three classes outputs the probabilities p=(0.7,0.2,0.1), and the correct class is the second. What is the gradient of the cross-entropy loss with respect to the three scores?
The gradient is p−y with y=(0,1,0), which is (0.7,0.2−1,0.1)=(0.7,−0.8,0.1). The entries add up to 0. The vector with all signs reversed is y−p, which would push the loss up if used to descend. Subtracting 1 at the third entry uses the wrong class, and p alone forgets the target.
A backward pass through y=Wx with a square 3×3 matrix W is coded as W @ g instead of W.T @ g. No error appears. What is the right conclusion?
For a square matrix both products are 3×1, so the shape check passes, yet the entries differ unless W is symmetric. A matrix product multiplies exactly the matrix it is given, so there is no automatic transpose. Having the shape of x is necessary for a correct gradient but does not prove it.
Exercises
Find ∇∥x∥2 and ∇∥x∥ at x=(1,−2,2).Show answer∥x∥=1+4+4=3. So ∇∥x∥2=2x=(2,−4,4) and ∇∥x∥=x/3=(31,−32,32),, which has length 1.
For A=(1324) and x=(1,−1), find ∇(x⊤Ax), and the wrong 2Ax.Show answerA+A⊤=(2558), so the gradient is (2−5,5−8)=(−3,−3).. The shortcut 2Ax=2(−1,−1)=(−2,−2) is wrong because A is not symmetric.
For X=111012 and y=(1,2,2), find the gradient of ∥Xw−y∥2 at w=0, then solve the normal equations. Show answerAt w=0 the residual is −y=(−1,−2,−2),X⊤r=(−5,−6) and the gradient is 2X⊤r=(−10,−12). The normal equations (3335)w=(5,6) give w=(67,21)≈(1.167,0.5)..
A layer has W=120013, input x=(2,1) and arriving gradient g=(1,0,−1). Find ∇xL and ∇WL, and give their shapes. Show answer∇xL=W⊤g=(1−0,0−3)=(1,−3),, with 2 entries like x.∇WL=gx⊤=20−210−1, shape 3×2 like W.
A ReLU acts on z=(−2,0.5,3), and the gradient (1,2,3) arrives at its outputs. What does it send back? Show answerThe slope of ReLU is 0 for negative inputs and 1 for positive ones, so g⊙ReLU′(z)=(0,2,3).. (At exactly 0 the slope is not defined and software picks a convention; none of the entries here is 0.)
Two classes have equal scores z=(0,0) and the first class is correct. Find the gradient of the cross-entropy loss. Show answerp=(0.5,0.5) and y=(1,0), so p−y=(−0.5,0.5): raise the first score, lower the second.
A batch of 64 examples with 784 features goes through a layer with 128 outputs, Y=XW⊤+b. Give the shapes of W,G,∇WL,∇bL and ∇XL.Show answerW is 128×784 and G is 64×128. Then ∇WL=G⊤X is (128×64)(64×784)=128×784..∇bL has 128 entries, and ∇XL=GW is (64×128)(128×784)=64×784..
A library stores the weights as W of shape n×m and computes Y=XW (no transpose). Find ∇WL and ∇XL from G.Show answer∇WL=X⊤G, shape (n×N)(N×m)=n×m, and ∇XL=GW⊤, shape (N×m)(m×n)=N×n. These are the earlier formulas with W replaced by W⊤. A central-difference check on random X,W and G agrees to about 10−9.
Why is p−y a sensible error signal for softmax? Show answerIts entry for the correct class is pk−1≤0, so a gradient step raises that score, and its other entries pi≥0 lower the wrong scores, more for the classes the model prefers. The entries add up to 0, so the step raises some scores and lowers others by the same total. It is small when p is already close to y.
Next: P1.C8 takes the second derivative of these formulas, the Hessian, and explains bowls and saddles. P4.8 and P4.10 use the dense-layer rules above to run backpropagation through a whole network, and P3.A2 and P3.A8 use the least-squares and softmax gradients to train models.
Key takeaways
Layout and the shape check. On this site the gradient of a scalar L with respect to a vector or matrix has the shape of that vector or matrix, and a Jacobian of f:Rn→Rm is m×n. Books differ, and their formulas then differ by a transpose. After you write a gradient, check its shape against the thing it belongs to.
The method. Nudge the variable by Δ, expand L(x+Δ), and drop terms with Δ twice. What is left is ⟨∇L,Δ⟩, a sum of entrywise products, and the thing multiplying Δ is the gradient.
Cheat sheet.∇(a⊤x)=a,∇∥x∥2=2x,∇∥x∥=x/∥x∥ for x=0,∇(x⊤Ax)=(A+A⊤)x (which is 2Ax only for symmetric A), and ∇w∥Xw−y∥2=2X⊤(Xw−y). For the average over N examples, divide by N.
Layers. For y=Wx+b with g=∇yL:∇xL=W⊤g,∇WL=gx⊤ (an outer product) and ∇bL=g. For a batch Y=XW⊤+b with G=∇YL:G⊤X,GW and the column sums of G. An elementwise function gives g⊙σ′(z).
Softmax with cross-entropy has the gradient p−y with respect to the scores, where y is the one-hot target. For scores (1,2,3) and the third class correct it is (0.0900,0.2447,−0.3348).
Check, do not trust. A shape check misses a missing transpose when W is square, and broadcasting can turn a wrong shape into a wrong number. Compare every new gradient with a central difference on small random numbers; automatic differentiation (PyTorch) gives the same answers.