Survey of Mathematics

3.8 Matrix calculus and backpropagation

Training a neural network means computing how a single number (the loss) changes with millions of weights. The derivative of a composition is a product of matrices, and evaluating that product from the output backwards is backpropagation.

Beyond the courseGoodfellow, Bengio and Courville, Deep Learning, ch. 6.5Petersen and Pedersen, The Matrix CookbookCS 532 (Matrix Methods in Machine Learning)

A neural network is a long composition of simple maps: multiply by a weight matrix, add a vector, squash each entry, repeat. Training it means nudging every weight to make the error smaller, which requires the derivative of one number (the loss) with respect to every weight. With millions of weights, computing each derivative separately would take millions of passes through the network. Backpropagation gets all of them in one backward pass, for about the cost of one forward pass. It is nothing but the chain rule, with the matrices multiplied in the right order.

Before you start

Chapter 1.4 (the derivative as best linear approximation, the chain rule), 2.5 (composition is matrix multiplication) and 2.10 (least squares).

Quick checkIn one variable, the chain rule says (f∘g)′(a)=f′(g(a)) g′(a)(f \circ g)'(a) = f'(g(a))\,g'(a). What happens to the 'slopes'?
Quick checkIf AA is 2×32 \times 3 and BB is 3×43 \times 4, what is the shape of ABAB?

The picture: derivatives as matrices

For a function g:Rn→Rmg: \mathbb R^n \to \mathbb R^m, the derivative at a point is the best linear approximation (1.4’s idea, one dimension up): g(x+h)≈g(x)+Jg(x) hg(x + h) \approx g(x) + J_g(x)\,h, where Jg(x)J_g(x) is the m×nm \times n Jacobian matrix whose entry (i,j)(i, j) is ∂gi∂xj\frac{\partial g_i}{\partial x_j}, the rate at which output ii changes when input jj is nudged. For a scalar function f:Rn→Rf: \mathbb R^n \to \mathbb R the Jacobian is a single row, and its transpose, a column, is the gradient ∇f\nabla f, pointing uphill. Chapters 5.2 and 5.3 make these definitions rigorous; here we use them to compute.

Where this came from· Backpropagation was discovered several times

The chain rule is from Leibniz (1676). Running it backwards through a computation (reverse-mode differentiation) was described by Seppo Linnainmaa in his 1970 master’s thesis. Paul Werbos applied it to neural networks in his 1974 PhD thesis. It became famous when David Rumelhart, Geoffrey Hinton and Ronald Williams showed in 1986 (Nature) that it lets multi-layer networks learn useful internal representations. Hinton later shared the 2018 Turing Award with Yoshua Bengio and Yann LeCun for work on deep learning. In 2024 he shared the Nobel Prize in Physics with John Hopfield for foundational discoveries on machine learning with artificial neural networks.

The rules you need

Three gradient formulas cover most of linear models. In each, x∈Rnx \in \mathbb R^n is the variable and everything else is constant.

Function f(x)f(x)Gradient ∇f(x)\nabla f(x)Why
aTx=∑iaixia^{\mathsf T}x = \sum_i a_i x_iaa∂∂xj∑iaixi=aj\frac{\partial}{\partial x_j}\sum_i a_ix_i = a_j
xTAxx^{\mathsf T}Ax(A+AT)x(A + A^{\mathsf T})x, which is 2Ax2Ax if AA is symmetricexpand ∑i,jaijxixj\sum_{i,j}a_{ij}x_ix_j and differentiate in xkx_k
∥Ax−b∥2\lVert Ax - b \rVert^22AT(Ax−b)2A^{\mathsf T}(Ax - b)expand, then use the first two rows
Worked example
Derive the gradient of f(x)=xTAxf(x) = x^{\mathsf T}Ax by differentiating in one coordinate.

Solution.

  1. Expand into a double sum. f(x)=∑i=1n∑j=1naijxixjf(x) = \sum_{i=1}^n\sum_{j=1}^n a_{ij}x_ix_j. Row-times-column written out entry by entry.
  2. Differentiate in xkx_k. Only terms containing xkx_k survive: those with i=ki = k give ∑jakjxj\sum_j a_{kj}x_j, and those with j=kj = k give ∑iaikxi\sum_i a_{ik}x_i. Product rule: xixjx_ix_j depends on xkx_k through either factor; when i=j=ki = j = k both contributions appear, which matches ddxx2=2x\frac{d}{dx}x^2 = 2x.
  3. Recognise the sums. ∑jakjxj=(Ax)k\sum_j a_{kj}x_j = (Ax)_k and ∑iaikxi=(ATx)k\sum_i a_{ik}x_i = (A^{\mathsf T}x)_k. Entry kk of a matrix-vector product.

Answer. ∇f=Ax+ATx=(A+AT)x\nabla f = Ax + A^{\mathsf T}x = (A + A^{\mathsf T})x. For symmetric AA this is 2Ax2Ax, the matrix version of ddx(ax2)=2ax\frac{d}{dx}(ax^2) = 2ax.

Worked example
Recover the normal equations of least squares by setting a gradient to zero.

Solution.

  1. Write the loss. L(x)=∥Ax−b∥2=xTATAx−2bTAx+bTbL(x) = \lVert Ax - b \rVert^2 = x^{\mathsf T}A^{\mathsf T}Ax - 2b^{\mathsf T}Ax + b^{\mathsf T}b. Expand (Ax−b)T(Ax−b)(Ax - b)^{\mathsf T}(Ax - b); the two middle terms are equal numbers.
  2. Gradient term by term. ∇(xTATAx)=2ATAx\nabla(x^{\mathsf T}A^{\mathsf T}Ax) = 2A^{\mathsf T}Ax (symmetric matrix ATAA^{\mathsf T}A), ∇(−2bTAx)=−2ATb\nabla(-2b^{\mathsf T}Ax) = -2A^{\mathsf T}b (first rule with a=ATba = A^{\mathsf T}b), and the constant contributes 0. The rules in the table.
  3. Set to zero. 2ATAx−2ATb=O2A^{\mathsf T}Ax - 2A^{\mathsf T}b = O, so ATAx=ATbA^{\mathsf T}Ax = A^{\mathsf T}b. At a minimum of a smooth function, every directional slope is zero (Fermat’s theorem in many variables, 5.6).

Answer. The normal equations of 2.10, reached by calculus instead of geometry. Both routes agree: “the error is perpendicular to every column” is “the gradient is zero”.

Worked example
Find ∇f\nabla f for f(x)=∥x∥2=xTxf(x) = \lVert x \rVert^2 = x^{\mathsf T}x, and the shape and value of the Jacobian of g(x)=Wxg(x) = Wx for WW of size 3×53 \times 5.

Solution.

  1. Match a rule. xTx=xTIxx^{\mathsf T}x = x^{\mathsf T}Ix, which is the second row of the table with A=IA = I. Writing the function in the form of a known rule is the first move for every gradient.
  2. Apply it. ∇f=(I+IT)x=2x\nabla f = (I + I^{\mathsf T})x = 2x. II is symmetric, so (A+AT)x=2Ax(A + A^{\mathsf T})x = 2Ax.
  3. Sanity check with one variable. For n=1n = 1, f(x)=x2f(x) = x^2 and f′(x)=2xf'(x) = 2x. The new rule must reduce to the old one.
  4. Jacobian shape. g:R5→R3g: \mathbb R^5 \to \mathbb R^3, so JgJ_g is 3×53 \times 5. Rows are outputs, columns are inputs.
  5. Jacobian value. Entry (i,j)(i, j) of JgJ_g is ∂∂xj∑kWikxk=Wij\frac{\partial}{\partial x_j}\sum_k W_{ik}x_k = W_{ij}, so Jg=WJ_g = W. A linear map is its own best linear approximation.

Answer. ∇∥x∥2=2x\nabla\lVert x \rVert^2 = 2x, and JWx=WJ_{Wx} = W (size 3×53 \times 5).

Worked example
Find the minimiser of the ridge-regression loss L(x)=∥Ax−b∥2+λ∥x∥2L(x) = \lVert Ax - b \rVert^2 + \lambda\lVert x \rVert^2 for A=[100111]A = \begin{bmatrix}1&0\\0&1\\1&1\end{bmatrix}, b=(1,2,3)b = (1, 2, 3), λ=1\lambda = 1.

Solution.

  1. Gradient. ∇L=2AT(Ax−b)+2λx\nabla L = 2A^{\mathsf T}(Ax - b) + 2\lambda x. Sum of the third table row and the gradient of λxTx\lambda x^{\mathsf T}x from the previous example.
  2. Set to zero. (ATA+λI)x=ATb(A^{\mathsf T}A + \lambda I)x = A^{\mathsf T}b. Divide by 2 and collect the xx terms.
  3. Compute the pieces. ATA=[2112]A^{\mathsf T}A = \begin{bmatrix}2&1\\1&2\end{bmatrix}, so ATA+I=[3113]A^{\mathsf T}A + I = \begin{bmatrix}3&1\\1&3\end{bmatrix}, and ATb=(1+3, 2+3)=(4,5)A^{\mathsf T}b = (1 + 3,\ 2 + 3) = (4, 5). Column dot products, then add λ\lambda on the diagonal.
  4. Solve. The determinant is 88, so x=18[3−1−13][45]=18(7,11)x = \frac18\begin{bmatrix}3&-1\\-1&3\end{bmatrix}\begin{bmatrix}4\\5\end{bmatrix} = \frac18(7, 11). The inverse of a 2×22 \times 2 matrix.

Answer. x=(78,118)x = (\frac78, \frac{11}8). The matrix ATA+λIA^{\mathsf T}A + \lambda I is positive definite for λ>0\lambda > 0 (3.2), so this is always solvable, even when AA has dependent columns.

Your answerFor f(x,y)=3x+5yf(x, y) = 3x + 5y (that is, aTxa^{\mathsf T}x with a=(3,5)a = (3, 5)), what is ∂f∂y\frac{\partial f}{\partial y}?
Worked example
Prove ∇(aTx)=a\nabla(a^{\mathsf T}x) = a, then use the product rule to prove ∇(xTAx)=(A+AT)x\nabla(x^{\mathsf T}Ax) = (A + A^{\mathsf T})x without expanding into sums.

Solution.

  1. The linear rule. aTx=∑iaixia^{\mathsf T}x = \sum_ia_ix_i, so ∂∂xk(aTx)=ak\frac{\partial}{\partial x_k}(a^{\mathsf T}x) = a_k. Only the term with i=ki = k contains xkx_k.
  2. Split the quadratic. Write xTAx=uTvx^{\mathsf T}Ax = u^{\mathsf T}v with u=xu = x and v=Axv = Ax. Two vector-valued functions of xx multiplied by a dot product.
  3. Product rule for a dot product. ∇(uTv)=JuTv+JvTu\nabla(u^{\mathsf T}v) = J_u^{\mathsf T}v + J_v^{\mathsf T}u. Differentiate ∑iuivi\sum_iu_iv_i in xkx_k: ∑i(∂ui∂xkvi+ui∂vi∂xk)\sum_i\big(\frac{\partial u_i}{\partial x_k}v_i + u_i\frac{\partial v_i}{\partial x_k}\big), which is entry kk of JuTv+JvTuJ_u^{\mathsf T}v + J_v^{\mathsf T}u.
  4. Jacobians. Ju=IJ_u = I and Jv=AJ_v = A. xx is its own best linear approximation, and AxAx is linear with matrix AA.
  5. Substitute. ∇(xTAx)=ITAx+ATx=Ax+ATx\nabla(x^{\mathsf T}Ax) = I^{\mathsf T}Ax + A^{\mathsf T}x = Ax + A^{\mathsf T}x.

Answer. ∇(xTAx)=(A+AT)x\nabla(x^{\mathsf T}Ax) = (A + A^{\mathsf T})x. ■\blacksquare

Proof workshopRebuild the gradient of a quadratic form

Tap the lines in the order a proof would write them. Each line can only use what is already above it.

    Your answerFor f(x)=xTAxf(x) = x^{\mathsf T}Ax with A=[2113]A = \begin{bmatrix}2&1\\1&3\end{bmatrix} at x=(1,1)x = (1, 1), what is the first entry of ∇f\nabla f?

    The chain rule as a product of matrices

    If x↦u=g(x)↦y=f(u)x \mapsto u = g(x) \mapsto y = f(u), then near a point

    Jf∘g(x)=Jf(u) Jg(x),J_{f \circ g}(x) = J_f(u)\,J_g(x),

    the product of the Jacobians, in the same order as the composition (Apostol 8.20, proved in 5.4). A network with layers x→h1→h2→⋯→hL→ℓx \to h_1 \to h_2 \to \dots \to h_L \to \ell (a scalar loss) therefore has

    ∇xℓT=Jℓ JhL⋯Jh2 Jh1,\nabla_x \ell^{\mathsf T} = J_\ell\,J_{h_L}\cdots J_{h_2}\,J_{h_1},

    a long product of matrices whose first factor is a single row.

    Why· Why the order of multiplication matters so much

    Matrix multiplication is associative, so any bracketing gives the same answer, but the cost differs enormously. Multiplying from the left starts with a row vector: (row) × (matrix) is a row, so every step is a cheap vector-times-matrix product. Multiplying from the right starts with two full matrices: every step is an expensive matrix-times-matrix product. For one output (the loss) and many inputs (the weights), going from the output backwards is far cheaper. That is the entire idea of backpropagation, also called reverse-mode differentiation.

    Definition B

    Computational graph

    A computational graph records a computation as nodes (the inputs, every intermediate value, and the output) joined by arrows from the values each node uses. Evaluating it from inputs to output is the forward pass.

    In one lineA diagram of a calculation: nodes are intermediate values, arrows say which values each one is computed from.

    Why it existsIt turns any program into a composition of simple steps, so the chain rule can be applied mechanically, node by node.

    Definition B

    Backpropagation

    Backpropagation computes ∂ℓ∂v\frac{\partial \ell}{\partial v} for every node vv of a computational graph whose output ℓ\ell is a scalar. It starts with ∂ℓ∂ℓ=1\frac{\partial \ell}{\partial \ell} = 1 and moves backwards: each node’s derivative is the sum, over the nodes that use it, of (that node’s derivative) × (the local derivative of that node with respect to this one).

    In one lineCompute the derivative of a scalar output with respect to every input by applying the chain rule backwards through the computational graph, reusing each intermediate result once.

    Why it existsIt gets all n partial derivatives for about the cost of one forward pass, instead of n separate passes.

    Worked example
    Backpropagate through the network z=w1xz = w_1x, h=max⁡(0,z)h = \max(0, z), y=w2hy = w_2h, ℓ=12(y−t)2\ell = \frac12(y - t)^2 at x=2x = 2, w1=3w_1 = 3, w2=−1w_2 = -1, t=1t = 1, and take one gradient step.

    Solution. Do a forward pass and keep every value. Then walk backwards, multiplying by one local derivative per arrow. The step-through shows each stage.

    Answer. ∂ℓ∂w1=14\frac{\partial \ell}{\partial w_1} = 14 and ∂ℓ∂w2=−42\frac{\partial \ell}{\partial w_2} = -42. After one step with learning rate 0.010.01 the weights are w1=2.86w_1 = 2.86, w2=−0.58w_2 = -0.58 and the loss falls from 24.524.5 to about 9.39.3.

    Worked example
    Same network, but with input x=−2x = -2. What is ∂ℓ∂w1\frac{\partial \ell}{\partial w_1}, and what has happened?

    Solution.

    1. Forward pass. z=w1x=−6z = w_1x = -6, h=max⁡(0,−6)=0h = \max(0, -6) = 0, y=w2h=0y = w_2h = 0, ℓ=12(0−1)2=0.5\ell = \frac12(0 - 1)^2 = 0.5. The ReLU clips the negative value to 0.
    2. Backward from the loss. ∂ℓ∂y=y−t=−1\frac{\partial \ell}{\partial y} = y - t = -1, and ∂ℓ∂h=−1⋅w2=1\frac{\partial \ell}{\partial h} = -1\cdot w_2 = 1. Same local derivatives as before.
    3. Through the ReLU. ∂ℓ∂z=∂ℓ∂h⋅1[z>0]=1⋅0=0\frac{\partial \ell}{\partial z} = \frac{\partial \ell}{\partial h}\cdot\mathbf 1[z > 0] = 1\cdot 0 = 0. z<0z < 0, so the ReLU has derivative 0 here.
    4. To the weight. ∂ℓ∂w1=0⋅x=0\frac{\partial \ell}{\partial w_1} = 0\cdot x = 0. Everything upstream of a zero is zero.

    Answer. ∂ℓ∂w1=0\frac{\partial \ell}{\partial w_1} = 0: the unit is “dead” for this input, so gradient descent cannot move w1w_1 using it. With the identity in place of ReLU the derivative would be 1⋅(−2)=−2≠01\cdot(-2) = -2 \ne 0.

    Worked example
    A dense layer has W=[1023−11]W = \begin{bmatrix}1&0&2\\3&-1&1\end{bmatrix}, input h=(1,2,3)h = (1, 2, 3) and incoming gradient g=∂ℓ∂z=(1,−1)g = \frac{\partial \ell}{\partial z} = (1, -1). Find ∂ℓ∂W\frac{\partial \ell}{\partial W} and ∂ℓ∂h\frac{\partial \ell}{\partial h}.

    Solution.

    1. Shapes first. z=Whz = Wh has 2 entries, so gg has 2. ∂ℓ∂W\frac{\partial \ell}{\partial W} must be 2×32 \times 3 and ∂ℓ∂h\frac{\partial \ell}{\partial h} must have 3 entries. Each gradient has the shape of the thing it differentiates by.
    2. Weight gradient. ∂ℓ∂W=ghT=[1−1][123]=[123−1−2−3]\frac{\partial \ell}{\partial W} = gh^{\mathsf T} = \begin{bmatrix}1\\-1\end{bmatrix}\begin{bmatrix}1&2&3\end{bmatrix} = \begin{bmatrix}1&2&3\\-1&-2&-3\end{bmatrix}. Entry (i,j)(i, j) is gihjg_ih_j: weight WijW_{ij} only affects output ii, by a factor hjh_j.
    3. Input gradient. ∂ℓ∂h=WTg=[130−121][1−1]=[−211]\frac{\partial \ell}{\partial h} = W^{\mathsf T}g = \begin{bmatrix}1&3\\0&-1\\2&1\end{bmatrix}\begin{bmatrix}1\\-1\end{bmatrix} = \begin{bmatrix}-2\\1\\1\end{bmatrix}. Input hjh_j affects every output ii through WijW_{ij}, so we add giWijg_iW_{ij} over ii, which is a multiplication by WTW^{\mathsf T}.

    Answer. ∂ℓ∂W=[123−1−2−3]\frac{\partial \ell}{\partial W} = \begin{bmatrix}1&2&3\\-1&-2&-3\end{bmatrix} (rank 1, an outer product), ∂ℓ∂h=(−2,1,1)\frac{\partial \ell}{\partial h} = (-2, 1, 1).

    Worked example algorithms
    A network has L=10L = 10 layers, each with an n×nn \times n weight matrix and n=1000n = 1000. Compare the cost of the products rTM1⋯MLr^{\mathsf T}M_1\cdots M_L evaluated left to right and right to left.

    Solution.

    1. Left to right. Each step multiplies a row by an n×nn \times n matrix, about n2=106n^2 = 10^6 operations. There are L=10L = 10 steps: about 10710^7. A row times a matrix needs nn multiplications for each of nn outputs.
    2. Right to left. The first L−1=9L - 1 = 9 steps multiply two n×nn \times n matrices, about n3=109n^3 = 10^9 operations each, then a final row product: about 9×1099\times10^9. A matrix times a matrix needs nn multiplications for each of n2n^2 outputs.
    3. Ratio. 9×109107=900\frac{9\times10^9}{10^7} = 900. Roughly nn times cheaper, as the general count Ln3Ln2=n\frac{Ln^3}{Ln^2} = n says.

    Answer. Left to right is about 900 times cheaper here, and about nn times cheaper in general. Reverse-mode differentiation is the left-to-right order, because it starts from the single-row end (the scalar loss).

    Python labCheck backpropagation against finite differences, then train
    import numpy as np
    
    # the tiny network of the step-through: z = w1*x, h = max(0, z), y = w2*h, loss = (y - t)^2 / 2
    def loss(w1, w2, x=2.0, t=1.0):
        h = max(0.0, w1 * x)
        return 0.5 * (w2 * h - t) ** 2
    
    w1, w2, x, t = 3.0, -1.0, 2.0, 1.0
    # backpropagation, by hand
    z = w1 * x; h = max(0.0, z); y = w2 * h
    dy = y - t
    dw2 = dy * h
    dh = dy * w2
    dz = dh * (1.0 if z > 0 else 0.0)
    dw1 = dz * x
    print("backprop      :", dw1, dw2)
    
    # finite differences: one extra forward pass per weight
    eps = 1e-6
    print("finite differ.:", (loss(w1 + eps, w2) - loss(w1, w2)) / eps,
                             (loss(w1, w2 + eps) - loss(w1, w2)) / eps)
    
    # gradient descent: watch the loss fall
    for step in range(5):
        print(step, round(loss(w1, w2), 4))
        z = w1 * x; h = max(0.0, z); y = w2 * h
        dy = y - t
        g1 = dy * w2 * (1.0 if z > 0 else 0.0) * x
        g2 = dy * h
        w1 -= 0.01 * g1; w2 -= 0.01 * g2

    Try this. Run it. The backprop gradients (14,−42)(14, -42) and the finite differences agree to about five digits, and the loss falls with every step. Change the input x in the first line of the loss function and in the hand computation to -2.0: the gradient with respect to w1 becomes 0, the dead-ReLU case from the example. Change both learning rates 0.01 to 0.1 in the training loop: the first step makes the loss rise from 24.5 to about 42.7 (the step overshoots), and then the unit goes dead and the loss freezes at 0.5.

    Worked example
    Check a backpropagated derivative numerically.

    Solution.

    1. Pick the derivative to check. Backprop gave ∂ℓ∂w1=14\frac{\partial \ell}{\partial w_1} = 14 in the step-through. Every framework’s tests compare backprop against a finite difference.
    2. Nudge the weight. With w1=3.001w_1 = 3.001: z=6.002z = 6.002, h=6.002h = 6.002, y=−6.002y = -6.002, ℓ=12(7.002)2=24.514002\ell = \frac12(7.002)^2 = 24.514002. One forward pass with the weight changed by 10−310^{-3}.
    3. Form the difference quotient. 24.514002−24.50.001=14.002\frac{24.514002 - 24.5}{0.001} = 14.002. The definition of the derivative (1.4), with a small hh instead of a limit.

    Answer. 14.002≈1414.002 \approx 14, matching backprop up to the O(h)O(h) error of a one-sided difference. A numerical check costs one forward pass per weight, which is why it is only used for testing, never for training.

    Your answerIn the step-through, change the target to t=−6t = -6 (so the prediction y=−6y = -6 is perfect). What is ∂ℓ∂w1\frac{\partial \ell}{\partial w_1}?
    Quick checkA layer computes z=Whz = Wh with WW of size 4×74 \times 7. What is the shape of ∂ℓ∂W\frac{\partial \ell}{\partial W}?
    Quick checkFor a scalar function f:Rn→Rf: \mathbb R^n \to \mathbb R, the Jacobian JfJ_f and the gradient ∇f\nabla f are related by:
    Quick checkIn a network, a ReLU unit has z<0z < 0 for the current input. What gradient reaches the weights that feed it?
    Quick checkWhy is backpropagation (reverse mode) used for training instead of computing each weight's derivative separately?
    Proof workshopGive the reason for each backward step

    Each line of the proof is shown in order. Choose the reason that justifies it, then press Check.

    1. ∂ℓ/∂y=y−t\partial \ell/\partial y = y - t
    2. ∂ℓ/∂h=(∂ℓ/∂y) w2\partial \ell/\partial h = (\partial \ell/\partial y)\, w_2
    3. ∂ℓ/∂z=(∂ℓ/∂h)⋅1[z>0]\partial \ell/\partial z = (\partial \ell/\partial h)\cdot 1[z > 0]
    4. ∂ℓ/∂w1=(∂ℓ/∂z) x\partial \ell/\partial w_1 = (\partial \ell/\partial z)\, x

    Layers of vectors and matrices

    For a dense layer z=Wh+bz = Wh + b with WW an m×nm \times n weight matrix, the same bookkeeping in matrix form gives, for the incoming gradient g=∂ℓ∂zg = \frac{\partial \ell}{\partial z} (an mm-vector):

    ∂ℓ∂W=g hT (m×n),∂ℓ∂b=g,∂ℓ∂h=WTg.\frac{\partial \ell}{\partial W} = g\,h^{\mathsf T}\ (m \times n),\qquad \frac{\partial \ell}{\partial b} = g,\qquad \frac{\partial \ell}{\partial h} = W^{\mathsf T}g.

    The gradient flows backwards through a layer by multiplying by the transpose WTW^{\mathsf T}. That is why the conditioning of the weight matrices (3.5) controls whether gradients explode (singular values above 1, multiplied many times) or vanish (below 1).

    Your answerA layer has WW of size 512×2048512 \times 2048. How many numbers does ∂ℓ∂W\frac{\partial \ell}{\partial W} contain?

    Where it is used

    Used inside maths· Inside maths: optimisation in many variables

    Gradient descent (5.10) moves against ∇f\nabla f; Newton’s method uses the Hessian (5.6); constrained problems add Lagrange multipliers (5.8). Each needs the derivatives this chapter computes. Chapter 5.4 proves the chain rule used here.

    Used in the real world· AI: every deep learning framework

    When you call loss.backward() in PyTorch, it walks the computational graph it recorded during the forward pass, in reverse, applying the rules above to every operation, and leaves ∂ℓ∂w\frac{\partial \ell}{\partial w} in each weight’s .grad. Training a large language model is this, repeated over trillions of tokens. The cost of a backward pass is about twice that of the forward pass, which is why “training costs about three times inference” is a standard estimate.

    Traps

    Watch out· Shapes first

    Before writing any gradient formula, write the shape of every quantity. ∂ℓ∂W\frac{\partial \ell}{\partial W} always has the shape of WW. If your formula gives another shape, a transpose is missing.

    Watch out· Gradient versus Jacobian

    For a scalar ff, the gradient is a column and the Jacobian is a row: ∇f=JfT\nabla f = J_f^{\mathsf T}. Mixing them up flips every product.

    Problems

    check

    Find ∇f\nabla f for f(x)=∥x∥2=xTxf(x) = \lVert x \rVert^2 = x^{\mathsf T}x.

    Solution

    xTIxx^{\mathsf T}Ix with II symmetric, so ∇f=2x\nabla f = 2x.

    check

    What is the shape of the Jacobian of g(x)=Wxg(x) = Wx for WW of size 3×53 \times 5, and what is it?

    Solution

    3×53 \times 5, and it equals WW: a linear map is its own best linear approximation.

    use

    Compute ∇L\nabla L for the ridge-regression loss L(x)=∥Ax−b∥2+λ∥x∥2L(x) = \lVert Ax - b \rVert^2 + \lambda\lVert x \rVert^2 and solve ∇L=O\nabla L = O.

    Solution

    ∇L=2AT(Ax−b)+2λx\nabla L = 2A^{\mathsf T}(Ax - b) + 2\lambda x. Setting it to zero: (ATA+λI)x=ATb(A^{\mathsf T}A + \lambda I)x = A^{\mathsf T}b. For λ>0\lambda > 0 the matrix is positive definite (3.2), hence invertible, even if AA has dependent columns.

    use

    In the step-through, replace ReLU by the identity (h=zh = z). Recompute ∂ℓ∂w1\frac{\partial \ell}{\partial w_1}.

    Solution

    The only change is the local derivative ∂h∂z=1\frac{\partial h}{\partial z} = 1, which was already 1 because z>0z > 0. So ∂ℓ∂w1=14\frac{\partial \ell}{\partial w_1} = 14 again. (With x=−2x = -2, ReLU would give 0 while the identity would not.)

    prove

    Prove ∇(aTx)=a\nabla(a^{\mathsf T}x) = a and use it, with the product rule, to prove ∇(xTAx)=(A+AT)x\nabla(x^{\mathsf T}Ax) = (A + A^{\mathsf T})x without coordinates.

    Solution

    ∂∂xk∑aixi=ak\frac{\partial}{\partial x_k}\sum a_ix_i = a_k. For the quadratic: xTAx=xT(Ax)x^{\mathsf T}Ax = x^{\mathsf T}(Ax); treat it as uTvu^{\mathsf T}v with u=xu = x, v=Axv = Ax. The product rule gives ∇(uTv)=JuTv+JvTu=Ax+ATx\nabla(u^{\mathsf T}v) = J_u^{\mathsf T}v + J_v^{\mathsf T}u = Ax + A^{\mathsf T}x, since Ju=IJ_u = I and Jv=AJ_v = A.

    prove

    For a dense layer z=Whz = Wh, prove ∂ℓ∂Wij=gihj\frac{\partial \ell}{\partial W_{ij}} = g_i h_j where g=∂ℓ∂zg = \frac{\partial \ell}{\partial z}, so ∂ℓ∂W=ghT\frac{\partial \ell}{\partial W} = gh^{\mathsf T}.

    Solution

    zk=∑jWkjhjz_k = \sum_j W_{kj}h_j, so ∂zk∂Wij\frac{\partial z_k}{\partial W_{ij}} is hjh_j if k=ik = i and 0 otherwise. By the chain rule, ∂ℓ∂Wij=∑kgk∂zk∂Wij=gihj\frac{\partial \ell}{\partial W_{ij}} = \sum_k g_k\frac{\partial z_k}{\partial W_{ij}} = g_ih_j, which is entry (i,j)(i, j) of ghTgh^{\mathsf T}.

    stretchalgorithms

    Multiplying a 1×n1 \times n row by an n×nn \times n matrix costs about n2n^2 operations; an n×nn \times n by n×nn \times n product costs about n3n^3. For a chain rTM1M2⋯MLr^{\mathsf T}M_1M_2\cdots M_L of LL such matrices, compare the cost of evaluating left-to-right with right-to-left.

    Solution

    Left-to-right: each step is row × matrix, so LL steps of n2n^2: about Ln2Ln^2. Right-to-left: L−1L - 1 matrix products of n3n^3 each, then one row product: about Ln3Ln^3. For n=1000n = 1000 that is a factor of 1000. Reverse-mode differentiation is the left-to-right order, starting from the scalar loss.

    Summary

    • The derivative of g:Rn→Rmg: \mathbb R^n \to \mathbb R^m is the m×nm \times n Jacobian; for a scalar function, the gradient is its transpose.
    • Rules: ∇(aTx)=a\nabla(a^{\mathsf T}x) = a, ∇(xTAx)=(A+AT)x\nabla(x^{\mathsf T}Ax) = (A + A^{\mathsf T})x, ∇∥Ax−b∥2=2AT(Ax−b)\nabla\lVert Ax - b \rVert^2 = 2A^{\mathsf T}(Ax - b). Setting the last to zero gives the normal equations.
    • Chain rule: the Jacobian of a composition is the product of Jacobians.
    • Backpropagation multiplies that product starting from the scalar loss, so all gradients cost about one forward pass. Through a layer z=Whz = Wh: ∂ℓ∂W=ghT\frac{\partial \ell}{\partial W} = gh^{\mathsf T}, ∂ℓ∂h=WTg\frac{\partial \ell}{\partial h} = W^{\mathsf T}g.
    • Check gradients numerically with a difference quotient; never train that way.

    Watch and read

    The same ideas explained by someone else. Use these when an explanation here does not land.

    Where this sits

    Comes from
    2.10 Least squares and regression as projection
    1.4 The derivative as best linear approximation
    3.5 Matrix norms, conditioning, and why numerics fail
    Leads to
    5.3 The total derivative, the Jacobian matrix and tangent planes
    5.10 Gradient descent, momentum and Newton's method
    Same idea elsewhere
    MATH 375: The chain rule for functions of several variables (Apostol 8.20 to 8.21) says the derivative of a composition is the product of the derivative matrices. Backpropagation is that rule, applied in a clever order.
    CS 240 / algorithms: Computing a product of many matrices right-to-left versus left-to-right can differ in cost by orders of magnitude; it is the matrix-chain ordering problem from algorithms courses.
    AI: Every deep learning framework (PyTorch, JAX, TensorFlow) is, at its core, an engine for this chapter: reverse-mode automatic differentiation.