We have a network that produces outputs and a loss that says how wrong they are. This chapter supplies the missing piece that turns a network into something that learns. It is the most important algorithm in the book, and it is one idea you already know, used very carefully.
Who is to blame?
Gradient descent needs one thing: for every weight, the slope of the loss with respect to that weight. Given the slopes, the update is the familiar “step against the gradient”.
For a line with two parameters the slopes were easy to write down. A network is harder. A weight in the first layer affects the loss only indirectly: it changes a neuron’s output, which changes every neuron in the next layer, which changes the scores, which changes the loss. Working out its share of the blame looks daunting.
There is a brute-force way. Nudge one weight slightly, run the whole network again, and see how much the loss moved. That works, but it needs one full run of the network per weight. A network with a million weights would need a million runs to take a single step.
One neuron, forwards then backwards
Start with the smallest network there is: one input, one weight, one bias, a ReLU, and a squared-error loss. The input is 2 and the target is 5.
The forward pass computes values, left to right. The
A forward pass and a backward pass
Round 1, step 0 of 7Start: an input, a weight, a bias and a target.
- Target
- 5
- Output this round
- –
- Loss this round
- –
- Loss in earlier rounds
- –
Here is the first round, written out. Forward:
Backward, one step at a time:
| Question | Local slope | Gradient so far |
|---|---|---|
| How does the loss change with the output ? | ||
| How does change with ? | ReLU has slope 1, since | |
| How does change with the weight? | The input, 2 | |
| How does change with the bias? | 1 |
Both gradients are negative, so both the weight and the bias should increase. With a learning rate of 0.05 the weight becomes and the bias . The next forward pass gives a loss of 3.06, down from 12.25.
The rule at every step
Look at what each step of the backward pass did. It took the gradient arriving from the right, multiplied it by one local slope, and passed the result to the left. That is the whole method:
gradient passed back = gradient received × the local slope of this step
Each kind of step has its own simple local slope, and a network is built from only a few kinds.
| Step | What it does going forward | What it does going backward |
|---|---|---|
| Add a bias | Passes the gradient through unchanged | |
| Multiply by a weight | The weight receives gradient × ; the input receives gradient × | |
| ReLU | Passes the gradient where , blocks it where | |
| Softmax with cross-entropy | scores → loss | Starts the whole process with probabilities − truth |
Two details are worth pausing on. A weight’s gradient is proportional to its input: a weight attached to an input of zero receives no blame, because it had no effect on this example. And a ReLU that was off, with a negative input, blocks the gradient entirely. Nothing behind it learns from this example.
For a whole dense layer the same rules, written with matrices, are three lines:
The first two are what the layer needs to update itself. The third is what it hands back to the layer before it, which uses it in exactly the same way. Each layer only needs to know its own inputs and the gradient arriving from the layer after it. That is why the method scales to networks of any depth.
During a backward pass, a hidden ReLU neuron had a negative input on this example. What gradient do the weights feeding into it receive from this example?
Take the same tiny network, but start with a weight of −0.5. The input is 2, the bias is 0.5 and the target is 5.
Forward. . The ReLU turns that into , and the loss is .
Backward. The loss changes with at a rate of . Then comes the ReLU. Its input was negative, so its local slope is 0, and the gradient passed back is . The weight and the bias both receive a gradient of 0.
The loss is large and the update is nothing. The neuron was off for this input, so no small change to its weight would alter the output, and backpropagation correctly reports that. If a neuron is off for every example in the data it can never recover. Such neurons are called dead, and they are one reason to keep starting weights small and learning rates moderate.
Trust, but check
Backward passes are easy to get subtly wrong, and a wrong gradient often still trains, just badly. Fortunately there is an independent way to find a gradient: the slow nudging method from the start of the chapter. Too slow for training, it is perfect for testing. Comparing the two is called a
Backpropagation against brute force
- From one backward pass
- 0.207647
- By nudging w11 by 1e-3
- 0.207647
- They differ by
- 5.9e-9
- Loss of the network
- 1.7648
The two agree to several decimal places for every weight. The nudge needs two runs of the network for each number checked; the backward pass produced all 21 at once. On a network with millions of weights, that difference is the difference between seconds and years.
Every network in this book is checked this way before it is used. So is the library that draws these figures.
The training loop
Everything is now in place. Training is four steps, repeated:
- Forward pass: run a batch through the network.
- Loss: measure how wrong the outputs are.
- Backward pass: find the gradient of the loss for every weight.
- Update: move every weight a small step against its gradient.
This cycle is the
For a real test we need data no straight line can handle. Here are 300 points in three classes, arranged in interleaved spiral arms. The network has 2 inputs, one hidden layer of 32 ReLU neurons, and 3 outputs: 195 learnable numbers.
A network learning the spiral
- Class 1, and where the network predicts it
- Class 2, and where the network predicts it
- Class 3, and where the network predicts it
- Steps
- 0
- Loss
- 1.173
- Right on the 300 shown
- 32%
- Right on 300 new points
- 34%
It works, and it is slow. After 2,000 steps the loss has fallen from 1.17 to about 0.79 and the network gets 62% of the points right, up from a third. The regions are starting to curl around the arms, but the loss spends long stretches barely moving.
The network is learning, driven by nothing but the four steps above. The slowness is not a flaw in backpropagation, which is giving exact gradients. It is a flaw in how we are using them: always the same step size, in whatever direction the gradient happens to point. The next chapter fixes that, and the same network will reach 99%.
Put the four steps of the training loop in the right order.
In code
Each layer gains a backward method that mirrors its forward. The full file, code/ch17_backprop.py (run it in Colab), trains this network on spiral data.
class Layer_Dense:
def forward(self, inputs):
self.inputs = inputs # remembered for the backward pass
self.output = inputs @ self.weights + self.biases
def backward(self, dvalues):
self.dweights = self.inputs.T @ dvalues # each weight: its input times the gradient
self.dbiases = np.sum(dvalues, axis=0, keepdims=True)
self.dinputs = dvalues @ self.weights.T # handed back to the previous layer
class Activation_ReLU:
def backward(self, dvalues):
self.dinputs = dvalues.copy()
self.dinputs[self.inputs <= 0] = 0 # blocked where the input was negative
for epoch in range(10001):
dense1.forward(X) # forward pass
activation1.forward(dense1.output)
dense2.forward(activation1.output)
loss = loss_activation.forward(dense2.output, y) # loss
loss_activation.backward(y) # backward pass, last layer first
dense2.backward(loss_activation.dinputs)
activation1.backward(dense2.dinputs)
dense1.backward(activation1.dinputs)
optimizer.update_params(dense1) # update
optimizer.update_params(dense2)
Run for 10,000 epochs with plain gradient descent, the Python version climbs from a loss of 1.099 and 36% accuracy to a loss of 0.134 and 95%.
Key Takeaways
- Training needs the slope of the loss for every weight. Nudging each weight in turn is far too slow.
- Backpropagation gets all the slopes from one forward pass and one backward pass.
- At each step: gradient passed back = gradient received × local slope. That is the chain rule.
- A weight’s gradient is proportional to its input, and a ReLU that was off blocks the gradient.
- The training loop is forward, loss, backward, update. Check a new backward pass against nudging.
- Carry out a forward and a backward pass through a small network by hand.
- State the rule that every backward step follows.
- Explain why a ReLU that was off passes no gradient.
- Check a backward pass against nudging, and write the four steps of the training loop.
Exercises
Try each one before opening its solution. Getting stuck for a few minutes is where most of the learning happens.
One neuron with a ReLU: the input is 3, the weight is 1, the bias is −1, and the target is 4. The loss is the squared error. Do the forward pass, then the backward pass, then update the weight and bias with a learning rate of 0.02. What is the loss after the update?
Hint
Forward: , then , then the loss. Backward: start with and multiply by each local slope in turn.
Solution
Forward. . The ReLU leaves it at . The loss is .
Backward. The loss changes with at . The ReLU was on, so its slope is 1 and the gradient stays . For the weight, multiply by the input: . For the bias, multiply by 1: .
Update. and .
Check. The new output is , and the loss is , down from 4.
Two neurons in a chain, with no biases. The first computes and the second computes . With , , and a target of 0, the loss is . Find the gradient for , then for .
Hint
Start with how the loss changes with , which is . A weight’s local slope is the input it multiplies.
Solution
Forward. , , and the loss is 36.
Backward. The loss changes with at .
For : its local slope is its input, . The gradient is .
To go further back, find how the loss changes with : the local slope is , so . The ReLU was on, so the gradient stays 36. For the local slope is its input, , giving .
Both gradients are positive, so both weights should decrease, which makes sense: the output is 6 and the target is 0. Notice that the gradient for had to pass through on the way. That is why the old value of must be kept until the backward pass is finished.
A network has 10,000 weights. To find the gradient by nudging each weight in turn, how many forward passes are needed for one update? How many passes does backpropagation need?
Hint
Nudging needs one extra forward pass for every weight.
Solution
Nudging needs one forward pass to measure the loss as it stands, and one more for each weight: 10,001 forward passes. If each weight is nudged both up and down for a better estimate, it is 20,000.
Backpropagation needs one forward pass and one backward pass, and the backward pass costs about as much as the forward one. That is a saving of several thousand times here. For a modern network with billions of weights, it is the difference between possible and impossible.
Check the chapter’s worked example with code. The neuron computes with , and a target of 5, and backpropagation gave a gradient of −14 for the weight at . Estimate the same gradient by nudging.
Hint
Write the loss as a function of . Evaluate it just above and just below 0.5, subtract, and divide by the gap.
Solution
def loss(w, b=0.5, x=2, target=5):
a = max(0, w * x + b) # ReLU
return (a - target) ** 2
h = 1e-5
estimate = (loss(0.5 + h) - loss(0.5 - h)) / (2 * h)
print(round(estimate, 4)) # -14.0Nudging the weight up and down by a tiny amount and dividing gives −14, the same as the chain rule. When the two agree to several decimal places, the backward pass is right.
In the figure “Backpropagation against brute force”, pick a weight and compare the two numbers with a small nudge. Then make the nudge very large. Which number changes, and why is the other one unaffected?
Hint
Only one of the two methods uses the nudge at all.
Solution
With a small nudge the two numbers agree to several decimal places. With a very large nudge the nudged estimate drifts away, and the backpropagated gradient stays exactly where it was.
Backpropagation computes the slope at the point itself using the chain rule, and no nudge is involved. The nudging method measures the average slope across the gap it opened. For a small gap that is the same thing. For a large one, the loss curves within the gap and the average is no longer the slope at the point.
Going further
Why “backward”?
The gradient of the loss with respect to a layer’s output is needed by every weight in that layer and by everything before it. Starting at the loss and working backward computes each of these shared quantities exactly once and reuses it. Going forward from each weight would recompute the same later steps again and again.
Automatic differentiation
Libraries such as PyTorch and JAX do not ask you to write backward methods. They record every operation of the forward pass and replay the record backward, applying each step’s local slope automatically. It is the same algorithm as in this chapter, generalised to any calculation built from known pieces.
Vanishing gradients
The gradient reaching the first layer is a product of one local slope per layer. If those slopes are mostly smaller than 1, as they are for saturated sigmoids, the product shrinks toward zero and the early layers barely learn. This problem held deep networks back for years. ReLU, whose slope is exactly 1 when it is on, is a large part of what solved it.
References and further reading
- H. Kinsley and D. Kukieła, Neural Networks from Scratch in Python, chapters 7 to 9, nnfs.io.
- A. Karpathy and others, CS231n notes: Backpropagation, intuitions, cs231n.github.io/optimization-2.
- C. Olah, Calculus on computational graphs: backpropagation.