Lesson 8 · Calculus
Chains of functions: the chain rule
The problem
In the last chapter we used a recipe: each squared miss changes at . It gave the right gradient, but we never said where it came from.
Look at how one delivery's error is built. It's not one formula; it's three small steps in a row:
- The weights make a prediction: .
- The prediction makes a miss: , where is the real time.
- The miss is squared: .
Each step is easy to differentiate on its own. This chapter shows how to combine their slopes.
Chaining functions
Feeding one function's output into another is called composition. If turns into , and then turns that into , the chain is written ("f after g"). Order matters: you do first.
Our error is a chain. Take delivery B (5 km, traffic 1, 26 minutes), and keep the traffic weight at 6 as in the derivatives chapter. Then
At : , then , then .
Slopes multiply
Predict first
Stage A doubles its input. Stage B triples its input. You feed A's output into B. If the input goes up by 1, how much does the final output go up?
The same thing happens with curved stages. The only difference is that a curved stage's slope depends on where you are. So you take each stage's slope at the value that's flowing through it.
Nudge below and follow the change down the chain. Each arrow is a local slope: the slope of one stage, at its current input.
w₁ (minutes per km)
3 → 3.1 change 0.1
↓ local slope × 5
p (prediction = 5w₁ + 6)
21
↓ local slope × 1
e (miss = p − 26)
−5
↓ local slope × -10 (2e, with e = -5)
s (squared error = e²)
25
Slopes multiplied: 0.1 × 5 × 1 × -10 = −5
Real change in s: −4.75. Shrink the nudge and the two agree more closely.
Worked example
Nudge w₁ from 3 to 3.1
has slope 5, so moves by : from 21 to 21.5.
That's the chain rule. For two links:
In words: the outer function's slope, taken at the inner function's value, times the inner function's slope. With the notation it reads like fractions cancelling:
They aren't fractions, but it's a good memory aid: each link's "bottom" matches the next link's "top."
Check it against the derivatives chapter. With , B's squared error is . Multiplying out gives , which is at . The chain rule got the same answer without multiplying out.
One more example: is with . The outer slope is and the inner slope is 3, so .
The computational graph
A real formula isn't one neat chain. It branches. The prediction has two weights feeding into it. To handle that, break the formula into its smallest steps (multiply, add, subtract, square) and draw each one as a box. Arrows show which values feed which step.
That drawing is a computational graph. It's used in two passes:
- Forward pass: values flow from the inputs to the output. This is computing the formula.
- Backward pass: gradients flow from the output back to the inputs. At each box, the gradient arriving from above is multiplied by that step's local slope.
Press play. Steps 1 to 5 run forward; steps 6 to 10 run backward. Each box shows its value, then the gradient of with respect to it ("grad").
Delivery B: x = (5 km, traffic 1), real time 26 min
Press play. First the values flow down the graph.
For delivery B at , the backward pass goes:
| Box | Value | Local slope | Gradient of |
|---|---|---|---|
| 36 | (start) | 1 | |
| −6 | |||
| 20 | |||
| 3 | |||
| 5 |
The table skips the add box and the two multiply boxes, and the data boxes (, and time), which need no gradient. The add box passes straight through. Each multiply box scales it by its feature.
So the gradient of B's squared error is . That is , the recipe from the last chapter. Now you can see where it comes from: is the square's local slope, and is the multiply's local slope.
Notice what each box needs: only its own local slope and the gradient arriving from above. No box needs to know the whole formula. That's why the method works for any formula, of any length. A neural network is a huge graph made of the same small steps. Running this backward pass through it is called backpropagation, the subject of chapter 3.4.
When paths join, gradients add
The total error adds up three deliveries. So reaches along three paths, one through each delivery's prediction. Nudge , and all three predictions move.
The rule for that: work out the chain rule along each path, then add the paths. Each delivery contributes .
| Feature | Ridge | Lasso |
|---|---|---|
| distance | 4.45 | 6.14 |
| traffic | 4.82 | 6.68 |
| rain | 1.42 | 1.57 |
| hour | −0.58 | −0.22 |
| items | 0.04 | 0 exactly |
| driver | −0.23 | 0 exactly |
At the paths for give (A), (B) and (C). They sum to , the partial derivative from the last chapter. For they give , and , summing to . A contributes nothing to , because A had no traffic.
In the graph, is a box with three arrows leaving it. In the backward pass, a gradient comes back along each arrow, and the box adds them up. So one backward pass adds the paths for you.
Predict first
Set the weights to (4, 6), the true values. What are the three path contributions for ∂E/∂w₁?
DeeperJacobians: the chain rule when everything is a vectorWith many inputs and many outputs, each local slope becomes a matrix, and the chain rule becomes matrix multiplication. · 5 min
So far each box had one output. Now treat all three predictions as one step: , where is the matrix of features, one row per delivery. Two inputs go in, three outputs come out. Its "slope" is a table of every output's partial derivative with respect to every input. That table is the Jacobian:
For a matrix-vector product, the Jacobian is the matrix itself.
The next step, , has three inputs and one output. Its Jacobian is a single row: at .
The chain rule says: multiply the Jacobians, outer first.
The shapes multiply like matrices: . The inner sizes match because the middle quantity, , has 3 entries. Each entry of the answer is the sum over the three paths, the same "paths add" rule as before. The grid below lays it out: each cell is one path.
| Delivery | 2e | → w₁ | → w₂ |
|---|---|---|---|
| A | -4 | -4 × 2 = -8 | -4 × 0 = 0 |
| B | -12 | -12 × 5 = -60 | -12 × 1 = -12 |
| C | -10 | -10 × 3 = -30 | -10 × 2 = -20 |
| Column sums | -98 | -32 | |
Blue numbers are the Jacobian X (one row per delivery). Orange is the row 2e. The column sums are the gradient (-98, -32).
This is the chain rule in its general form. Chaining functions multiplies their Jacobians, as chaining transformations multiplies their matrices.
The backward pass never builds a full Jacobian. It starts with the output's single row and multiplies it by each Jacobian in turn, from the output end. Each of those products is a single row. That is much cheaper than multiplying whole matrices. So the backward pass is cheapest when the output is a single number, like the error.
Common misconceptions
"The slopes of a chain add." They multiply. A ×2 stage then a ×3 stage gives ×6, not ×5. Gradients add only where separate paths join.
"Take every slope at the original input." Each link's slope is taken at the value flowing into that link. For that's at , not at .
Recap
- Composition feeds one function's output into the next.
- The chain rule: the slope of a chain is the product of each link's local slope, taken at the value flowing through it.
- A computational graph breaks any formula into small steps. Values flow forward; gradients flow backward, multiplied by each local slope.
- Where paths join, their gradients add. One backward pass does this for you.
Section 2 shows how to compute these in PyTorch.