Lesson 6 of 7 · Math for AI: Linear Algebra & Calculus Essentials

The Chain Rule & Backpropagation: How Gradients Flow Through a Network

A network is a long chain of small functions. The chain rule turns "how does the loss change if I nudge this one weight?" into a bookkeeping job, and backpropagation is that job done in the cheapest possible order.

M4 gave you the derivative of a single function and the finite-difference check that tests it. M5 gave you partial derivatives and the gradient: one slope per parameter, bundled into a vector. M2 gave you matrices as machines that transform vectors. This lesson joins them. A real model is dozens of layers, each feeding the next, and the slope of the loss with respect to a weight in layer 3 depends on everything downstream of it. The chain rule says how to get that slope. Backpropagation is the chain rule organized so that one sweep through the network yields the slope for every weight. The statistics course, Lesson 8 (The Statistics Behind Training a Model), described gradient descent as a walk downhill. This lesson shows where the direction of that walk comes from.

1. Composite functions and the chain rule

A composite function feeds the output of one function into another: f(g(x)). First compute the inner value u = g(x), then compute y = f(u). A neural network layer is exactly this shape, and a whole network is many of them stacked.

The chain rule says that the slope of the composite is the product of the slopes of the pieces:

dy/dx = (dy/du) × (du/dx)

Read it as a chain of exchange rates. If nudging x by 1 moves u by 3, and nudging u by 1 moves y by 14, then nudging x by 1 moves y by 3 × 14 = 42. Rates multiply.

Example: a polynomial inside a square

Let y = (3x + 1)2 and evaluate at x = 2. Name the inner piece u = 3x + 1.

u = 3x + 1 = 3(2) + 1 = 7
y = u² = 49
du/dx = 3
dy/du = 2u = 2(7) = 14
dy/dx = 14 × 3 = 42

Check with M4's finite difference: nudge x to 2.000001, get y = (7.000003)2 = 49.000042, and (49.000042 − 49) / 0.000001 = 42. The product of local slopes matches the measured slope.

Key Insight Every derivative in the chain is local. The slope of 3x + 1 knows nothing about squaring; the slope of squaring knows nothing about 3x + 1. Each piece only needs its own input and its own output. Backpropagation exploits exactly this: each layer only has to know how to differentiate itself.

2. The computational graph: forward pass and backward pass

Draw a calculation as a computational graph. Each node is one simple operation (multiply, add, sigmoid, subtract and square). Each arrow carries a value from one node to the next. A neural network's loss is one big graph.

The quantity travelling backward is the slope of the final loss L with respect to the value at that point, written ∂L/∂(value); at the loss node it starts at 1.

3. Worked example: a complete backprop by hand

Build the smallest network that still has a hidden nonlinearity: one input, one hidden unit with a sigmoid, one linear output. Sigmoid is σ(z) = 1 / (1 + e−z); it squashes any number into the range 0 to 1, and its slope is σ′(z) = σ(z)(1 − σ(z)). Suppose a team is fitting a toy score predictor on a single example and every number is fixed up front:

ItemSymbolValue
Inputx1.5
Target (what we want)t1.0
Hidden weight and biasw1, b10.4, 0.1
Output weight and biasw2, b20.9, −0.2
Learning rateη0.5

The model is z = w1x + b1, then h = σ(z), then Ŷ = w2h + b2 (the prediction, written "y-hat"), and the loss is squared error with a half in front so the derivative comes out clean: L = ½(Ŷ − t)2.

Forward pass: compute and save every value

z = w₁·x + b₁ = 0.4(1.5) + 0.1 = 0.7
h = σ(0.7) = 1 / (1 + e^−0.7) = 0.6682
Ŷ = w₂·h + b₂ = 0.9(0.6682) + (−0.2) = 0.4014
L = ½(0.4014 − 1.0)² = ½(0.3583) = 0.1792

The prediction is 0.4014 against a target of 1.0, so the loss is 0.1792. Now the graph, with the forward values on top and the backward gradients underneath:

w₁ = 0.4 grad −0.1792 b₁ = 0.1 grad −0.1195 w₂ = 0.9 grad −0.4000 b₂ = −0.2 grad −0.5986 input x 1.5 z = w₁x + b₁ 0.7 h = σ(z) 0.6682 Ŷ = w₂h + b₂ 0.4014 L = ½(Ŷ−t)² 0.1792 ∂L/∂L = 1 ∂L/∂Ŷ = −0.5986 ∂L/∂h = −0.5388 ∂L/∂z = −0.1195 (input, not trained)

The same graph carries two kinds of numbers. Blue arrows carry values forward; red arrows carry "how much does the loss care about this value" backward.

Backward pass: one local derivative at a time

Start at the loss and walk left. At each step, the gradient arriving from the right is multiplied by the local derivative of that node.

StepLocal derivativeArithmeticGradient
Loss to prediction∂L/∂Ŷ = Ŷ − t0.4014 − 1.0−0.5986
Prediction to w2∂Ŷ/∂w2 = h−0.5986 × 0.6682−0.4000
Prediction to b2∂Ŷ/∂b2 = 1−0.5986 × 1−0.5986
Prediction to hidden∂Ŷ/∂h = w2−0.5986 × 0.9−0.5388
Hidden to pre-activationσ′(z) = h(1 − h)0.6682 × 0.3318 = 0.2217; −0.5388 × 0.2217−0.1195
Pre-activation to w1∂z/∂w1 = x−0.1195 × 1.5−0.1792
Pre-activation to b1∂z/∂b1 = 1−0.1195 × 1−0.1195

The longest path shows the chain rule at full length: ∂L/∂w1 = (∂L/∂Ŷ) × (∂Ŷ/∂h) × (∂h/∂z) × (∂z/∂w1) = (−0.5986)(0.9)(0.2217)(1.5) = −0.1792. The backward pass reused −0.5986 and −0.5388 for several results; computing shared partial products once is the savings of backprop.

One gradient-descent step, and a check

All four gradients are negative: raising any parameter would lower the loss. Gradient descent (the statistics course, Lesson 8) subtracts η times the gradient, so each parameter moves up:

w₁ = 0.4 − 0.5(−0.1792) = 0.4896
b₁ = 0.1 − 0.5(−0.1195) = 0.1597
w₂ = 0.9 − 0.5(−0.4000) = 1.1000
b₂ = −0.2 − 0.5(−0.5986) = 0.0993
New forward pass: z = 0.4896(1.5) + 0.1597 = 0.8941, h = 0.7097, Ŷ = 1.1(0.7097) + 0.0993 = 0.8800
L: 0.1792 → 0.0072 (one step cut the loss by about 96%)

Never trust hand-derived gradients without the M4 test. Nudge each parameter by ±0.000001, recompute the loss, and divide the difference by 0.000002:

ParameterBackprop gradientFinite difference
w1−0.1792−0.1792
b1−0.1195−0.1195
w2−0.4000−0.4000
b2−0.5986−0.5986

They agree to about ten digits when run in code. The whole check, with no libraries:

import math
sig = lambda z: 1 / (1 + math.exp(-z))
def loss(w1, b1, w2, b2, x=1.5, t=1.0):
h = sig(w1 * x + b1)
return 0.5 * (w2 * h + b2 - t) ** 2
p = [0.4, 0.1, 0.9, -0.2]
for i in range(4):
up, dn = p[:], p[:]
up[i] += 1e-6; dn[i] -= 1e-6
print((loss(*up) - loss(*dn)) / 2e-6)
Pitfall The backward pass needs numbers saved from the forward pass (h = 0.6682 and x = 1.5 both appeared as local derivatives), so a framework keeps every layer's intermediate values in memory. That is why training needs far more memory than running a model.

4. When one variable feeds two places: sum over paths

In the tiny network every variable fed exactly one next node. Real networks branch: one value goes to two places, and both influence the loss. The multivariable chain rule says to add up the contributions along each path.

Take a variable x that feeds two nodes, u = x + 1 and v = x2, which are then multiplied: f = u × v. At x = 3:

u = 4, v = 9, f = 36
Path through u: ∂f/∂u × du/dx = v × 1 = 9
Path through v: ∂f/∂v × dv/dx = u × 2x = 4 × 6 = 24
df/dx = 9 + 24 = 33

Check: f = (x + 1)x2 = x3 + x2, so df/dx = 3x2 + 2x = 27 + 6 = 33. A finite difference at step 0.000001 also returns 33.00001.

This is common: a residual connection (section 7) sends a layer's input down two routes, and a shared embedding table receives a gradient from every position where a token appears. Whenever two gradients arrive at the same node in a backward pass, they are added.

5. The matrix form: Jacobians and why backward is cheap

The examples above have one number per node. A real layer takes a vector in and gives a vector out. The M5 gradient generalizes to the Jacobian: a matrix whose entry in row i, column j is the partial derivative of output i with respect to input j. For a layer with 1,000 inputs and 1,000 outputs, the Jacobian is a 1,000 × 1,000 matrix. (For a linear layer a = Wz from M2, the Jacobian is simply W itself.)

The chain rule for a stack of layers then reads: the Jacobian of the whole network is the product of the layer Jacobians. Only the order of multiplication is a choice, and the order decides the cost:

The difference is large. A 1,000-entry vector times a 1,000 × 1,000 matrix costs about 1,000,000 multiply-adds. Two 1,000 × 1,000 matrices cost about 1,000,000,000. Backprop keeps the left factor a vector, so it never pays the second price.

Key Insight Reverse mode is cheap because training has the shape many inputs, one scalar output: millions or billions of parameters, one loss number. A single backward pass costs roughly a small multiple of the forward pass, no matter how many parameters there are. That one fact is what made training large networks practical. The price, as the pitfall above noted, is memory for the saved forward values.

6. Vanishing and exploding gradients

The backward pass multiplies one factor per layer. A long product of numbers is dangerous: if the factors are mostly below 1 the product shrinks toward zero, and if they are mostly above 1 it blows up.

Sigmoid is the classic case. Its slope σ′(z) = σ(z)(1 − σ(z)) peaks at z = 0, where σ = 0.5 and the slope is 0.5 × 0.5 = 0.25. It is never larger. In the tiny network the slope was 0.2217, already close to that ceiling, and it shrinks quickly when z is large in either direction. Now stack layers. If each layer's weight is 1 and every sigmoid sits at its best case, each layer multiplies the gradient by at most 0.25:

Sigmoid layersBest-case gradient factorValue
50.2550.00098
100.25100.00000095
200.25209.1 × 10−13

With 10 layers, the gradient reaching the first layer is under one millionth of the gradient at the output. The early layers receive almost no signal, so they barely learn. That is the vanishing gradient problem, and it is the best case. Sigmoid slopes are at most 0.25, so this is the best case for a chain of sigmoids; large weights can offset it, which is the exploding side of the same product.

The mirror image is the exploding gradient. If each layer's factor is 1.5 instead, the product grows:

1.510 = 57.7
1.530 = 191,751
1.550 ≈ 637,621,500

A gradient that large produces a wild update, and the loss can jump to infinity or NaN. The usual remedy is gradient clipping: if the gradient's length exceeds a limit, rescale it to the limit before updating.

7. Why ReLU and residual connections help

ReLU

The ReLU activation, max(0, z), has slope exactly 1 for any positive input and 0 for a negative one. For active units the factor per layer is therefore 1 rather than at most 0.25, so a product of many such factors does not shrink just from the activation. A negative input has slope 0 and passes no gradient, so units can get stuck "dead"; and the weights still multiply in. ReLU lowers the risk but does not remove it.

Residual connections

A residual connection computes y = x + F(x), adding the input back onto the output. Differentiating gives dy/dx = 1 + dF/dx. That "+1" is the sum-over-paths rule from section 4 at work: the gradient has a direct route that skips F entirely, so even if dF/dx is tiny, the total factor stays near 1 instead of near 0. This is one reason very deep networks became trainable. It is a helpful property, not a guarantee; a deep network still needs sensible initialization and learning rates.

8. Automatic differentiation: the framework does it, you still need to know what flows

Nobody derives these equations by hand for a real model. Deep-learning frameworks track the computation as the forward pass runs, then execute reverse-mode automatic differentiation to produce every gradient. Each primitive operation ships with its own local derivative; the framework just chains them. A call like loss.backward() is the backward pass from section 3, at scale.

Knowing the mechanism still pays. A NaN gradient means look for a node with a huge local derivative. Slow early layers mean vanishing factors. Out-of-memory in training but not inference means saved forward values. A non-differentiable operation, such as rounding or a hard argmax, stops the gradient there.

9. Why this matters for building AI systems

Why This Matters Every weight in every neural network you will use was set by a gradient that backpropagation computed. The mechanism is short enough to hold in your head, and it explains many failures that otherwise look mysterious.

Debugging training

If loss does not move, print the gradient size per layer. Near-zero gradients in early layers and healthy ones late point to vanishing factors; spikes point to exploding ones. Exactly zero for a group of parameters often means something is detached from the graph.

Cost and memory

One backward pass costs a small multiple of a forward pass and needs the activations stored. That is why recomputing activations instead of storing them exists, and why fine-tuning few parameters, as LoRA does, cuts memory: frozen parameters need no stored gradient.

Leads into M7

Derivatives answer "how fast does this change?" M7 covers integrals: adding up a quantity that varies continuously. That is how a probability density becomes a probability, how an expected value over a continuous distribution is computed, and why normalizing constants appear in probabilistic models. It connects the calculus you now have back to the statistics course.

Recap

✅ Check Yourself

1. For y = (3x + 1)2, what is dy/dx at x = 2?

14, because that is the slope of the outer square at u = 7
21, because 3 × 7 uses only the inner piece
42, because dy/du = 14 and du/dx = 3 multiply

2. In the tiny network, the hidden unit's output is h = 0.6682. What is the local derivative of the sigmoid at that point, used in the backward pass?

0.2217, which is h(1 − h) = 0.6682 × 0.3318
0.6682, because the derivative of sigmoid equals its output
0.3318, because the slope is 1 − h

3. Why is reverse mode (backprop) the standard choice for training a model with millions of parameters and one loss value?

It needs one separate forward pass for every parameter, which is the cheapest approach
One backward sweep, multiplying a vector by one Jacobian at a time, yields the gradient for every parameter
It avoids storing any intermediate values from the forward pass

4. A stack of 10 sigmoid layers, each with weight 1 and each at the best-case slope of 0.25, scales the gradient reaching the first layer by about:

2.5, because 0.25 × 10
0.0025, because 0.25 ÷ 100
0.00000095, because 0.2510

5. A variable x feeds two nodes whose outputs are later combined into the loss. How does backprop combine the gradients arriving at x?

It adds the gradient from each path
It multiplies the gradients from the two paths together
It keeps only the larger of the two gradients