A network has just made a wrong prediction. The loss is one number. Inside the network are thousands, or millions, of weights, and training has to change them so that the next loss is smaller. But which weights are to blame for this mistake, and by how much?
This is the credit-assignment problem (or blame-assignment problem). A weight near the input and a weight near the output both affect the result, through different routes, and nobody told the network which one did the damage. Backpropagation answers the question for every weight at once, by sending the blame backward from the loss through the network in a single sweep.
This lesson builds the picture with small numbers. P4.8 then follows every number through a complete example, and P4.9 turns the rules into code.
A network small enough to see
Two inputs, two hidden units and one output, written as formulas (a hidden unit adds up its weighted inputs, then squashes the sum with the sigmoid ; P4.3 and P4.4 introduce these units in full):
Here is the weight from input into hidden unit , and is the weight from hidden unit to the output. We leave out biases to keep the picture small (a bias is a weight whose input is always 1). That makes 6 weights. Take the input , the target , and the weights , , , , , .
Going forward: , , , , so and the loss is . The prediction is far from the target . Which of the 6 weights should change, in which direction, and how much?
What “blame” means: the gradient
The answer for one weight is its gradient (P1.C4, P1.C5): how much the loss changes per unit change of that weight, with all other weights held fixed. It carries two pieces of information:
- the sign gives the direction: a negative gradient means that raising the weight lowers the loss;
- the size says how sensitive the loss is to that weight right now.
For this network (you will see where it comes from below). So raising by should change the loss by about , a small drop. In this lesson we call the gradient of a value its blame: a large size means that nudging it matters a lot, and the sign says which way to nudge.
The slow way: nudge and re-run
Here is a method that needs no new ideas. To find the blame of , change by a tiny amount , run the whole network forward again, and see how much the loss moved. Divide by . This finite-difference method (P1.C2, P1.C4) works, and it gives the right answer. (Nudging in both directions, which is more accurate, costs two passes per weight.)
The cost is the problem. Every weight needs its own nudge and its own forward pass:
- 6 weights: 6 extra forward passes;
- a network with a million weights: a million extra forward passes;
- and that is for one training step. Training takes many steps.
Real networks cannot be trained this way. We need all the blames from a cost that does not grow with the number of weights.
The key idea: rates multiply along a path
Take a short chain. A value goes into one step, , and then another, . At : and .
Nudge up by a tiny amount. The first step makes move 3 times as much as . The second step, at , makes move times as much as . So moves times as much as : the rates multiply. This is the chain rule (P1.C3). A check by nudging: at we get and , a rise of , which is about .
An everyday picture is a chain of currency exchanges. If one dollar buys 3 euros and one euro buys 12 yen, one dollar buys yen. P1.C3 used gears for the same idea. Where does the picture break? Exchange rates stay fixed, but the rate of a step in a network depends on where you stand, for example the above used , and it is only right for tiny nudges. Also, real exchange rates are positive, while a rate here can be negative (the output goes the other way), or zero (then nothing gets through, and the whole product is zero).
Now the useful part. Start at the end and walk back. The loss has blame . One step back, has blame . One more step back, has blame . Each step back multiplies by one more rate, and every value on the way gets its blame as a by-product. In a network, the weights sit at different depths along many paths. Walking back from the loss once shares the work among all of them. Starting from each weight and walking forward would repeat the shared part of every path again and again, which is the nudging cost in disguise.
Forward, then backward, on a graph
To do this for any computation, write it as a computation graph (P1.C10): one box for each small calculation, with arrows for the values passed on. Then:
- Forward pass. Compute the values from the inputs to the loss, and store them, because the backward pass will need them.
- Backward pass. Start at the loss with blame . Go through the boxes in reverse order. Each box takes the blame arriving from above, multiplies it by its local rate, and hands the result to its inputs.
A local rate says how a box’s output changes when one input changes, ignoring everything else. Three kinds of box cover most of what you will meet. (P4.8 gives the full table and the exact derivative rules.)
- Add copies the blame to each input, unchanged.
- Multiply swaps: each input gets the blame times the other input.
- A nonlinearity, such as the sigmoid or ReLU, scales the blame by its slope at the value it was given. The sigmoid’s slope is never above . ReLU’s slope is or .
One more rule handles branching: if a value is used in more than one place, the blames from each use add up.
In our network a hidden unit hides an add and some multiplies inside one box. For a weight, the rules reduce to this: its blame is the blame at the sum it feeds, times the value it multiplied.
Below is the graph of our network. Play it, or press Step one at a time. Values go forward in blue. Blame goes backward in orange, and the thicker an edge, the larger the blame it carries. The table lists each weight with its gradient.
Things to try:
- Press Play and watch the blue values go forward, then the orange blame come back. Which weight gets the loudest blame, and which the quietest?
- Run the nudge test on with , then on . The real change in the loss should be close to gradient . Then try and .
- Move the Output weight slider to . Which gradients become , and why?
Reading the numbers
The widget’s default numbers give the following, from the loss backward:
- Square. . The prediction is too low, so raising would lower the loss.
- Output sum (multiply swaps). The blame on is , and on it is . Each hidden unit receives the blame times its output weight: for and for . The signs differ, because is negative: raising would push down.
- Sigmoids (scale by the slope). The slopes are and , so the blame on is and on it is .
- First-layer weights (multiply swaps). The blame on is and on it is . For unit 2: gets and gets .
- A value used twice. The input feeds both hidden units, so its blame is the sum of two blames: . (Inputs are data, so we do not use this number. The same rule matters for a hidden value that feeds many units.)
Two things to notice. The blame got smaller as it passed the sigmoids, because their slope is at most : a preview of a problem in deep networks (P4.16). And the smallest weight in the network by size, , has a blame of larger size () than (). The size of a weight says little about the size of its blame. The blame depends on the input the weight multiplies and on the route to the loss.
What the blame is used for
Backpropagation measures. The next step uses the measurements. Gradient descent (P1.F3) moves each weight against its gradient, . With a learning rate , one step on all 6 weights lowers the loss in this example from to about . Training repeats three steps: forward pass, backward pass, update. Optimizers such as momentum and Adam (P4.13) change the update step, but they take the same gradients.
Why one backward sweep is cheap
- Shared work. The blame at is computed once and used for all the weights below it. The blame at serves and . In a deep network, the blame at each layer is computed once and reused by everything in the layers beneath. Nothing is recomputed per weight.
- The cost. A standard result in automatic differentiation is that the gradient of one output costs a small constant multiple of one forward pass, and the multiple does not grow with the number of weights. For networks dominated by large matrix products, the backward sweep alone is often described as roughly twice the forward pass. These are rules of thumb, not exact figures. So a million weights cost about a forward pass and a backward sweep, not a million extra forward passes.
- Its name. Computing derivatives by sweeping from the output back to the inputs is reverse-mode automatic differentiation. Sweeping the other way, from the inputs forward, is forward mode, and it needs one sweep per input. A network has one output (the loss) and many inputs (the weights), so reverse mode wins. P1.C10 compares the two modes.
- The price. The backward pass needs the values from the forward pass, so training keeps them in memory. This is one reason training needs more memory than running a trained network (P4.8).
Where the idea came from
The reverse sweep has a history older than neural networks, and who deserves the credit is debated. Linnainmaa described reverse-mode differentiation of programs in 1970. Werbos described how to use it to train networks in a 1974 thesis. A 1986 paper by Rumelhart, Hinton and Williams in Nature made backpropagation widely known and showed that hidden units can learn useful internal representations. Treat these as milestones, not as a complete record.
Intuition
Picture a company. A customer complains about the final product. The complaint goes back to the last department, which looks at how much its own work mattered, and passes a copy of the complaint to each team that fed it, scaled by how strongly that team’s output affected the result. Those teams pass it back to theirs, and so on. In the end, every person has a number that says how much their work mattered for this complaint, and in which direction they should change it.
Where does the picture break? These numbers are not shares of a pie: they do not add up to the complaint, they can be negative, and an add step gives the full blame to each input. They also describe only tiny changes from the way things are now. And the blame at a step depends on the values stored from the forward pass, so the process is not a free-floating “error signal”: it is arithmetic on stored numbers.
Math
The blame of is the chain-rule product of the rates along the path from to the loss:
With the numbers: . The backward pass computes the product from the left, and every partial product is reused. For example, serves both (times ) and (times ).
When a value feeds several places, the contributions add (the multivariable chain rule, P1.C4):
Code
PyTorch records the operations of the forward pass and backward() sweeps through them in reverse. It gives the same gradients as the widget:
import torch
x, y = torch.tensor([1.0, 2.0]), torch.tensor(1.0)
W = torch.tensor([[0.5, -0.3], [0.8, 0.2]], requires_grad=True)
v = torch.tensor([1.0, -1.5], requires_grad=True)
h = torch.sigmoid(W @ x) # forward pass
L = (v @ h - y) ** 2
L.backward() # one backward sweep
print(round(L.item(), 4)) # 2.8149
print(W.grad) # [[-0.8368, -1.6736], [0.8954, 1.7908]]
print(v.grad) # [-1.5939, -2.5788]Try it: backprop against nudging
This cell builds the same network in NumPy. It computes all 6 blames in one backward sweep, then finds each one the slow way by nudging every weight and re-running the forward pass, and counts the extra forward passes. Last, it takes one gradient-descent step.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The two methods agree to four decimals. The nudging needed 6 extra forward passes, and with a million weights it would need a million. Try changing y to another target, or one of the weights: the two methods keep agreeing.
Go deeper The blame can shrink on its way back
Every sigmoid multiplies the blame by a slope of at most . In the widget the slopes were and . If a signal passes through ten sigmoid layers, the slopes alone can shrink it by a factor of , so the weights near the input get almost no blame and learn very slowly. The weights multiply the blame too, and they can make it larger instead, which then grows without limit. This is the problem of vanishing and exploding gradients (P4.16). Part of the cure is a different choice of activation (P4.4) and of starting weights (P4.12), and another part is residual connections (P4.20).
Go deeper Forward mode: the same idea in the other direction
Instead of starting at the loss and moving back, you can start at one input and carry its effect forward: “if I nudge this input, how much does each later value move?” This is forward mode. One forward-mode sweep gives the effect of one input on all the outputs. To get the effect of all weights on one loss, you need sweeps, no better in spirit than nudging each weight. Reverse mode gives the effect of all inputs on one output in a single sweep. A training loss is one output and the weights are the inputs, which is why backpropagation is reverse mode. Forward mode is the better choice when there are few inputs and many outputs. P1.C10 gives the pass counts.
Check your understanding
A network has weights. To measure the effect of each weight on the loss by nudging it once and re-running the forward pass, how many extra forward passes are needed?
Each weight needs its own nudged forward pass, so there is one extra pass per weight: 2,000,000. A single pass cannot serve all of them, because nudging all weights at once mixes their effects together. The factor of 4,000,000 would belong to a two-sided nudge, which uses two passes per weight.
A chain computes and then . At , what is ?
The rates multiply. Going from x to a has rate 5, and going from a to L has rate 2a = 10 at a = 5. So the answer is 5 × 10 = 50. Adding the rates would give 15, which is wrong. The value 10 forgets the first step, and 25 is the value of L.
A value is used in two places. The blames arriving at from the two uses are and . What is the blame of ?
When a value is used in more than one place, the blames from each use add: 3 + (−1) = 2. Taking only one of them ignores the other path, and averaging (which gives 1) is not the chain rule.
A model has one loss and weights. Why is a backward sweep from the loss better than sweeping forward from each weight?
There is one output and many inputs, so a single reverse sweep reuses the shared work and covers every weight. The forward pass is still needed first, because the backward pass uses its stored values. Finite differences are not wrong, only slow.
What does the backward pass of backpropagation produce?
Backpropagation gives gradients: how the loss changes if each weight is nudged. The new weights come from an update rule that uses those gradients, the learning rate is chosen separately, and the prediction comes from the forward pass.
Exercises
- Let , and . At , find by multiplying the rates from the end. Then check by writing as a function of .
Show answer
, at , and . So . Check: , whose slope is at . - In the widget, set to and run the backward pass. Which first-layer gradients become , and does itself still get blame?
Show answer
and become , because the blame reaching hidden unit 2 is the blame at times , so nothing is handed back to them. But itself still gets , which is about : changing would change the output. - Run the nudge test on with , then . Why does the agreement with gradient get better as shrinks?
Show answer
At the real change is against predicted. At both are . The gradient is the slope of the loss at the current weights, and the loss curve bends away from its tangent line, so a smaller nudge stays closer to the tangent. - A network has 3 million weights. How many extra forward passes does nudging every weight once need, and how many backward sweeps does backpropagation need?
Show answer
Nudging needs 3 million extra forward passes. Backpropagation needs one backward sweep (after the forward pass), which typically costs a small multiple of a forward pass. - Let with and . Find and .
Show answer
The value is used twice. The multiply node sends it blame , and the add node sends it blame . They add to . For , the multiply node gives . Check: , so and .
Next: in P4.8 you will follow every number through a different tiny model, a single neuron, and see the same rules in a complete forward pass, backward pass and weight update. P4.9 turns them into a small autograd engine.