Lesson 3 · Building networks
Backpropagation
The problem
The trained network in the last lesson got about 94% of the validation deliveries right. Its weights came from gradient descent: start from random weights, then move every weight a little in the direction that lowers the loss. Repeat thousands of times.
Each step needs the loss's gradient: one number per weight, saying how fast the loss changes when that weight changes. The course's default network, 2-16-16-2, has 354 weights and biases. So every step needs 354 numbers.
The obvious way is to nudge each weight, one at a time, and see how the loss moves. That costs one extra forward pass per weight: 354 of them, for a single step. This lesson shows a way to get all 354 numbers for the cost of a small, fixed number of forward passes. It's the chain rule, run backwards through the network.
A network small enough to work by hand
Here is a 2-2-1 network: two inputs, two hidden units with the sigmoid, and one output. It reads one delivery with standardised inputs . The target is , meaning late.
The weights were picked so the arithmetic stays easy. We give each one a short name:
| Weight | Value | Job |
|---|---|---|
| ; | 0.5, −1; 0 | into hidden unit 1 |
| ; | −0.25, 1; −0.5 | into hidden unit 2 |
| ; | 1, −0.6; 0.3 | into the output |
That's 9 numbers to learn. In the course's notation, holds the 's and .
The output has no activation, and the loss is the squared error , the mean squared error of one example. The course's real network uses cross-entropy instead. Squared error keeps the numbers round, and backprop works the same way for any loss.
Worked example
The forward pass, by hand
Hidden sums: , and .
Backward, one step at a time
The computational graph from the chain rule lesson breaks this network into boxes. Each box does one small job: a weighted sum, a sigmoid, the squared error. Values flow left to right.
Step through the figure. The first five steps are the forward pass you worked out above. The next five go backwards, from to the weights.
Press play. The forward pass fills in values from left to right.
w₁₁, w₁₂, b₁ feed hidden unit 1; w₂₁, w₂₂, b₂ feed hidden unit 2; v₁, v₂ and c make the output.
Each box knows one thing about itself: how its output changes when one of its inputs changes. That's its local gradient, the "×" number on each edge. It needs no knowledge of the rest of the network:
- A weighted sum's local gradient for a weight is that weight's input: .
- A sigmoid's local gradient is its slope, . At , that's .
- The output's local gradient for is , and for it's .
- The squared error's local gradient is .
The backward pass starts at with gradient 1. At every box, it multiplies the gradient arriving from the right by the edge's local gradient, and passes the result left.
Worked example
The backward pass, by hand
The loss: .
All 9 gradients, from one pass backwards. Each one is a product of local gradients along the path from :
| Weight | Path from | Gradient |
|---|---|---|
| −0.5 | ||
| −0.25 | ||
| −0.25 | ||
| 0.3 | ||
| 0.15 | ||
| 0.15 | ||
| −0.5 | ||
| −0.5 | ||
| −1 |
Things to notice:
- Each gradient is a product along one path from to that weight. For it's .
- The paths share their right-hand ends. The number at is worked out once, then reused by , and . The at is reused by everything.
- The signs make sense. The output is too low (0.5, not 1). The gradient for is negative, so gradient descent raises , which raises .
This is backpropagation, or backprop: the chain rule, run from the loss back to the weights, so each shared part is worked out once. "Backprop" names the whole method. The backward pass is the part that runs right to left.
The maths
Write (delta) for the gradient of the loss with respect to a unit's weighted sum: . For the output, which has no activation, . Then the backward pass is three rules:
Read it back with the figure:
- A hidden unit's is the delta from above, times the weight that carried the unit's output up, times the unit's own slope.
- A weight's gradient is the delta at the unit it feeds, times the input it multiplies.
In a deeper network the first rule repeats, one layer at a time, from the output back to the input. Where one unit feeds several units above it, their contributions add, as paths add in the chain rule lesson.
Predict first
In a ReLU network, one hidden unit's weighted sum is −0.4 for this example. What gradient reaches the weights into that unit?
Check it three ways
How do you know the backward pass is right? Check one weight's gradient three ways:
- Nudge it. Raise the weight by a small amount , run the forward pass again, and divide the change in the loss by . This is the derivative's definition, with a small step instead of a limit.
- By hand, with the backward pass above.
- With autograd. The book's tiny autograd records the graph and runs the backward pass for you.
| 1. Nudge | L goes from 0.25 to 0.2495 when w₁₁ goes up by 0.001. change ÷ nudge = −0.4997 |
|---|---|
| 2. By hand | 2(y − t) × v₁ × σ′(z₁) × x₁ = −1 × 1 × 0.25 × 2 = −0.5 |
| 3. Autograd | L.backward(), then w₁₁.grad = −0.5 |
Nudging is off by 2.5e−4. A smaller nudge gets closer, because the loss curves. Backprop and autograd are exact.
For with a nudge of 0.001, the loss goes from 0.25 to 0.2495, so the nudge says . Backprop and autograd both say exactly.
The small gap comes from the loss curving. Over a bigger nudge, the slope changes along the way. With , the nudge says . Shrink and the gap shrinks with it. So nudging is a good check on a few weights, but it only ever gives an estimate.
Why not nudge every weight?
Nudging needs one forward pass for the starting loss, then one more per weight. Backprop needs one forward pass and one backward pass, whatever the size of the network.
Predict first
A network has about 1,000 weights. Roughly how much work does backprop need for one gradient, counted in forward passes?
Network 2-2-1: 9 weights and biases
Backprop is 4.3 times cheaper here. Counting multiplications: a forward pass takes 6, the backward pass 8.
For the course's 2-16-16-2 network, nudging costs 355 forward passes. Backprop costs about 2.9. That's about 120 times less work for every training step. For a network with a billion weights, nudging is out of the question. Backprop is how every modern network gets its gradients.
DeeperWhy the backward pass costs about two forward passesCount the multiplications in the 2-2-1 graph: each weight is used once going forward and twice coming back. · 3 min
Count the multiplications by weights in the 2-2-1 network. Ignore the additions, and the sigmoid and squared error, which are a few steps each.
Forward: each weight multiplies one number. The first layer does multiplications, and the output does 2. That's 6.
Backward: each weight is used twice.
- Once for its own gradient: . That's 6 multiplications, one per weight.
- Once to send the gradient down to its input: . Only the output layer needs this, because nothing sits below the first layer. That's 2 more.
So the backward pass does 8 multiplications against the forward pass's 6. In a big network almost every layer has a layer below it, so the ratio gets close to 2. Forward plus backward is then close to 3 forward passes, as the cost figure shows.
The trick is the reuse. Each is computed once and shared by every weight that feeds that unit. Nudging recomputes the whole network for every weight, including all the parts the weights share.
In PyTorch
The same network in PyTorch, in float64 so the numbers match the hand working exactly:
# One delivery's two standardised inputs, and its target (1 = late).
x = torch.tensor([[2.0, 1.0]], dtype=torch.float64) # (1, 2): a batch of one
t = torch.tensor([[1.0]], dtype=torch.float64) # (1, 1)
def make_net() -> nn.Sequential:
"""The lesson's 2-2-1 network, with its hand-picked starting weights."""
net = nn.Sequential(
nn.Linear(2, 2), # W1 (2×2) and b1: hidden sums z1, z2
nn.Sigmoid(), # h = σ(z)
nn.Linear(2, 1), # v1, v2 and c: the output y
).double() # float64, so the numbers match the hand working exactly
with torch.no_grad():
net[0].weight.copy_(torch.tensor([[0.5, -1.0], [-0.25, 1.0]], dtype=torch.float64))
net[0].bias.copy_(torch.tensor([0.0, -0.5], dtype=torch.float64))
net[2].weight.copy_(torch.tensor([[1.0, -0.6]], dtype=torch.float64))
net[2].bias.copy_(torch.tensor([0.3], dtype=torch.float64))
return netHere is the backward pass written out with tensors, one line per rule, and next to it the one line that does it all, loss.backward(). Autograd records the forward pass as it runs. Each result's grad_fn links back to the step that made it, and .backward() walks those links from the loss to the weights.
def backprop_by_hand(net: nn.Sequential) -> dict[str, torch.Tensor]:
"""The backward pass written out, layer by layer. No autograd."""
W1, b1 = net[0].weight.detach(), net[0].bias.detach() # (2, 2), (2,)
W2, b2 = net[2].weight.detach(), net[2].bias.detach() # (1, 2), (1,)
# Forward pass, keeping every intermediate value.
z = x @ W1.T + b1 # (1, 2): hidden sums
h = torch.sigmoid(z) # (1, 2): hidden outputs
y = h @ W2.T + b2 # (1, 1): the output
# Backward pass: each line is (gradient from above) × (local slope).
dL_dy = 2 * (y - t) # L = (y − t)², so dL/dy = 2(y − t) (1, 1)
dL_dW2 = dL_dy.T @ h # ∂y/∂v_j = h_j (1, 2)
dL_db2 = dL_dy.sum(dim=0) # ∂y/∂c = 1 (1,)
dL_dh = dL_dy @ W2 # ∂y/∂h_j = v_j (1, 2)
dL_dz = dL_dh * h * (1 - h) # σ′(z) = σ(z)(1 − σ(z)) (1, 2)
dL_dW1 = dL_dz.T @ x # ∂z_j/∂w_ji = x_i (2, 2)
dL_db1 = dL_dz.sum(dim=0) # ∂z_j/∂b_j = 1 (2,)
return {"W1": dL_dW1, "b1": dL_db1, "W2": dL_dW2, "b2": dL_db2}def backprop_by_autograd(net: nn.Sequential) -> dict[str, torch.Tensor]:
"""The same gradients from PyTorch: one forward pass, then loss.backward()."""
net.zero_grad()
loss = F.mse_loss(net(x), t) # (y − t)²: one example, so the mean is the square
loss.backward() # backprop: fills .grad on every parameter
return {"W1": net[0].weight.grad, "b1": net[0].bias.grad, "W2": net[2].weight.grad, "b2": net[2].bias.grad}W1 by hand [[-0.5, -0.25], [0.3, 0.15]] autograd [[-0.5, -0.25], [0.3, 0.15]]
b1 by hand [-0.25, 0.15] autograd [-0.25, 0.15]
W2 by hand [[-0.5, -0.5]] autograd [[-0.5, -0.5]]
b2 by hand [-1.0] autograd [-1.0]They agree to the last digit. The by-hand version uses matrix products, like dL_dz.T @ x. The aside below shows why those shapes are right.
F.mse_loss is PyTorch's squared error, averaged over the batch. With one example, it's .
To get one gradient without touching .grad, use torch.autograd.grad:
def one_gradient(net: nn.Sequential) -> torch.Tensor:
"""Just the gradient for the first layer's weights, returned rather than stored in .grad."""
loss = F.mse_loss(net(x), t)
(g,) = torch.autograd.grad(loss, net[0].weight) # a tuple, one entry per input asked for
return g # (2, 2); net[0].weight.grad is untouchedA glimpse of hooks
When training goes wrong, you often want to see the gradients inside the network, not only the weights' gradients. A hook is a function PyTorch calls for you at a set moment. Below, a forward hook on each layer attaches a tensor hook to that layer's output. During backward(), each tensor hook receives the gradient arriving at that output, .
def gradients_into_each_layer(net: nn.Sequential) -> dict[str, torch.Tensor]:
"""Hooks for debugging: record the gradient that arrives at each layer's output during backward()."""
seen: dict[str, torch.Tensor] = {}
def watch(name: str):
def forward_hook(module: nn.Module, inputs: tuple, output: torch.Tensor) -> None:
# A tensor hook runs during backward(), with dL/d(output) as its argument.
output.register_hook(lambda grad: seen.__setitem__(name, grad.detach().clone()))
return forward_hook
handles = [layer.register_forward_hook(watch(f"{i}: {type(layer).__name__}")) for i, layer in enumerate(net)]
net.zero_grad()
F.mse_loss(net(x), t).backward()
for h in handles:
h.remove() # hooks stay until removed; leave none behind
return seengradient at the output of 2: Linear: [[-1.0]]
gradient at the output of 1: Sigmoid: [[-1.0, 0.6]]
gradient at the output of 0: Linear: [[-0.25, 0.15]]These are , then , then : the numbers from the hand working, in backward order. In a deep network, checks like this find layers whose gradients have faded to almost nothing, a problem called vanishing gradients.
DigressionBackprop by hand, once, in matrix formThe three rules become two matrix products and one elementwise product, and the shapes check themselves. · 4 min
With a whole layer at once, the rules become matrix products. Write for layer 's deltas, as a column. For our network, , a matrix.
A layer's weight gradient is its deltas times its inputs, laid on their side:
The shapes: , the same shape as . That's always true. A gradient has the shape of the thing it's the gradient of.
The deltas one layer down come back through the transposed weights, then get multiplied, entry by entry, by the activation's slopes. The symbol means multiply entry by entry:
Shapes: , one delta per hidden unit. The transpose sends each delta back along the same weights that carried values forward.
The first layer's weight gradient follows the same rule as the second:
Shapes: , like . These are the table's numbers.
With a batch of examples, each and each input gets columns, and the same products add up the gradient over the batch. The PyTorch code above stores one example per row instead of per column, which is why it writes dL_dz.T @ x. In terms of Jacobians, each line multiplies a gradient row by one layer's Jacobian, without ever building the full Jacobian.
DigressionThe autograd behind these figuresAbout 120 lines of TypeScript record every step and run the backward pass. · 3 min
The figures in this course train networks in your browser with a tiny autograd. The scalar version records every step as a Value, with links to its inputs and a small function that applies its local gradient:
export class Value {
readonly id: number
data: number
grad = 0
readonly parents: Value[]
readonly op: string
label: string
/** Adds this node's gradient into its parents' gradients (the local chain-rule step). */
backwardStep: () => void = () => {}
constructor(data: number, parents: Value[] = [], op = '', label = '') {
this.id = nextId++
this.data = data
this.parents = parents
this.op = op
this.label = label
}
add(other: ValueLike): Value {
const o = toValue(other)
const out = new Value(this.data + o.data, [this, o], '+')
out.backwardStep = () => {
this.grad += out.grad
o.grad += out.grad
}
return out
}
mul(other: ValueLike): Value {
const o = toValue(other)
const out = new Value(this.data * o.data, [this, o], '×')
out.backwardStep = () => {
this.grad += o.data * out.grad
o.grad += this.data * out.grad
}
return out
}backward() sorts the graph so each node comes after its inputs, then runs those small functions from the loss back to the start. Each one adds into its inputs' grad. Adding, rather than overwriting, is what makes paths add up when one value feeds several steps.
/** Fill in `grad` for every node that feeds into this one, with d(this)/d(this) = 1. */
backward(): void {
const order = topoSort(this)
for (const v of order) v.grad = 0
this.grad = 1
for (let i = order.length - 1; i >= 0; i--) order[i].backwardStep()
}PyTorch does the same thing with whole tensors instead of single numbers, and with a hand-written local gradient for every operation it offers.
Putting it together
Backprop gives the gradient. One step of gradient descent then moves every weight against it: , with learning rate .
Worked example
One training step for the 2-2-1 network, with α = 0.1
Forward pass: and .
Every weight moved at once, each by its own amount, and the output jumped from 0.5 to 0.70, towards the target of 1. Training a network is this step, repeated: forward, backward, update. The next lesson wraps it in PyTorch's training loop, with batches of data and checks on data the network hasn't trained on.
Common misconceptions
"Backprop is how a network learns." Backprop only computes the gradient. The optimiser, here gradient descent, uses it to change the weights. The backward pass itself changes no weights.
"Backprop and autograd are different methods." Autograd is backprop done automatically. It records the graph as your code runs, then runs the same backward pass on whatever graph it recorded.
"A weight with gradient 0 doesn't matter." It means the loss doesn't change when that weight moves, for this example, right now. A ReLU that's off gives 0 for one example and a large gradient for the next.
"Each weight's gradient needs its own pass through the network." That's nudging. Backprop gets every gradient from one forward and one backward pass, because the paths share their parts.
Recap
- Gradient descent needs one gradient per weight. Nudging each weight costs one forward pass per weight; backprop costs about three in total.
- Each step of the network has a local gradient that needs no knowledge of the rest. The backward pass multiplies local gradients from the loss back to every weight.
- A weight's gradient is the delta at the unit it feeds times the input it multiplies: . A unit's delta is the delta from above times the connecting weight times the unit's slope.
- A ReLU that's off has slope 0, so on that example nothing reaches the weights before it.
- PyTorch names in this lesson:
loss.backward()and.grad,grad_fn,torch.autograd.grad,F.mse_loss,nn.Sigmoid,register_forward_hookandTensor.register_hook.