Maths toolkit8 / 17

Lesson 8 · Calculus

Chains of functions: the chain rule

The problem

In the last chapter we used a recipe: each squared miss changes at 2×miss×feature2 \times \text{miss} \times \text{feature}. 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:

  1. The weights make a prediction: p=w⋅xp = \mathbf{w} \cdot \mathbf{x}.
  2. The prediction makes a miss: e=p−te = p - t, where tt is the real time.
  3. The miss is squared: s=e2s = e^2.

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 gg turns xx into g(x)g(x), and ff then turns that into f(g(x))f(g(x)), the chain is written f∘gf \circ g ("f after g"). Order matters: you do gg 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

w1  →  p=5w1+6  →  e=p−26  →  s=e2w_1 \;\to\; p = 5w_1 + 6 \;\to\; e = p - 26 \;\to\; s = e^2

At w1=3w_1 = 3: p=21p = 21, then e=−5e = -5, then s=25s = 25.

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 w1w_1 below and follow the change down the chain. Each arrow is a local slope: the slope of one stage, at its current input.

  1. w₁ (minutes per km)

    3 → 3.1 change 0.1

  2. ↓ local slope × 5

    p (prediction = 5w₁ + 6)

    21

  3. ↓ local slope × 1

    e (miss = p − 26)

    −5

  4. ↓ 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.

Stage 0 of 3
A nudge in w₁ ripples down the chain. Each stage multiplies the change by its local slope. The product of the slopes predicts the change in s.

Worked example

Nudge w₁ from 3 to 3.1

  1. p=5w1+6p = 5w_1 + 6 has slope 5, so pp moves by 5×0.1=0.55 \times 0.1 = 0.5: from 21 to 21.5.

That's the chain rule. For two links:

ddxf(g(x))=f′(g(x))⋅g′(x)\frac{d}{dx} f\big(g(x)\big) = f'\big(g(x)\big) \cdot g'(x)

In words: the outer function's slope, taken at the inner function's value, times the inner function's slope. With the dd notation it reads like fractions cancelling:

dsdw1=dsde⋅dedp⋅dpdw1=2e⋅1⋅5=2(−5)(5)=−50\frac{ds}{dw_1} = \frac{ds}{de} \cdot \frac{de}{dp} \cdot \frac{dp}{dw_1} = 2e \cdot 1 \cdot 5 = 2(-5)(5) = -50

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 w2=6w_2 = 6, B's squared error is s=(5w1−20)2=25(w1−4)2s = (5w_1 - 20)^2 = 25(w_1 - 4)^2. Multiplying out gives s′=50(w1−4)s' = 50(w_1 - 4), which is −50-50 at w1=3w_1 = 3. The chain rule got the same answer without multiplying out.

One more example: y=e3xy = e^{3x} is eue^u with u=3xu = 3x. The outer slope is eue^u and the inner slope is 3, so dy/dx=3e3xdy/dx = 3e^{3x}.

The computational graph

A real formula isn't one neat chain. It branches. The prediction p=w1x1+w2x2p = w_1 x_1 + w_2 x_2 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 ss with respect to it ("grad").

inputw₁datax₁inputw₂datax₂multiplyw₁x₁multiplyw₂x₂addpdatatimesubtractesquares

Delivery B: x = (5 km, traffic 1), real time 26 min

Press play. First the values flow down the graph.

Step 0 of 10
One delivery's squared error as a graph. Values flow down; then gradients flow up, multiplied by the local slope on each edge. The small label on each box says what that step does.

For delivery B at w=(3,5)\mathbf{w} = (3, 5), the backward pass goes:

BoxValueLocal slopeGradient of ss
s=e2s = e^236(start)1
e=p−26e = p - 26−6ds/de=2e=−12ds/de = 2e = -121×(−12)=−121 \times (-12) = -12
p=w1x1+w2x2p = w_1x_1 + w_2x_220de/dp=1de/dp = 1−12-12
w1w_13∂p/∂w1=x1=5\partial p / \partial w_1 = x_1 = 5−12×5=−60-12 \times 5 = -60
w2w_25∂p/∂w2=x2=1\partial p / \partial w_2 = x_2 = 1−12×1=−12-12 \times 1 = -12

The table skips the add box and the two multiply boxes, and the data boxes (x1x_1, x2x_2 and time), which need no gradient. The add box passes −12-12 straight through. Each multiply box scales it by its feature.

So the gradient of B's squared error is (−60,−12)(-60, -12). That is 2e×x=2(−6)(5,1)2e \times \mathbf{x} = 2(-6)(5, 1), the recipe from the last chapter. Now you can see where it comes from: 2e2e is the square's local slope, and x\mathbf{x} 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 w1w_1 reaches EE along three paths, one through each delivery's prediction. Nudge w1w_1, and all three predictions move.

The rule for that: work out the chain rule along each path, then add the paths. Each delivery contributes 2×miss×feature2 \times \text{miss} \times \text{feature}.

Ridge (L2)
0.010.111010002468λ (log scale)weight (minutes per std)
Lasso (L1)
0.010.111010002468λ (log scale)weight (minutes per std)all 0 here
FeatureRidgeLasso
distance4.456.14
traffic4.826.68
rain1.421.57
hour−0.58−0.22
items0.040 exactly
driver−0.230 exactly
w₁ reaches the total error through three deliveries. Each path's gradient is 2 × miss × feature; the partial derivative is their sum. Line thickness shows each path's share.

At (3,5)(3, 5) the paths for w1w_1 give −8-8 (A), −60-60 (B) and −30-30 (C). They sum to −98-98, the partial derivative from the last chapter. For w2w_2 they give 00, −12-12 and −20-20, summing to −32-32. A contributes nothing to w2w_2, because A had no traffic.

In the graph, w1w_1 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: p=Xw\mathbf{p} = X\mathbf{w}, where XX is the 3×23 \times 2 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:

∂p∂w=(∂pA/∂w1∂pA/∂w2∂pB/∂w1∂pB/∂w2∂pC/∂w1∂pC/∂w2)=(205132)=X\frac{\partial \mathbf{p}}{\partial \mathbf{w}} = \begin{pmatrix} \partial p_A / \partial w_1 & \partial p_A / \partial w_2 \\ \partial p_B / \partial w_1 & \partial p_B / \partial w_2 \\ \partial p_C / \partial w_1 & \partial p_C / \partial w_2 \end{pmatrix} = \begin{pmatrix} 2 & 0 \\ 5 & 1 \\ 3 & 2 \end{pmatrix} = X

For a matrix-vector product, the Jacobian is the matrix itself.

The next step, E=∑i(pi−ti)2E = \sum_i (p_i - t_i)^2, has three inputs and one output. Its Jacobian is a single row: 2e=(−4,−12,−10)2\mathbf{e} = (-4, -12, -10) at (3,5)(3, 5).

The chain rule says: multiply the Jacobians, outer first.

∂E∂w=(−4, −12, −10)⏟1×3(205132)⏟3×2=(−98, −32)⏟1×2\frac{\partial E}{\partial \mathbf{w}} = \underbrace{(-4,\ -12,\ -10)}_{1 \times 3} \underbrace{\begin{pmatrix} 2 & 0 \\ 5 & 1 \\ 3 & 2 \end{pmatrix}}_{3 \times 2} = \underbrace{(-98,\ -32)}_{1 \times 2}

The shapes multiply like matrices: (1×3)(3×2)=1×2(1 \times 3)(3 \times 2) = 1 \times 2. The inner sizes match because the middle quantity, p\mathbf{p}, 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.

Delivery2e→ 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).

Each cell is one path: 2e for that delivery times its feature (the Jacobian X). Each column sums to one entry of the gradient.

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 s=e2s = e^2 that's 2e2e at e=−5e = -5, not at w1=3w_1 = 3.

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.