The rules of lesson 73 handle sums of powers. Real formulas are built differently: one function inside another, like (3x + 1)², or two multiplied together. A neural network is the extreme case, a long chain of small steps, each feeding the next. The chain rule says how to get the slope of the whole chain from the slopes of its links: multiply them. That one sentence is backpropagation, the algorithm that trains every neural network, and by the end of this lesson you'll use it to find how a neuron's loss changes with its weight, one link at a time.
What you'll be able to do
Differentiate a product with the product rule: (fg)′ = f′g + fg′
Differentiate a chain of functions by multiplying the local slopes: dy/dx = dy/du × du/dx
Compute a chain forward, then its slope backward as a product, and check it numerically
Find dL/dw for one neuron, x → z → a → L, as a product of three local slopes, and read every link's slope from PyTorch
Quick check
Have a guess before you start. A gear turns 3 times for each turn of the handle, and a wheel turns 2 times for each turn of the gear. How many times does the wheel turn for each turn of the handle?
5
3
1.5
6
Show the answer
6
Rates through a chain multiply: 3 × 2 = 6. That's the chain rule.
The math: products and chains
Purpose. Slopes of functions built from other functions.
The product rule. When two functions are multiplied, each takes a turn changing while the other holds:
(fg)′=f′g+fg′
In plain words: the slope of the first times the second, plus the first times the slope of the second.
For x²·(3x + 1) at x = 2: 2x·(3x + 1) + x²·3 = 4 × 7 + 4 × 3 = 40. A named mistake is multiplying the two slopes, 2x × 3 = 12, which is wrong.
Quick check
From lesson 20: if f(x) = 3x + 1 and g(u) = u², what is g(f(2))?
49
13
7
14
Show the answer
49
f(2) = 7, then g(7) = 49. The chain rule finds the slope of exactly this kind of machine-inside-a-machine.
The chain rule. For y = (3x + 1)², name the inside u = 3x + 1, so y = u². Each link has a slope: dy/du = 2u and du/dx = 3. The slope of the whole chain is their product:
dxdy=dudy×dxdu
In plain words: how fast y changes with x = how fast y changes with u, times how fast u changes with x.
At x = 1: u = 4, so dy/dx = 2 × 4 × 3 = 24. The named mistake here is dropping the inner factor, giving 2u = 8: that forgets that u itself changes 3 times as fast as x.
A neuron is a chain: x and w make z = w·x + b, then a = relu(z), then the loss L = (a − y)². The flow runs it forward, then sends slopes backward, multiplying at each link.
The picture. Each circle is a value, and each arrow carries it to the step that uses it. Forward, each value is written in its circle. Backward, each slope is written under its circle (∂), and the arrow it came back along keeps its local slope (×). Follow the arrows from L back to w: the slope that reaches w is the local slopes along the way, multiplied. The code's PyTorch tab does the whole backward pass with one call, L.backward().
Try it now
The slope column fills from the bottom up, and the picture writes each slope under its circle: each one is the slope after it times a local slope. Had w been −1, z would be negative, relu's slope 0, and every slope behind it 0.
Symbols and formula. For a chain of three, the slopes of all three links multiply:
y=f(g(h(x)))⇒dxdy=f′(g(h(x)))⋅g′(h(x))⋅h′(x)
In plain words: each link's slope is taken at the value flowing into it, and they all multiply.
For y = 3(2x + 1)² + 5: u = 2x + 1, v = u², y = 3v + 5. At x = 1, u = 3, so dy/dx = 3 × 2u × 2 = 3 × 6 × 2 = 36. Each local slope is easy; the chain rule just strings them together.
Quick check
y = e^(2x). What is dy/dx at x = 0?
1
e²
2
0
Show the answer
2
Outer: eᵘ has slope eᵘ = e⁰ = 1. Inner: 2x has slope 2. Product: 2.
In your own words
In your own words: why do the slopes of a chain multiply rather than add?
Write a sentence or two, then compare it with a good answer in the lesson.
In Python: forward, then backward
Purpose. Compute a chain's value step by step, then its slope as a product, and check it.
x = 1
u = 3 * x + 1
y = u ** 2
dy_du = 2 * u
du_dx = 3print(y, dy_du * du_dx)
deff(x):
return (3 * x + 1) ** 2
h = 0.000001print(round((f(x + h) - f(x - h)) / (2 * h), 4))
It runs right here in your browser, with nothing to install.
The forward pass computes and keeps each intermediate value, u and y. The backward pass uses them for the local slopes, 2u and 3, and multiplies. The central difference from lesson 73 agrees: 24.
Code flow. The same two passes on a longer chain, the math part's y = 3(2x + 1)² + 5 at x = 1. Forward, each value is appended to a list as it's made: x, then u, then v = u², then y. Backward, local holds the three link slopes from the output back to x, dy/dv = 3, dv/du = 2u and du/dx = 2, and the loop multiplies them into slope, which starts at 1. Step through and watch slope grow one link at a time.
Why keep the forward values? Each local slope is taken at the value flowing into its link: 2u needs u. So the forward pass stores them, and the backward pass reads them. That's exactly what deep-learning libraries do, and why training needs extra memory: every layer's values are kept until its slopes have been computed.
A named mistake: the slope at the wrong point. Writing dy/du = 2x instead of 2u takes the outer slope at the input x rather than at the inner value u. The numerical check catches it at once.
Worked example
Worked example: three chains, checked
For three chains, compute the slope at a point as a product of local slopes, and compare with a central difference.
Each line puts the chain rule's product next to the measured slope. (x² + 1)³ gives 3u² × 2x = 12 × 2 = 24. e^(x²) gives e^(x²) × 2x = 2e ≈ 5.4366. 3(2x + 1)² + 5 gives 36, as worked above. Agreement on all three is good evidence each chain was split into links correctly.
Quick check
What does this print?
x = 2
u = x ** 2
y = 5 * u
print(y, 5 * (2 * x))
4 20
20 10
20 20
20 5
Show the answer
20 20
Forward: u = 4, y = 20. Backward: dy/du = 5 and du/dx = 2x = 4, so dy/dx = 20.
Drill
A chain's slope, two ways
For y = (2x − 3)⁴, fix chain(x) so it returns dy/dx as a product of local slopes. Then set agree to whether it matches the central difference at x = 2 to 4 places.
deff(x):
return (2 * x - 3) ** 4defchain(x):
u = 2 * x - 3return4 * u ** 3
h = 0.000001
agree = Falseprint(chain(2), agree)
In the lesson, your code is checked as you write it.
In your own words
Why does the backward pass need the values from the forward pass?
Write a sentence or two, then compare it with a good answer in the lesson.
In AI and ML: backpropagation in one line
Purpose. The slope of a neuron's loss with respect to its weight.
One neuron with a relu and a squared error is a chain of three links, and the chain rule gives the slope of the loss with respect to w:
In plain words: twice the error, times 1 if the neuron was on (0 if it was off), times the input.
w, x, b, y = 2, 1.5, 0.5, 2.5
z = w * x + b
a = max(0, z)
L = (a - y) ** 2
dL_da = 2 * (a - y)
if z > 0:
da_dz = 1else:
da_dz = 0
dz_dw = x
print(z, a, L, dL_da * da_dz * dz_dw)
The neuron outputs 3.5 when 2.5 was wanted, so ∂L/∂w = 2 × 1 × 1.5 = 3: lower w. ∂ ("partial") is used because L depends on several inputs; lesson 77 explains it.
In PyTorch. You met requires_grad, backward() and .grad in lesson 72. Here is the same neuron. PyTorch notes each link as the forward lines run, and L.backward() multiplies the local slopes back from L. It keeps a slope only for the tensors made with requires_grad=True, here w and b. The middle values z and a drop theirs once they've been passed on, to save memory, so .retain_grad() asks PyTorch to keep them:
import torch
w = torch.tensor(2.0, requires_grad=True)
b = torch.tensor(0.5, requires_grad=True)
x, y = 1.5, 2.5
z = w * x + b
a = torch.relu(z)
L = (a - y) ** 2
z.retain_grad()
a.retain_grad()
L.backward()
print(z.item(), a.item(), L.item(), w.grad.item())
print(a.grad.item(), z.grad.item(), b.grad.item())
The first line matches the plain Python cell above: z = 3.5, a = 3.5, L = 1.0 and ∂L/∂w = 3. The second reads the chain link by link. ∂L/∂a = 2(a − y) = 2. The neuron is on, so relu passes that 2 to z unchanged. b's own link has slope 1, so ∂L/∂b is 2 too, while w's link multiplies by x = 1.5 to give 3. Lesson 82 opens up how PyTorch keeps that record.
Quick check
A neuron's z is −1.5, so relu outputs 0. What is ∂L/∂w?
0: relu's slope is 0 when it's off
The error times the input x
1
It can't be computed
Show the answer
0: relu's slope is 0 when it's off
∂a/∂z is 0 for negative z, and one zero factor makes the whole product 0: the weight gets no signal.
Dead neurons. That zero is a real effect. A neuron whose z stays negative for every example gets ∂L/∂w = 0 every time, so its weights never change: it's "dead". Variants like leaky relu (lesson 71) keep a small slope for negative z so that some signal always gets through. Seeing the chain as a product of slopes makes problems like this, and their fixes, easy to understand.
Longer chains, same rule. A deep network is the same chain with more links: input, layer, activation, layer, activation, and so on, to the loss. The slope of the loss with respect to a weight deep inside is the product of every link's slope between that weight and the loss. That product is why very deep networks can have trouble: many slopes below 1 multiply to almost nothing, so early layers learn slowly. This is the vanishing-gradient problem, and relu, whose slope is exactly 1 when on, was adopted partly to ease it in deep networks.
Quick check
A neuron's z comes out negative. What does this print?
w, x, b, y = -1.0, 2.0, 0.5, 1.0
z = w * x + b
a = max(0, z)
relu_slope = 0if z > 0:
relu_slope = 1print(z, a, relu_slope)
1.5 1.5 1
-1.5 0 0
-1.5 -1.5 1
-1.5 0 1
Show the answer
-1.5 0 0
z = −2 + 0.5 = −1.5, so relu outputs 0 and its slope is 0: every slope behind it is 0 too.
Drill
All three local slopes
For the neuron below, set dL_da, da_dz and dz_dw to its three local slopes, and dL_dw to their product. Then set dL_db: ∂z/∂b is 1, so it's the same chain with the last factor 1.
w, x, b, y = 0.5, 4, -1, 2
z = w * x + b
a = max(0, z)
dL_da = 0
da_dz = 0
dz_dw = 0
dL_dw = 0
dL_db = 0print(z, a, dL_dw, dL_db)
In the lesson, your code is checked as you write it.
In your own words
Why is ∂L/∂b the same as ∂L/∂w except for the last factor?
Write a sentence or two, then compare it with a good answer in the lesson.
31Formulas with fractions: clear them firstFreeClearing denominators, cross-multiplying, a letter in the bottom, and reciprocal formulas like 1/R = 1/R₁ + 1/R₂.35 min
37Inverse functions, lines and scalingFreeUndoing a function by making x the subject, domains that allow it, line forms, and unscaling predictions.40 min
38Sequences and sums: find n, a, d and rFreeEvery letter of the arithmetic and geometric formulas as the subject, and an average's window from its decay.40 min
40Review: rearrange anything (algebra)FreeBroken rearrangements to fix, mixed practice from the whole algebra block, a strategy chart, and its formula sheet.35 min
41Coordinates and distanceFreePoints as (x, y), Pythagoras, distance in any number of coordinates, and nearest neighbors.42 min
42Angles, degrees and radiansFreeMeasuring a turn, converting units, arcs, and the angle between two arrows.36 min
43Sine and cosineFreeAcross and up: right triangles, the unit circle, and directions and rotations.42 min
44Waves: height, speed and shiftFreeAmplitude, period and phase, sampling a wave, and position codes in transformers.37 min
68Vector equations: rearranging with arrowsFreeSolving for a vector or a scale, recovering a gradient from two weight snapshots, and an angle from a dot product.40 min
87Counting: choices, orders and groupsFreeThe counting principle, factorials, ordered picks and groups, and why attention's cost grows with the square of the length.43 min
88Probability: from counts to chancesFreeEqually likely outcomes, the complement, distributions, seeded simulation, and a next-word model.43 min
89Combining events: and, or, independentFreeThe or rule, independence, probability trees, drawing with and without replacement, and chains of steps.42 min
100Maximum likelihoodFreeLikelihoods as products, log-likelihoods as sums, grid search, underflow, and the negative log-likelihood loss.45 min
101Linear regression: the best lineFreeResiduals, least squares by formula, three roads to one line, the matrix form, and train versus test error.45 min
109One neuron, start to finishFreeWeighted sum, activation, loss, slopes and update, by hand and in code, and what one straight line can and can't split.45 min
111Training a small networkFreeThe backward pass in matrix form, gradient checks, a full training loop, and reading loss curves.45 min
112The same network in PyTorchFreenn.Sequential with the NumPy weights loaded, the same loss and slopes, then SGD and mini-batches.45 min
113Attention as matrix mathFreeScaled dot-product scores, the causal mask, a row-by-row softmax, and blending value vectors.45 min
114Residual connections and layer normFreeAdding the input back and why its slope keeps learning alive, layer norm by hand, and add and norm.40 min
115A transformer block, start to finishFreeA sentence through embeddings, attention, add and norm, a small network and next-word scores, every shape named.45 min
117Final test: transpose any formulaFreeSlips to fix from every topic, mixed practice of every kind of rearranging, the strategy chart and the full sheet.45 min
Learn the math behind AI from arithmetic up: numbers, algebra, vectors and matrices, calculus, probability and statistics, each shown as numbers moving and checked in Python, ending with a network you build and train from the formulas.
See the course →
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write