In P1.C2 you learned that has slope . Then a central difference on at gave a slope of 2, not 1. Where did the 2 come from?
It came from the inside. The exponent changes twice as fast as , and the exponential then reacts to the exponent. Two rates, one after the other, and the slope of the whole is their product. That one idea, rates multiply, is the chain rule. A neural network is a long chain of such steps, so this is the lesson that backpropagation rests on.
A function inside a function
A composition feeds the output of one function into another. Write . The function is the inside, and is the outside. It is easier to follow with a name for the middle value:
You compute from the inside out: first from , then from . Here are some you have already met, split into inside and outside:
- : inside , outside .
- : inside , outside .
- : inside , outside .
- : inside , outside .
- : inside , outside .
The order matters. Take and . Then , but . The notation is another way to write : “ after ”.
A neural network is a composition with many layers: , and the loss is one more function on top. If you nudge a weight in the first layer, the nudge travels through every function after it. To know what it does to the loss, we need a rule for the whole journey.
Rates multiply
Start with something you can touch: a bicycle. One turn of the pedals turns the rear wheel 3 times (a 48-tooth front gear driving a 16-tooth rear gear, and ). One turn of the wheel carries the bike 2.1 m. So one pedal turn carries it m.
Let be pedal turns, wheel turns and metres. Then and , so . The rates are , and . Look at the units:
The “wheel turns” cancel, and the rates multiply. A chain of gears is a chain of functions, and a gear ratio is the slope of a straight line.
Curves are gears whose ratio changes
Most functions in machine learning are not straight lines. But P1.C1 showed that a smooth curve looks straight when you zoom in, so for a tiny nudge each function acts like a gear with a fixed ratio: its slope at that point. Two things follow:
- The ratio of the inside gear is , the slope at .
- The ratio of the outside gear is , the slope at the value that the inside delivers, not at .
Where does the gear picture break? Three places. A real gear train has fixed ratios, while here the ratios depend on where you stand, so the product is only right for tiny nudges. The outside gear must be read at , which is a different place from . And a real gear train never has a ratio of exactly 0, while a flat spot does: then nothing passes through, and the whole product becomes 0.
Numbers first: at
Let and . At : and . Nudge by and watch both steps:
| nudge | |||
|---|---|---|---|
( means “the change in”.) The ratio is exactly 3, the slope of . The ratio is , then , then , heading for 8, which is the slope of at : . And the overall ratio is the product of the two, for every row: . As shrinks, the ratio heads for .
Two wrong answers are tempting. Forgetting the inside gives . Taking the slope of at instead of at gives . Neither matches the table.
The chain rule
Collect what the table showed. If is differentiable at and is differentiable at , then
In words: the slope of the outside, taken at the inside value, times the slope of the inside. A recipe that works every time:
- Name the inside and the outside .
- Differentiate each on its own: and .
- Evaluate at , and multiply by .
As a check, for two straight lines and the composition is , with slope : the product of the two slopes.
A note on
P1.C1 told you to read as one symbol, because the derivative is a limit and alone has no meaning yet. That is still true. What has changed is that the nudge ratios are real fractions, and the table above shows that is plain algebra: the cancels. Take the limit and each fraction becomes a derivative, so looks like “cancel the ”.
That makes it a very good mnemonic: it tells you which factors belong together and in which units. It is not a proof by itself, for two reasons. The symbol has not been given a meaning, and the algebra needs , which can fail (see the careful proof below). Use the pattern to remember the rule, and the limit to justify it. With several variables (P1.C4 onwards) the cancelling needs more care.
Things to try with the rates multiply widget:
- Start as it opens (, , , ). The row moves , the row , the row . The orange tick on the row sits at . Slide towards and watch the tick and the bar meet.
- Switch the inside to . Its rate is negative, so moves the opposite way. With the outside rate is negative too, and two negatives give an overall rate of .
- Choose and and move to 0. The inside rate is 0 and the status line says the chain is blocked: the product is 0, and is flat there.
- Choose and and move to 2. Then , where the sigmoid is nearly flat (rate about ). The outside gear squashes the nudge.
- Press Show the two classic mistakes and compare the red lines with the central difference.
Why it is true
Here is the idea behind the rule. Nudge by a small .
- The inside moves: (the tangent-line approximation of P1.C1).
- The outside then moves: (the same approximation, for at ).
- Put together: , so .
In the table, with : , and against a true . The leftover is , which shrinks like , faster than itself. Each “” hides an error that is small even compared with , so after dividing by and letting the errors vanish and the product remains.
This is the reason, not yet a proof. The second approximation is used with a that itself changes with , and that needs care.
Go deeper A careful proof, and the trap in the quick one
The quick proof writes and takes limits. It divides by , which can be 0 even when : take a function that is constant on a stretch, or one that wiggles through the same value again and again close to . The fix is to build the division into a function that is fine at 0.
Fix and put . Define, for a number ,
Because is differentiable at , as . By the definition of , for every including 0,
Now let , so . Then
As : because a differentiable is continuous (), so ; and the last fraction tends to . The right side tends to . No division by ever happened, so the case is covered.
The rule at work
For each example: name the inside and the outside, differentiate each, read the outside rate at the inside value, multiply. Every answer was also checked with a central difference of the whole function, which uses no rule.
. Inside (rate 2), outside (rate at ). So : at it is , the number P1.C2 found, and at it is . For any constant , . With : , the result P1.C2 got from the reciprocal rule. And gives , the result P1.C2 got by a limit.
. Inside (rate 3), outside (rate ). So the slope is : at and at . Expanding the fifth power would take six terms.
. Inside (rate ), outside (rate ). So the slope is , which is at (P1.C2 saw , while the outside rule alone said ) and at .
. Outside (rate ), inside (rate ). The slope is , which is at .
Softplus . Outside (rate ), inside (rate ). So the slope is . P1.C2 only checked this numerically: at it is , where the outside rule alone would have said . Softplus is a smooth version of ReLU, and its slope rises smoothly from 0 to 1 instead of jumping.
Any real power for . P1.C2 stated the power rule for every real and left the proof to this lesson. Write . The inside has rate , and the outside has rate , so
Check: at gives , and at gives . Central differences agree.
Patterns to remember. For a differentiable inside :
- ( if is not a whole number)
- (where )
Chain rule or product rule?
Look at the last operation you would do when evaluating the function. If it is a product, use the product rule first. If it is a function applied to something, use the chain rule first. Often you need both.
Take . The last operation is a product of and . The product rule gives , and the chain rule supplies . So the slope is : at . Using the chain rule alone, as if were a constant, gives . Using the product rule and forgetting the factor 2 gives .
Longer chains: multiply them all
With three functions, , apply the rule twice. Name the values and . Then
Each rate is read at the value that arrives at that function. With four functions there are four factors, and so on. This is why a forward pass comes first: you need the values before you can read off the rates.
The sigmoid as four small steps
P1.C2 got from the reciprocal rule. Here is the chain-rule route, with the sigmoid cut into four steps, at :
The forward values are , , and . The four local rates are , , and . Their product is
which is . In symbols, , the same answer as before.
Backward: the seed of backpropagation
Multiplying the four rates from the output end gives a running product:
- the slope of with respect to itself is (the start);
- with respect to : ;
- with respect to : ;
- with respect to : ;
- with respect to : .
One sweep from the end gave the slope of the output with respect to every value along the way, not just the first one. That is backpropagation: each node multiplies the slope arriving from above by its own local rate (P4.8 does this on a bigger graph, with the same numbers shown step by step).
Go deeper Why start at the end, when numbers can be multiplied in any order
For plain numbers the order does not change the product. It matters when many values feed one result. Going from the end, each running product is the slope of the end with respect to that value, and it is reused by everything that feeds into it. A network with a million weights and one loss then needs one backward sweep, not a million separate forward ones. With vectors the factors become matrices (the Jacobian of P1.C7), the order changes the cost, and the backward direction is cheap when the end is a single number. P1.C10 explains this as forward mode and reverse mode.
Three derivatives from machine learning
tanh from the sigmoid. P1.A5 showed . The inside is (rate 2), and the outside has rate . So
With we have and , which is the same thing, so this agrees with P1.C2’s . At it gives and at it gives (more digits: ). The factor 4 at the middle is two factors of 2: the inside squeezes the curve sideways, and the outside stretches it upward. That is why tanh is four times as steep as the sigmoid at 0.
The squared error. For one example the loss is . Let be the error. The outside has rate . The inside has rate with respect to and rate with respect to (the other values held fixed: nudging one parameter at a time is P1.C4). So
With , , and (the numbers of P4.8): , so the slopes are and . P1.C2 got by expanding the square first; here no expansion is needed. For , the chain rule gives , the same as the expanded differentiated. For the three-example loss of P0.2, averaging over the examples gives at , the slope that took a page in P1.C1. The slope of an average is the average of the slopes.
The logistic loss. If the right answer is “yes” and the model gives probability , the loss is . The outside has rate , and the inside has rate . The factors cancel:
At it is , at it is , and at it is . It is “prediction minus target” again, and it does not fade when the model is confidently wrong: at the slope is . Compare the squared error on the same sigmoid, . Its slope is , and at it is only , because the flat sigmoid tail squashes it. This is one reason classification uses the log loss (P3.A7, P4.6).
A chain of local rates
The next widget shows the whole procedure on small chains: the forward values in blue, the local rates and the backward products in orange. A slider replays the backward pass from the end.
Things to try with the chain of local rates widget:
- Squared error, as it opens (, ). The values are , , , , , the local rates are , , , , and the end slopes are , , , , . The slope with respect to is , the number in P4.8. Drag the backward slider one step at a time, then switch to the bias : its slope is .
- Sigmoid and logistic loss (): , , and the rates , , , multiply to . Move to (confidently right) and the slope with respect to almost vanishes, about . Move to (confidently wrong) and it is about .
- Stack of sigmoids, one number per layer with , and input . Five layers give a product of about and ten layers about . Raise to , set and the input to : every layer sits at with rate , and ten layers give .
Vanishing and exploding products
The sigmoid slope is never more than (P1.A5, P1.C2). So each sigmoid layer multiplies the backward signal by at most , times the weight that feeds it. In the best case, per layer:
- 1 layer:
- 2 layers:
- 3 layers:
- 5 layers:
- 10 layers:
That is the picture P1.A5 sketched. Two corrections make it honest. The weights are factors too: each layer contributes , so it is the size of that sets the bound, and with above 4 the bound allows growth. And a unit pushed into the flat tail has a rate far below : at the slope is , so three saturated layers give .
So a long product of rates below 1 shrinks fast (vanishing gradients), and a long product of rates above 1 grows fast (exploding gradients). The chain rule is not at fault: the product is exactly right, and it is tiny or huge. The layers near the input then barely learn, or learn wildly. This is the subject of P4.16.
Why does ReLU help? Its slope is 1 where the unit is on, so an active ReLU unit passes the signal back at the size of its weight, with no extra factor of . A unit that is off has slope 0 and blocks the signal, which is the flat spot again. P4.4 compares the activations.
Go deeper One variable feeding two paths (a preview)
Sometimes a value reaches the end by two routes. Let and , and let . Nudging changes through and through , and the two effects add. The effect through is the rate of with respect to (which is ) times . The effect through is times . At : . Check: has slope .
The rule for such cases is to multiply along each path and add the paths. The notation for “the rate of with respect to while is held fixed” is the partial derivative of P1.C4, and the general statement uses the Jacobian of P1.C7. Backpropagation adds the gradients that arrive from each use of a value (the box “What if a value is used in more than one place?” in P4.8).
Go deeper Slopes of inverse functions, and a second proof for the logarithm
If undoes , so that , apply the chain rule to both sides: , so wherever (assuming is differentiable). With and : . P1.C2 proved this from a limit, and the mirror-image picture there says the same: slopes of a function and its inverse are reciprocals.
The chain rule in three depths
Intuition
A nudge passes through a chain of machines. Each machine multiplies the size of the nudge by its own gear ratio at the moment, so the final change is the starting nudge times all the ratios. If one machine does nothing (ratio 0), nothing comes out. If one is very flat, the nudge is squeezed, however large the others are.
For a network this means: the effect of a weight on the loss is the product of how much it moves its neuron, how much that moves the next, and so on to the loss. Multiplying from the loss backward gives that number for every value in one pass.
Math
If is differentiable at and is differentiable at , then is differentiable at and
With and : . For a chain of functions, with and :
Proof idea: with , applied with (the careful proof above).
Code
import math
def central(f, x, h=1e-5):
return (f(x + h) - f(x - h)) / (2 * h)
def sigmoid(z):
return 1 / (1 + math.exp(-z))
# slope of sigmoid(3x - 1) at x = 1: sigmoid'(2) * 3
z = 3 * 1 - 1
rule = sigmoid(z) * (1 - sigmoid(z)) * 3
print(rule, central(lambda x: sigmoid(3 * x - 1), 1.0)) # both about 0.3150PyTorch multiplies the local rates for you (backpropagation, P4.8). This runs in Colab or on your machine, not in the browser here:
import torch
x = torch.tensor(1.0, requires_grad=True)
y = torch.sigmoid(3 * x - 1)
y.backward()
print(x.grad) # about 0.3150Try it: the chain rule against a finite difference
The first cell checks the rule on seven functions and also shows the “ at ” mistake. The second runs the four-step sigmoid backward and compares a stack of sigmoid layers with the best case . Predict the output first, then change the numbers.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Challenge: add at (inside , outside ). The slope should be .
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Challenge: find a weight and bias that keep ten layers near a product of 1 (hint: make every layer sit at and set , so and with input ).
Common mistakes
Check your understanding
Let and . What is the slope of at ?
The inside value is , so the outside slope is , and the inside slope is . The product is . The value forgets the inside rate. The value reads at instead of at (). The value is , the value of the function, not its slope.
What is the slope of at ?
The inside has rate , and the outside has rate at . The product is . The value forgets the inside, the value is the slope of at 0, and has the wrong sign: the exponent falls as rises.
A chain of three steps has local rates , and . What is the rate of the end with respect to the start?
Rates multiply: . The value adds the rates, which is the wrong operation. The value has lost the sign of the middle rate. The value leaves out the last factor.
What is the slope of at ?
The product rule gives , and the chain rule gives . So the slope is at . The value applies only the chain rule, as if were constant. The value forgets the factor 2 from the inside. The value is the function itself, not a slope.
Why can a long stack of sigmoid layers make the layers near the input learn very slowly?
The slope of is , so every layer contributes a small factor (unless its weight is large), and the product shrinks quickly as layers are added. The chain rule holds for any number of functions. The sigmoid slope is positive, and its output lies strictly between 0 and 1.
Exercises
- Differentiate and evaluate the slope at .
Show answer
Inside (rate 2), outside (rate ). The slope is . At , , so it is . - Differentiate and find its value at .
Show answer
Inside (rate ), outside . The slope is , which is at . (This bell shape reappears in probability, and its slope is 0 at , its peak.) - Show that and evaluate it at and .
Show answer
with gives . At : . At : . This is minus the slope of the logistic loss . - Find the slope of at .
Show answer
Inside (rate 3), which is at . The outside slope is . The product is . - Find the slope of at , using three links.
Show answer
(rate 2), (rate ), (rate ). At : , . The rates are , and , so the slope is . - Find at in two ways: with and through .
Show answer
First way: the inside has rate 3, and , so the slope is . Second way: has slope . Both agree. - Let and . Find the slope of and of at . Why do they differ?
Show answer
has slope at . has slope . The functions are different (the order of the composition matters), so their slopes differ. - Five sigmoid layers each have rate (an idealised best case: every unit at and weight 1; with , and input 0 the actual product is about ). By about what factor is a nudge at the input scaled at the output? What changes if the weight in each layer is 4?
Show answer
, about a thousandth. With weight 4 each layer’s rate is (when ), so the product is and the nudge arrives unchanged. - A student writes . Find the error, give the right slope, and compare the two at .
Show answer
The inside rate was forgotten. The slope is . At the student’s answer is and the right one is . - Find the point where has slope 0, and the value of the function there.
Show answer
Product rule with the chain rule: . This is at , where the value is .
Next: P1.C4 lets a function have several inputs and nudges them one at a time (partial derivatives), and P1.C5 collects those slopes into the gradient. The chain rule you just learned then runs through all of them, and P4.8 uses it on a whole network.