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). What happens to the 'slopes'?
Linear approximations compose by multiplying slopes (1.4). In many variables the slopes become matrices, and the product becomes a matrix product.Review: the chain rule
Quick checkIf A is 2×3 and B is 3×4, what is the shape of AB?
For a function g:Rn→Rm, the derivative at a point is the best linear approximation (1.4’s idea, one dimension up): g(x+h)≈g(x)+Jg(x)h, where Jg(x) is the m×nJacobian matrix whose entry (i,j) is ∂xj∂gi, the rate at which output i changes when input j is nudged. For a scalar function f:Rn→R the Jacobian is a single row, and its transpose, a column, is the gradient∇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∈Rn is the variable and everything else is constant.
Function f(x)
Gradient ∇f(x)
Why
aTx=∑iaixi
a
∂xj∂∑iaixi=aj
xTAx
(A+AT)x, which is 2Ax if A is symmetric
expand ∑i,jaijxixj and differentiate in xk
∥Ax−b∥2
2AT(Ax−b)
expand, then use the first two rows
Worked example
Derive the gradient of f(x)=xTAx by differentiating in one coordinate.
Solution.
Expand into a double sum.f(x)=∑i=1n∑j=1naijxixj. Row-times-column written out entry by entry.
Differentiate in xk. Only terms containing xk survive: those with i=k give ∑jakjxj, and those with j=k give ∑iaikxi. Product rule: xixj depends on xk through either factor; when i=j=k both contributions appear, which matches dxdx2=2x.
Recognise the sums.∑jakjxj=(Ax)k and ∑iaikxi=(ATx)k. Entry k of a matrix-vector product.
Answer.∇f=Ax+ATx=(A+AT)x. For symmetric A this is 2Ax, the matrix version of dxd(ax2)=2ax.
Worked example
Recover the normal equations of least squares by setting a gradient to zero.
Solution.
Write the loss.L(x)=∥Ax−b∥2=xTATAx−2bTAx+bTb. Expand (Ax−b)T(Ax−b); the two middle terms are equal numbers.
Gradient term by term.∇(xTATAx)=2ATAx (symmetric matrix ATA), ∇(−2bTAx)=−2ATb (first rule with a=ATb), and the constant contributes 0. The rules in the table.
Set to zero.2ATAx−2ATb=O, so ATAx=ATb. 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 for f(x)=∥x∥2=xTx, and the shape and value of the Jacobian of g(x)=Wx for W of size 3×5.
Solution.
Match a rule.xTx=xTIx, which is the second row of the table with A=I. Writing the function in the form of a known rule is the first move for every gradient.
Apply it.∇f=(I+IT)x=2x. I is symmetric, so (A+AT)x=2Ax.
Sanity check with one variable. For n=1, f(x)=x2 and f′(x)=2x. The new rule must reduce to the old one.
Jacobian shape.g:R5→R3, so Jg is 3×5. Rows are outputs, columns are inputs.
Jacobian value. Entry (i,j) of Jg is ∂xj∂∑kWikxk=Wij, so Jg=W. A linear map is its own best linear approximation.
Answer.∇∥x∥2=2x, and JWx=W (size 3×5).
Worked example
Find the minimiser of the ridge-regression loss L(x)=∥Ax−b∥2+λ∥x∥2 for A=101011, b=(1,2,3), λ=1.
Solution.
Gradient.∇L=2AT(Ax−b)+2λx. Sum of the third table row and the gradient of λxTx from the previous example.
Set to zero.(ATA+λI)x=ATb. Divide by 2 and collect the x terms.
Compute the pieces.ATA=[2112], so ATA+I=[3113], and ATb=(1+3,2+3)=(4,5). Column dot products, then add λ on the diagonal.
Solve. The determinant is 8, so x=81[3−1−13][45]=81(7,11). The inverse of a 2×2 matrix.
Answer.x=(87,811). The matrix ATA+λI is positive definite for λ>0 (3.2), so this is always solvable, even when A has dependent columns.
Your answerFor f(x,y)=3x+5y (that is, aTx with a=(3,5)), what is ∂y∂f?
The gradient of aTx is a=(3,5), so the y-component is 5.
Worked example
Prove ∇(aTx)=a, then use the product rule to prove ∇(xTAx)=(A+AT)x without expanding into sums.
Solution.
The linear rule.aTx=∑iaixi, so ∂xk∂(aTx)=ak. Only the term with i=k contains xk.
Split the quadratic. Write xTAx=uTv with u=x and v=Ax. Two vector-valued functions of x multiplied by a dot product.
Product rule for a dot product.∇(uTv)=JuTv+JvTu. Differentiate ∑iuivi in xk: ∑i(∂xk∂uivi+ui∂xk∂vi), which is entry k of JuTv+JvTu.
Jacobians.Ju=I and Jv=A. x is its own best linear approximation, and Ax is linear with matrix A.
Substitute.∇(xTAx)=ITAx+ATx=Ax+ATx.
Answer.∇(xTAx)=(A+AT)x. ■
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.
Row times column written out entry by entry.
Product rule on xixj; only terms containing xk survive.
Write the double sum before differentiating it.
Entry k of a matrix times a vector, once for A and once for AT.
You need the two sums from the derivative first.
The partial derivatives in every coordinate k, stacked as a column.
This conclusion needs the identification of both sums.
Your answerFor f(x)=xTAx with A=[2113] at x=(1,1), what is the first entry of ∇f?
Use ∇(xTAx)=2Ax for symmetric A.
A is symmetric, so ∇f=2Ax=2(3,4)=(6,8). First entry 6.
The chain rule as a product of matrices
If x↦u=g(x)↦y=f(u), then near a point
Jf∘g(x)=Jf(u)Jg(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→ℓ (a scalar loss) therefore has
∇xℓT=JℓJhL⋯Jh2Jh1,
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∂ℓ for every node v of a computational graph whose output ℓ is a scalar. It starts with ∂ℓ∂ℓ=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=w1x, h=max(0,z), y=w2h, ℓ=21(y−t)2 at x=2, w1=3, w2=−1, t=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 and ∂w2∂ℓ=−42. After one step with learning rate 0.01 the weights are w1=2.86, w2=−0.58 and the loss falls from 24.5 to about 9.3.
Worked example
Same network, but with input x=−2. What is ∂w1∂ℓ, and what has happened?
Solution.
Forward pass.z=w1x=−6, h=max(0,−6)=0, y=w2h=0, ℓ=21(0−1)2=0.5. The ReLU clips the negative value to 0.
Backward from the loss.∂y∂ℓ=y−t=−1, and ∂h∂ℓ=−1⋅w2=1. Same local derivatives as before.
Through the ReLU.∂z∂ℓ=∂h∂ℓ⋅1[z>0]=1⋅0=0. z<0, so the ReLU has derivative 0 here.
To the weight.∂w1∂ℓ=0⋅x=0. Everything upstream of a zero is zero.
Answer.∂w1∂ℓ=0: the unit is “dead” for this input, so gradient descent cannot move w1 using it. With the identity in place of ReLU the derivative would be 1⋅(−2)=−2=0.
Worked example
A dense layer has W=[130−121], input h=(1,2,3) and incoming gradient g=∂z∂ℓ=(1,−1). Find ∂W∂ℓ and ∂h∂ℓ.
Solution.
Shapes first.z=Wh has 2 entries, so g has 2. ∂W∂ℓ must be 2×3 and ∂h∂ℓ must have 3 entries. Each gradient has the shape of the thing it differentiates by.
Weight gradient.∂W∂ℓ=ghT=[1−1][123]=[1−12−23−3]. Entry (i,j) is gihj: weight Wij only affects output i, by a factor hj.
Input gradient.∂h∂ℓ=WTg=1023−11[1−1]=−211. Input hj affects every output i through Wij, so we add giWij over i, which is a multiplication by WT.
Answer.∂W∂ℓ=[1−12−23−3] (rank 1, an outer product), ∂h∂ℓ=(−2,1,1).
Worked example algorithms
A network has L=10 layers, each with an n×n weight matrix and n=1000. Compare the cost of the products rTM1⋯ML evaluated left to right and right to left.
Solution.
Left to right. Each step multiplies a row by an n×n matrix, about n2=106 operations. There are L=10 steps: about 107. A row times a matrix needs n multiplications for each of n outputs.
Right to left. The first L−1=9 steps multiply two n×n matrices, about n3=109 operations each, then a final row product: about 9×109. A matrix times a matrix needs n multiplications for each of n2 outputs.
Ratio.1079×109=900. Roughly n times cheaper, as the general count Ln2Ln3=n says.
Answer. Left to right is about 900 times cheaper here, and about n 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 / 2def loss(w1, w2, x=2.0, t=1.0): h = max(0.0, w1 * x) return 0.5 * (w2 * h - t) ** 2w1, w2, x, t = 3.0, -1.0, 2.0, 1.0# backpropagation, by handz = w1 * x; h = max(0.0, z); y = w2 * hdy = y - tdw2 = dy * hdh = dy * w2dz = dh * (1.0 if z > 0 else 0.0)dw1 = dz * xprint("backprop :", dw1, dw2)# finite differences: one extra forward pass per weighteps = 1e-6print("finite differ.:", (loss(w1 + eps, w2) - loss(w1, w2)) / eps, (loss(w1, w2 + eps) - loss(w1, w2)) / eps)# gradient descent: watch the loss fallfor 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) 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.
Pick the derivative to check. Backprop gave ∂w1∂ℓ=14 in the step-through. Every framework’s tests compare backprop against a finite difference.
Nudge the weight. With w1=3.001: z=6.002, h=6.002, y=−6.002, ℓ=21(7.002)2=24.514002. One forward pass with the weight changed by 10−3.
Form the difference quotient.0.00124.514002−24.5=14.002. The definition of the derivative (1.4), with a small h instead of a limit.
Answer.14.002≈14, matching backprop up to the 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=−6 (so the prediction y=−6 is perfect). What is ∂w1∂ℓ?
∂y∂ℓ=y−t=0, and every later derivative is a multiple of it. A perfect prediction gives zero gradient: no reason to change any weight.
Quick checkA layer computes z=Wh with W of size 4×7. What is the shape of ∂W∂ℓ?
The derivative of a scalar loss with respect to a matrix has one entry per entry of that matrix. The formula ghT is (4×1)(1×7)=4×7. A 7×4 answer means a transpose is missing.
Quick checkFor a scalar function f:Rn→R, the Jacobian Jf and the gradient ∇f are related by:
The Jacobian is 1×n (one output, n inputs) and the gradient is the n×1 column of the same partial derivatives. A Jacobian of a scalar function is not square, so it has no inverse.
Quick checkIn a network, a ReLU unit has z<0 for the current input. What gradient reaches the weights that feed it?
The ReLU's derivative is 0 for z<0, and the backward pass multiplies by it. Everything upstream gets a factor of zero, so those weights do not move for this input (a 'dead' unit).
Quick checkWhy is backpropagation (reverse mode) used for training instead of computing each weight's derivative separately?
Separately, each of n weights would need its own pass: n times the work. Reverse mode multiplies the Jacobian product starting from the single-row end, so the whole gradient costs a small constant times one forward pass.
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.
∂ℓ/∂y=y−t
∂ℓ/∂h=(∂ℓ/∂y)w2
∂ℓ/∂z=(∂ℓ/∂h)⋅1[z>0]
∂ℓ/∂w1=(∂ℓ/∂z)x
Layers of vectors and matrices
For a dense layer z=Wh+b with W an m×n weight matrix, the same bookkeeping in matrix form gives, for the incoming gradient g=∂z∂ℓ (an m-vector):
∂W∂ℓ=ghT(m×n),∂b∂ℓ=g,∂h∂ℓ=WTg.
The gradient flows backwards through a layer by multiplying by the transpose WT. 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 W of size 512×2048. How many numbers does ∂W∂ℓ contain?
It has the same shape as W: 512×2048=1,048,576. Backprop produces all of them as one outer product ghT.
Where it is used
Used inside maths· Inside maths: optimisation in many variables
Gradient descent (5.10) moves against ∇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∂ℓ 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∂ℓ always has the shape of W. If your formula gives another shape, a transpose is missing.
Watch out· Gradient versus Jacobian
For a scalar f, the gradient is a column and the Jacobian is a row: ∇f=JfT. Mixing them up flips every product.
Problems
check
Find ∇f for f(x)=∥x∥2=xTx.
Solution
xTIx with I symmetric, so ∇f=2x.
check
What is the shape of the Jacobian of g(x)=Wx for W of size 3×5, and what is it?
Solution
3×5, and it equals W: a linear map is its own best linear approximation.
use
Compute ∇L for the ridge-regression loss L(x)=∥Ax−b∥2+λ∥x∥2 and solve ∇L=O.
Solution
∇L=2AT(Ax−b)+2λx. Setting it to zero: (ATA+λI)x=ATb. For λ>0 the matrix is positive definite (3.2), hence invertible, even if A has dependent columns.
use
In the step-through, replace ReLU by the identity (h=z). Recompute ∂w1∂ℓ.
Solution
The only change is the local derivative ∂z∂h=1, which was already 1 because z>0. So ∂w1∂ℓ=14 again. (With x=−2, ReLU would give 0 while the identity would not.)
prove
Prove ∇(aTx)=a and use it, with the product rule, to prove ∇(xTAx)=(A+AT)x without coordinates.
Solution
∂xk∂∑aixi=ak. For the quadratic: xTAx=xT(Ax); treat it as uTv with u=x, v=Ax. The product rule gives ∇(uTv)=JuTv+JvTu=Ax+ATx, since Ju=I and Jv=A.
prove
For a dense layer z=Wh, prove ∂Wij∂ℓ=gihj where g=∂z∂ℓ, so ∂W∂ℓ=ghT.
Solution
zk=∑jWkjhj, so ∂Wij∂zk is hj if k=i and 0 otherwise. By the chain rule, ∂Wij∂ℓ=∑kgk∂Wij∂zk=gihj, which is entry (i,j) of ghT.
stretchalgorithms
Multiplying a 1×n row by an n×n matrix costs about n2 operations; an n×n by n×n product costs about n3. For a chain rTM1M2⋯ML of L such matrices, compare the cost of evaluating left-to-right with right-to-left.
Solution
Left-to-right: each step is row × matrix, so L steps of n2: about Ln2. Right-to-left: L−1 matrix products of n3 each, then one row product: about Ln3. For n=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→Rm is the m×n Jacobian; for a scalar function, the gradient is its transpose.
Rules: ∇(aTx)=a, ∇(xTAx)=(A+AT)x, ∇∥Ax−b∥2=2AT(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=Wh: ∂W∂ℓ=ghT, ∂h∂ℓ=WTg.
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.
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.