The Chain Rule
The chain rule differentiates functions inside functions, like or . It says rates of change multiply along a chain: if changes 3 times as fast as , and changes 2 times as fast as , then changes 6 times as fast as . It is also the single idea that makes training neural networks possible.
The rule
If , write so . Then
"Differentiate the outer function, leave the inside alone, then multiply by the derivative of the inside." Leibniz notation makes it look like fractions cancelling. They are not fractions, but the notation is a reliable memory aid.
Worked examples
Chains can be longer. For there are three layers: cube, sine and .
Checking with SymPy and numbers
import sympy as sp
x = sp.symbols('x')
for expr in [(3*x + 1)**10, sp.sqrt(x**2 + 9), sp.sin(x**2), sp.sin(4*x)**3]:
print(f"d/dx {str(expr):<16} = {sp.factor(sp.diff(expr, x))}")d/dx (3*x + 1)**10 = 30*(3*x + 1)**9
d/dx sqrt(x**2 + 9) = x/sqrt(x**2 + 9)
d/dx sin(x**2) = 2*x*cos(x**2)
d/dx sin(4*x)**3 = 12*sin(4*x)**2*cos(4*x)
sp.factor tidies the result into a product, which is how the chain rule naturally produces it. Now numbers: the derivative of at from shrinking central differences, against :
import math
f = lambda x: math.sin(x**2)
x0 = 1.5
exact = 2 * x0 * math.cos(x0**2)
for h in [1e-1, 1e-2, 1e-3, 1e-4, 1e-5]:
approx = (f(x0 + h) - f(x0 - h)) / (2 * h)
print(f"h = {h:.0e} {approx:.10f} error {abs(approx - exact):.1e}")
print(f"chain rule: {exact:.10f}")h = 1e-01 -1.8792804218 error 5.2e-03
h = 1e-02 -1.8844715803 error 4.9e-05
h = 1e-03 -1.8845203756 error 4.9e-07
h = 1e-04 -1.8845208632 error 4.9e-09
h = 1e-05 -1.8845208681 error 3.4e-11
chain rule: -1.8845208682
The error drops by about 100 each time shrinks by 10: the central difference is second order, as promised in The Derivative.
Why it works (sketch)
Let . Then
As , because is continuous, so the first bracket tends to and the second to . (A careful proof handles the case , but the idea is exactly this.)
In software: backpropagation
A neural network is one long composition: input → linear layer → activation → linear layer → … → loss. To train it we need for every weight , and the chain rule gives it as a product of local derivatives along the path from to the loss.
Take a single neuron with squared-error loss:
Backpropagation computes those factors from the loss backwards, reusing each partial product for every weight upstream. That reuse is why one backward pass costs about the same as one forward pass, no matter how many millions of weights there are.
import math
sigmoid = lambda z: 1 / (1 + math.exp(-z))
x, y, w, b = 2.0, 1.0, 0.3, -0.1
def loss(w):
a = sigmoid(w * x + b)
return (a - y) ** 2
z = w * x + b
a = sigmoid(z)
dL_da, da_dz, dz_dw = 2 * (a - y), a * (1 - a), x
print(f"factors: dL/da = {dL_da:.6f}, da/dz = {da_dz:.6f}, dz/dw = {dz_dw}")
print(f"chain rule dL/dw = {dL_da * da_dz * dz_dw:.8f}")
h = 1e-6
print(f"numeric dL/dw = {(loss(w + h) - loss(w - h)) / (2 * h):.8f}")factors: dL/da = -0.755081, da/dz = 0.235004, dz/dw = 2.0
chain rule dL/dw = -0.35489383
numeric dL/dw = -0.35489383
The full story, with many layers and vectors of weights, is in Backpropagation Is the Chain Rule, and the general machinery in Automatic Differentiation. The factor is derived in Derivatives of Exponentials and Logs.
Note: Multiplying many factors is also the source of vanishing gradients: is at most 0.25, so a chain of ten sigmoid layers can scale a gradient by . This is one reason modern networks prefer ReLU, residual connections and normalisation.
Exercises
Exercise 1: One layer
Differentiate .
Answer
Solution
Exercise 2: A root in the denominator
Differentiate .
Answer
Solution
Exercise 3: Three layers
Differentiate and evaluate at a point where .
Answer
; at that point .
Solution
Exercise 4: Gradient of a two-layer chain
For with , , compute at with the chain rule () and check it numerically.
Answer
About (both methods agree).
Solution
import math
x, y, w = 1.5, 0.5, 0.4
t = math.tanh(w * x)
print(round(2 * (t - y) * (1 - t * t) * x, 4))
L = lambda w: (math.tanh(w * x) - y) ** 2
h = 1e-6
print(round((L(w + h) - L(w - h)) / (2 * h), 4))0.0791
0.0791
Test yourself
What is ?
In backpropagation, why compute derivatives from the loss backwards?
- It is more accurate than forward order
- The forward pass cannot be differentiated
- Each shared partial product is computed once and reused for all upstream weights
- To avoid using the chain rule
What is ?