A neural network makes a wrong prediction. It has millions of weights. Which way should each one move, and how sensitive is the loss to it?
You could nudge each weight a tiny bit, rerun the whole network, and see what happens to the loss. With a million weights that is a million extra forward passes, for every single training step. Backpropagation gets all of those answers in one backward pass. That pass typically costs a small multiple of one forward pass (about twice as much). That is what makes training deep networks practical.
The best way to understand it is to do it once with real numbers.
The smallest possible model
One input , one weight , one bias , and a target answer :
(“y-hat”) is the prediction and is the squared-error loss. We’ll use , , and .
The trick is to break the computation into tiny steps, one operation each, so every step is easy on its own. Each step is a node in a computation graph:
Two passes happened. The forward pass computed the values, from inputs to loss. The backward pass computed a gradient for every node: , which means “how much does change if I nudge this node a tiny bit?”. Notice that the data and also received gradients. We ignore them, because we never change data. We only update the parameters and .
The local rules
Going backward, every node did the same thing: take the gradient arriving from above and multiply it by the node’s own local derivative. That’s the chain rule, applied one node at a time. A local derivative says how a node’s output changes when one of its inputs changes, ignoring the rest of the network.
| node | local derivative(s) | so the gradient… |
|---|---|---|
| add: | for both inputs | is copied unchanged to both inputs |
| subtract: | for , for | is copied, with the sign flipped for |
| multiply: | , | is multiplied by the other input (“swap”) |
| square: | is multiplied by | |
| ReLU: | if , if (undefined at exactly 0; PyTorch uses 0 there) | passes through if , is blocked (becomes 0) otherwise |
| sigmoid: | is multiplied by that; never more than | |
| exp: | (the output itself) | is multiplied by the output |
| log: (for ) | is multiplied by |
The first four rows are all the widget used. Subtract is just add with one sign flipped. The last four are activation and helper nodes you will meet in real networks (sigmoid is introduced in P1.A5; ReLU and the other activations in P4.4). Every node, however fancy, follows the same pattern: a local derivative, multiplied by the gradient arriving from above.
Why backward, and why store the forward values?
Why in reverse order? The gradient of a node is: (gradient from the nodes that use it) × (its local derivative). So a node can only finish its gradient after every node downstream of it (closer to the loss) has finished. The loss is the end of the graph and has the simplest gradient, . So we start there and walk back. Going forward would not work: needs first, which needs , and so on.
Why must the forward pass store its values? Look at the local rules. Multiply needs the other input ( or ). Square needs . Sigmoid needs its output. ReLU needs to know whether was positive. All of these are numbers from the forward pass. So training keeps every intermediate value in memory until the backward pass has used it. This is why training needs much more memory than just running a trained model, and it is a big reason large models need big GPUs. P10.B4 counts exactly how much.
Intuition
Think of the gradient as blame: how much each value is responsible for the loss, and in which direction. The loss starts with a gradient of 1. Each node then hands a gradient back to whatever produced its inputs.
But blame is not shared out like a pie. An add node does not split the gradient between its inputs. It gives the full gradient to each of them, because nudging either input moves the sum by the same amount. A multiply node scales the gradient by the other input: if is large, a small change in has a big effect. Gradients can also be negative, so they are not “shares” that add up to the total.
The sign says which way to move. Here : increasing would decrease the loss, so gradient descent increases .
Math
Chaining the local derivatives from the loss down to :
With our numbers: . Similarly .
Backprop computes these products from the loss downward, reusing each partial result: is computed once and then used for both and . In a big network, this sharing is what makes one backward pass enough. The general version is reverse-mode automatic differentiation (P1.C10).
Code
PyTorch does all of this for you. It records the operations during the forward pass, then backward() walks the graph in reverse:
import torch
x, y = torch.tensor(2.0), torch.tensor(3.0)
w = torch.tensor(1.5, requires_grad=True)
b = torch.tensor(-1.0, requires_grad=True)
L = (w * x + b - y) ** 2 # forward pass
L.backward() # backward pass
print(L.item(), w.grad.item(), b.grad.item()) # 1.0 -4.0 -2.0Same numbers as the widget.
From gradients to learning
Backprop only measures. The last step in the widget is plain gradient descent from P1.F3: move each parameter against its gradient, scaled by the learning rate :
The new prediction is , and the loss falls from 1 to 0.25. Press “Apply update and run another round” in the widget to keep going. Training a neural network is exactly this loop, repeated: forward, backward, update.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
More than one training example
So far we had one example. Real training data has many. The loss is then the average of the per-example losses:
The gradient of an average is the average of the gradients. So: run forward and backward for each example, then average the gradients before the update. (In practice a batch of examples is used per step, and the average is over the batch.)
Example with , and two examples, and :
| example | ||||
|---|---|---|---|---|
| average |
With : and . The average loss falls from to about . The two examples pulled in different directions for ( and ). The average is a compromise.
Is my backprop correct? Gradient checking
Backprop code is easy to get subtly wrong, and wrong gradients still “run” without errors. The standard test needs no calculus. Use the idea behind the definition of the derivative: nudge a parameter up and down by a tiny and measure the slope of the loss:
This is gradient checking with finite differences. It is far too slow for training (one extra pair of forward passes per parameter, the very cost backprop avoids), but it is perfect for testing. If the two numbers disagree, your backprop has a bug. Run the cell below. It also does the batch average from the table above.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Try breaking it: change gw += 2 * e * x to gw += 2 * e (forgetting the “swap”) and watch the two lines disagree.
Go deeper Why the two-sided (central) difference, and how close is close enough?
A one-sided difference, , has an error that shrinks in proportion to . The two-sided version cancels the first error term, so its error shrinks like . That makes it more accurate for the same .
But cannot be too small: the computer rounds numbers, and subtracting two nearly equal numbers loses digits. Values around to are common choices (with 64-bit floats). Compare the two gradients by relative difference, . As a rule of thumb, tiny values (say below with 64-bit numbers) mean “agree”; a relative difference near or even means a bug. Check a few parameters, not all.
Gradient checking also cannot be trusted exactly at a kink such as ReLU at , where the true derivative is not defined.
Go deeper What if a value is used in more than one place?
Then its gradient is the sum of the gradients from each use. Here’s a quick check: take . The multiply rule says each input gets “the other input” times the incoming gradient of 1, so the two uses contribute and . Adding them gives , which is exactly the derivative of .
This matters in real networks, where one value often feeds many later computations (a hidden unit feeds every unit in the next layer). Forgetting to add these contributions is a classic bug when writing backprop by hand. It also explains a PyTorch habit: .grad accumulates (adds) every time you call backward(). So you must reset the gradients to zero before each training step (optimizer.zero_grad()), or old gradients pile up. P2.6 shows this in detail. You’ll handle the summing yourself when you build your own autograd engine in P4.9.
Go deeper What changes in a real network? (a preview)
Real layers work on vectors and matrices, not single numbers: . The method is the same: forward, then backward in reverse, each node multiplying the gradient from above by its local derivative. The multiply rule’s “swap” becomes a matrix product with a transpose, and the gradient of every weight matrix has the same shape as the matrix. The bookkeeping is more complex; the idea is not. P1.C11 covers the matrix calculus and P4.10 builds a full network this way.
Check your understanding
A multiply node computes with and . The gradient arriving from above is . What is ?
Multiply nodes swap: the gradient for w is the incoming gradient times the other input, 2 × x = 2 × 5 = 10.
An add node receives a gradient of from above. What gradients do and get?
Both local derivatives of a sum are 1, so the add node copies the full gradient, −7, to each input. It does not split it.
After the backward pass, . With learning rate , what does gradient descent do to ?
w ← w − 0.1 × (−4) = w + 0.4. A negative gradient means increasing w lowers the loss.
Why is backprop much faster than nudging each weight separately to see how the loss changes?
Nudging needs one extra forward pass per weight. Backprop computes each node’s gradient once and reuses it for every node that feeds into it, so one backward pass gives all the gradients. It still needs the forward pass first.
A ReLU node has input . The gradient arriving from above is . What gradient does it pass back to ?
The local derivative of ReLU is 0 when z is negative (the output is flat at 0 there), so the gradient is 5 × 0 = 0. ReLU blocks the gradient for negative inputs.
Exercises
- In the widget, open “Change the numbers” and set , (with , ). Before stepping, predict the loss and both gradients.
Show answer
the prediction is exactly 3, so the loss and every gradient are 0. Nothing to learn. - By hand, compute and for , , , .
Show answer
e = 3, so ∂L/∂b = 6 and ∂L/∂w = 6. - In the first code cell, change the learning rate to 0.3. What happens to the loss, and why?
Show answer
the loss goes 1, 4, 16, 64, 256: it quadruples each step. The step is so large that it overshoots the minimum by more than it started away. See the learning-rate table in P1.F3. - A sigmoid node has input and receives a gradient of from above. What does it pass back?
Show answer
, so the local derivative is , and the gradient is . - Use at . Using the rule for values used more than once, find .
Show answer
is used three times. The multiply node gives and , which is . The add node gives . They sum to . Check: . - In the second code cell, change the data to a single example . What should the gradients be?
Show answer
and , as in the widget, and finite differences should match.
Next: in P4.9 you’ll turn these rules into a tiny automatic-differentiation engine, about 100 lines of Python, that can run backprop on any expression.