Lesson 74's chain rule handled a single chain: one link after another. A real network isn't a single chain. One weight's effect splits, reaches the loss along several routes, and the routes join up again. Backpropagation is the chain rule extended to that: work backward from the loss, multiply local slopes along each path, and where paths meet, add. Done in the right order, every slope in the network comes out of one backward pass, reusing the work already done, instead of one expensive nudge per weight. This lesson does it all by hand on a small graph, then on a network with two inputs, two hidden units and one output: nine slopes, one update, a lower loss, and PyTorch agreeing with every slope.
What you'll be able to do
Draw a calculation as a graph of small steps, and run it forward
Apply the two-clause rule: multiply along a path, add across paths
Write a backward pass line by line, and check every slope against a numerical one
Find all nine slopes of a 2-2-1 network by hand, check them against PyTorch, take one update, and see the loss fall
Quick check
Have a guess before you start. A town's income comes from tourists and from a factory, and both depend on the weather. To see how the weather affects income, what do you do with the two routes?
Use only the bigger route
Average them
Multiply the two routes' effects
Add the two routes' effects
Show the answer
Add the two routes' effects
The weather reaches income along two separate paths, so the total effect is the sum of the two.
The math: multiply along a path, add across paths
Purpose. The slope of the loss for every weight, in one backward pass.
Write a calculation as a graph: each node is a small step, and an arrow says one value feeds another. Take z, which depends on x and y, which both depend on t:
x=t2,y=3t,z=x⋅y
To find dz/dt, follow every path from t to z. Along each, multiply the local slopes; then add the paths:
dtdz=∂x∂zdtdx+∂y∂zdtdy=y⋅2t+x⋅3
In plain words: multiply along a path, add across paths. At t = 2: x = 4, y = 6, so dz/dt = 6 × 4 + 4 × 3 = 36.
Quick check
From lesson 74: y = (2x)², and x = 1. What is dy/dx?
8
2
4
6
Show the answer
8
u = 2x = 2; dy/du = 2u = 4 and du/dx = 2, so dy/dx = 8. That's one path; this lesson adds the case of several.
The picture. Here's that graph in the flow, with the 3 as an input of its own, c. 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 shows its local slope (×). Watch t: its slope arrives in two pieces that add. The code's PyTorch tab does the whole backward pass with one call, z.backward().
Try it now
At t = 1 the same two paths give 3 + 6 = 9, which matches z = 3t³ and its slope 9t².
Symbols and formula. For a node v feeding several later nodes u₁, u₂, …, its slope collects one term per child:
∂v∂L=k∑∂uk∂L⋅∂v∂uk
In plain words: each child passes back its own slope times its local slope with respect to v, and v adds them.
Why backward? Work from the loss toward the inputs and every node's slope is ready before any node that needs it: ∂L/∂u is known by the time v asks for it. Each local slope is computed once and reused by every path through it. That reuse is what makes backpropagation cheap: one backward pass costs about as much as one forward pass, however many weights there are.
Quick check
v feeds two nodes: one passes back ∂L/∂u₁ × ∂u₁/∂v = 3, the other 5. What is ∂L/∂v?
8
15
5
4
Show the answer
8
Across paths, slopes add: 3 + 5 = 8.
In your own words
In your own words: why do slopes multiply along a path but add across paths?
Write a sentence or two, then compare it with a good answer in the lesson.
In Python: forward, then backward, line by line
Purpose. Store every forward value, then write one backward line per local slope.
t = 2.0
x = t ** 2
y = 3 * t
z = x * y
dz_dx = y
dz_dy = x
dz_dt = dz_dx * (2 * t) + dz_dy * 3print(z, dz_dt)
deff(t):
return (t ** 2) * (3 * t)
h = 0.000001print(round((f(t + h) - f(t - h)) / (2 * h), 4))
It runs right here in your browser, with nothing to install.
The backward lines read the stored values: ∂z/∂x is y and ∂z/∂y is x, exactly what the forward pass kept. The last line adds the two paths. The numerical slope agrees: 36.
Code flow. That cell adds both paths in one line. For a graph of any size, a backward pass is written one line per slope: each slope is the slope of the step it feeds times one local slope, and a value that feeds two steps starts at 0 and adds one term per path. Here is that cell's backward pass written that way. Step through it and watch dz_dt.
A named mistake: overwriting a slope instead of adding. Had line 10 been dz_dt = dz_dx * (2 * t), it would throw away the path through y, and the slope would match one path only. Starting every slope at 0 and always adding, as lines 8 to 10 do, makes the rule automatic.
Check every slope. A backward pass written by hand is easy to get subtly wrong. Nudging each input and comparing (lesson 78's numerical gradient) checks every slope at once. Libraries use exactly this, called a gradient check, to test their own backward passes.
Worked example
Worked example: a backward pass with a branch
u = w·x feeds the loss twice: L = (u − 3)² + u. Find dL/dw at w = 2, x = 1, adding u's two contributions.
w, x = 2.0, 1.0
u = w * x
L = (u - 3) ** 2 + u
dL_du = 0.0
dL_du = dL_du + 2 * (u - 3)
dL_du = dL_du + 1
dL_dw = dL_du * x
print(L, dL_du, dL_dw)
deff(w):
u = w * x
return (u - 3) ** 2 + u
h = 0.000001print(round((f(w + h) - f(w - h)) / (2 * h), 4))
In the lesson you can change this and run it.
u feeds the square term, whose local slope is 2(u − 3) = −2, and the plain + u, whose slope is 1. Starting dL_du at 0 and adding each gives −1. Then dL/dw = −1 × x = −1, and the numerical check agrees. Had the second line been dL_du = 1, the answer would have been +1: a confident, wrong sign.
Quick check
What does this print?
a = 3.0
b = a * a
c = a + b
dc_db = 1
dc_da = 1 + dc_db * 2 * a
print(c, dc_da)
12.0 1.0
9.0 7.0
12.0 6.0
12.0 7.0
Show the answer
12.0 7.0
c = 3 + 9 = 12. a reaches c directly (slope 1) and through b (slope 1 × 2a = 6): 1 + 6 = 7.
Drill
Add across the paths
For y = 4p and z = p·y, the starter's backward pass overwrites p's slope. Fix it so dz_dp adds both paths, then set check_ok to whether it matches the central difference at p = 1.5 to 4 places.
p = 1.5
y = 4 * p
z = p * y
dz_dy = p
dz_dp = y
dz_dp = dz_dy * 4deff(p):
return p * (4 * p)
h = 0.000001
check_ok = Falseprint(z, dz_dp, check_ok)
In the lesson, your code is checked as you write it.
In your own words
Why is backpropagation much cheaper than nudging every weight?
Write a sentence or two, then compare it with a good answer in the lesson.
In AI and ML: a 2-2-1 network by hand
Purpose. Every slope of a small network, checked against PyTorch, then one update and a lower loss.
Two inputs x = (1, 2), two hidden relu units, one output, target y = 1. The forward pass:
z=W1x+b1,a=relu(z),o=w2⋅a+b2,L=(o−y)2
In plain words: a layer, a relu, a single output neuron, and a squared error: 4 + 2 + 2 + 1 = 9 weights.
The backward pass, from the loss down: dL/do = 2(o − y); then the output layer's weights and the hidden values; then through each relu; then the first layer's weights.
import numpy as np
x = np.array([1.0, 2.0])
y = 1.0
W1 = np.array([[0.5, -0.2], [0.3, 0.4]])
b1 = np.array([0.1, -0.1])
w2 = np.array([0.6, -0.5])
b2 = 0.2
z = W1 @ x + b1
a = np.maximum(0, z)
o = w2 @ a + b2
L = (o - y) ** 2print(z.round(4).tolist(), round(o, 4), round(L, 4))
do = 2 * (o - y)
dw2 = do * a
db2 = do
da = do * w2
dz = da * (z > 0)
dW1 = np.outer(dz, x)
db1 = dz
print(dw2.round(4).tolist(), round(db2, 4), dW1.round(4).tolist(), db1.round(4).tolist())
(z > 0) is True or False for each unit; multiplying by it keeps the slope where the relu was on and zeros it where it was off. np.outer(dz, x) (lesson 61) makes all four first-layer slopes at once: each is dzᵢ × xⱼ.
The picture. Here is the network with the cell's numbers. Press Next to walk it backward: the circles hold values, then slopes, and the arrows hold weights, then each weight's slope.
Quick check
In that network, why is each first-layer slope dzᵢ × xⱼ?
The weights all happen to be equal
Relu doubles every slope it passes
xⱼ is the loss of the whole network
W1ᵢⱼ scales xⱼ into zᵢ: slope xⱼ × dzᵢ
Show the answer
W1ᵢⱼ scales xⱼ into zᵢ: slope xⱼ × dzᵢ
Each weight W1ᵢⱼ touches only zᵢ, scaled by xⱼ. The slope arriving at zᵢ, dzᵢ, times that local slope xⱼ, gives it.
In PyTorch. PyTorch builds this same graph for you as the forward pass runs, recording every step that depends on a tensor made with requires_grad=True. L.backward() then runs the backward pass, with the same local slopes and the same add-across-paths rule, and leaves each weight's slope in its .grad:
import torch
x = torch.tensor([1.0, 2.0])
y = 1.0
W1 = torch.tensor([[0.5, -0.2], [0.3, 0.4]], requires_grad=True)
b1 = torch.tensor([0.1, -0.1], requires_grad=True)
w2 = torch.tensor([0.6, -0.5], requires_grad=True)
b2 = torch.tensor(0.2, requires_grad=True)
z = W1 @ x + b1
a = torch.relu(z)
o = w2 @ a + b2
L = (o - y) ** 2
L.backward()
print(w2.grad, b2.grad)
print(W1.grad)
print(b1.grad)
Every .grad is a slope you found by hand: the same nine numbers as the NumPy cell's second line, printed PyTorch's way with four decimals. To find them, PyTorch keeps the forward values each local slope needs until the backward pass has used them, which is why training takes more memory than running a model.
One update, and the loss falls. With all nine slopes in hand, and PyTorch agreeing on each, step every weight against its own slope with η = 0.1 and run the forward pass again:
The loss drops from 1.3924 to 0.0015 in one step. That's one iteration of training, done completely by hand.
Quick check
The network's forward pass at x = (1, 2). What does this print?
import numpy as np
x = np.array([1.0, 2.0])
W1 = np.array([[0.5, -0.2], [0.3, 0.4]])
b1 = np.array([0.1, -0.1])
w2 = np.array([0.6, -0.5])
a = np.maximum(0, W1 @ x + b1)
o = w2 @ a + 0.2print(np.round(a, 4).tolist(), round(o, 4), round((o - 1) ** 2, 4))
[0.0, 1.0] -0.18 1.3924
[0.2, 1.0] -0.18 1.3924
[0.2, 1.0] 0.18 0.6724
[0.2, 1.0] -0.18 1.18
Show the answer
[0.2, 1.0] -0.18 1.3924
Both hidden units are on, giving 0.2 and 1.0. The output is 0.12 − 0.5 + 0.2 = −0.18, and the loss is (−1.18)² = 1.3924.
Drill
The network, with a new input
Change the input to x = (2, 1) and redo the forward and backward passes. Set o to the output, dw2 to the output-layer slopes as a list, and dW1 to the first-layer slopes as a list of lists, all rounded to 4 places.
import numpy as np
x = np.array([2.0, 1.0])
y = 1.0
W1 = np.array([[0.5, -0.2], [0.3, 0.4]])
b1 = np.array([0.1, -0.1])
w2 = np.array([0.6, -0.5])
b2 = 0.2
o = 0
dw2 = []
dW1 = []
print(o, dw2, dW1)
In the lesson, your code is checked as you write it.
In your own words
Which slope in the network would be exactly 0 if a hidden unit's z were negative, and why?
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