Level 3 In-Depth AI · Math Foundations
The Chain Rule
The chain rule says how to find the slope of a function built from other functions — multiply the slopes of each step. Applied backwards through a network of operations, it is backpropagation, the algorithm that trains every neural network.
- Level
- ●●●●● Easy
- Reading
- 11 min
- To learn it well
- 45 minutes to read, an hour to practise
- Builds on
- 1 concept →
- Quiz
- 5 questions ↓
Read first
Derivatives and SlopesThis leads to
BackpropagationThe full path from zero — 1 concept before this one
- Derivatives and Slopes
- The Chain Rule
Read them roughly in this order. See it on the concept map →
Why it matters
A neural network is a long chain of simple steps. The input is multiplied by weights, a bias is added, an activation function is applied, the result is multiplied by more weights, and so on, layer after layer, until a final step compares the prediction with the right answer and produces a loss. To train the network with Gradient Descent, you need the derivative of that loss with respect to every weight, including weights buried 100 layers deep.
The chain rule is the tool that makes this possible. It tells you how to get the slope of a long chain of functions from the slopes of the individual steps. Run it backwards through the network, reuse the intermediate results, and you get every derivative at once for roughly the cost of running the network twice. That procedure is called Backpropagation, and it is how every modern network, from image classifiers to GPT-style language models, is trained.
The chain rule is the single most important piece of calculus in AI. Fortunately it is also one of the easiest to understand.
The intuition
Imagine three gears in a row. Turning gear A once turns gear B three times. Turning gear B once turns gear C twice. How many times does gear C turn when you turn A once? Obviously . The rates multiply.
The chain rule is exactly that, for functions. Suppose a quantity affects , and affects . If changes 3 times as fast as , and changes 8 times as fast as , then changes times as fast as .
Or think of a nudge travelling down the chain. Nudge by 0.01. That nudges by . That nudges by . Each step amplifies (or shrinks) the nudge by its own local rate, and the overall effect is the product of all of them.
Key idea To find the slope of a chain of functions, multiply the slopes of the links: . Backpropagation is this rule, applied from the loss backwards through every step of a network.
How it works
Composed functions
Plugging the output of one function into another is called function composition. If and , then . You meet this constantly:
- is "multiply by 3 and add 1" followed by "square".
- A neuron's output is "multiply and add" followed by the sigmoid .
- A whole network is layer 1 followed by layer 2 followed by … followed by the loss.
The rule
If depends on and depends on :
Leibniz's notation makes it look as if the 's cancel, like fractions. They don't really, but it's a useful memory aid. Both slopes must be measured at the right place: at the current , and at the current .
A worked example by hand
Find the slope of at .
- Name the inner step. Let , so .
- Go forward and record the values. At : , and .
- Local slopes. . .
- Multiply. .
Check with a nudge: at , . The change is for a nudge of , a slope of about 24. ✓
You could instead expand and differentiate to get . Same answer. But with 100 nested steps expanding is impossible, while the chain rule just keeps multiplying.
Longer chains
The rule extends to any length. If :
One slope per link, all multiplied together. This has a famous consequence. If each of 50 links has a slope of about 0.25 (the sigmoid's maximum), the product is , effectively zero. The first layers of the network receive no learning signal. These are Vanishing and Exploding Gradients. If each link has a slope of 1.5, the product is million, and training explodes. Much of modern network design, such as ReLU activations, careful Weight Initialization, normalisation layers and Residual Connections, exists to keep this product sensible.
Computation graphs
To apply the chain rule systematically, draw the calculation as a computation graph: each operation is a node, and arrows show which values feed into which. Here is one neuron with a squared-error loss:
with input , target , weight and bias . We want and . (The curly is read "d" too. It is used when a quantity depends on several inputs and we change just one of them. The Partial Derivatives and Gradients chapter explains it fully. For now, treat it like .)
Forward pass. Compute and keep every intermediate value:
| Step | Value |
|---|---|
Backward pass. Start at the loss, where , and move backwards, multiplying by one local slope per step:
| Step | Local slope | Running product |
|---|---|---|
Both derivatives are negative, so increasing and would lower the loss. That makes sense: the neuron output 0.62 but the target is 1, so it should output more. A Gradient Descent step with learning rate 1 would set .
Notice two things that make this efficient:
- The forward values are reused. The local slope needs , which the forward pass already computed. That is why frameworks keep intermediate values in memory during training, and why training needs much more memory than just running a model.
- The running product is shared. was computed once and then used for both and . In a big network, the product for a layer's output is computed once and reused for every weight in that layer. That is why one backward pass gives all the derivatives, for roughly twice the cost of the forward pass.
When paths branch: add them up
Sometimes a value feeds into more than one place. Then a nudge to it travels down several paths at once, and the total effect is the sum of the effects along each path.
For example, let with and . Then affects through (slope ) and through (slope ), so
which matches differentiating directly. In neural networks this happens all the time: one neuron's output feeds every neuron of the next layer, so its derivative is a sum over all of them. The rule is: multiply along a path, add across paths.
In code
The from-scratch version follows the tables exactly:
import numpy as np
x, t = 2.0, 1.0 # input and target
w, b = 0.5, -0.5 # parameters
# forward pass: keep every intermediate value
z = w * x + b # 0.5
a = 1 / (1 + np.exp(-z)) # sigmoid
L = (a - t) ** 2 # squared error
print(f"z={z:.4f} a={a:.4f} L={L:.4f}")
# z=0.5000 a=0.6225 L=0.1425
# backward pass: chain rule, from the loss back to the parameters
dL_da = 2 * (a - t)
da_dz = a * (1 - a)
dL_dz = dL_da * da_dz
dL_dw = dL_dz * x # dz/dw = x
dL_db = dL_dz * 1 # dz/db = 1
print(f"dL/da={dL_da:.4f} da/dz={da_dz:.4f} dL/dw={dL_dw:.4f} dL/db={dL_db:.4f}")
# dL/da=-0.7551 da/dz=0.2350 dL/dw=-0.3549 dL/db=-0.1774
# check dL/dw with a finite difference
def loss(w):
a = 1 / (1 + np.exp(-(w * x + b)))
return (a - t) ** 2
h = 1e-5
print((loss(w + h) - loss(w - h)) / (2 * h)) # -0.3548938347003316 matches
PyTorch records the computation graph as you compute, then runs the backward pass for you. This is automatic differentiation:
import torch
x, t = torch.tensor(2.0), torch.tensor(1.0)
w = torch.tensor(0.5, requires_grad=True)
b = torch.tensor(-0.5, requires_grad=True)
L = (torch.sigmoid(w * x + b) - t) ** 2
L.backward() # the chain rule, applied automatically
print(w.grad, b.grad) # tensor(-0.3549) tensor(-0.1774)
Common pitfalls
- Evaluating a local slope at the wrong point. In , use the value of at the current input (), not . Keeping the forward values in a table avoids this.
- Forgetting the inner derivative. The derivative of is not . You must multiply by the inner slope, 3. This is the most common hand-calculation error.
- Forgetting to add across branches. When a value is used twice, its derivative is the sum over both uses. PyTorch does this by accumulating into
.grad, which is also why you must zero gradients between steps. - Breaking the graph. In PyTorch, converting to NumPy, calling
.item(), or using.detach()in the middle of a computation cuts the chain. Gradients stop flowing to everything before that point, silently.
Watch out Because the chain rule multiplies many local slopes, a single bad link can ruin the whole product. One saturated sigmoid (slope near 0) blocks the signal for everything before it. One exploding link makes everything before it blow up. When a deep network won't train, check the size of gradients layer by layer.
Where it leads
- Partial Derivatives and Gradients: the chain rule for functions of many variables, where slopes become vectors and matrices (the Jacobian).
- Backpropagation: the chain rule applied to a whole neural network, worked number by number.
- Vanishing and Exploding Gradients, Residual Connections and Weight Initialization: keeping the product of many slopes from vanishing or exploding.
- Gradient Descent: uses the derivatives the chain rule produces.
- Recurrent networks apply the chain rule through time, one link per step of the sequence.
A bit of history
The chain rule was known to Gottfried Wilhelm Leibniz, who used it in a 1676 manuscript, and it appeared in Guillaume de l'Hôpital's 1696 textbook, the first calculus textbook ever published. The idea of applying it mechanically to a computer program goes back to the 1960s. Seppo Linnainmaa's 1970 master's thesis described reverse-mode automatic differentiation, which is backpropagation in general form. Paul Werbos proposed using it to train neural networks in his 1974 PhD thesis, and David Rumelhart, Geoffrey Hinton and Ronald Williams made it famous in 1986. Today's frameworks, from PyTorch to JAX, are at heart very efficient chain-rule machines.
Try it
- By hand, find the slope of at . Check with a nudge of 0.001.
- In the neuron example, change the target to . Recompute by hand. What sign do you expect, and why?
- Extend the from-scratch code with a second neuron after the first: , loss . Compute for the first weight by hand, then confirm with PyTorch.
Hint for 1: with , and , so the slope is 54.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Essence of Calculus
Derivatives, the chain rule and integrals, explained visually in short videos.
Calculus on Computational Graphs: Backpropagation
A short, beautifully drawn essay showing how the chain rule on a graph of operations becomes backpropagation.
micrograd
A tiny autograd engine in about 100 lines. Reading it is the best way to demystify backprop.
Differential Calculus
Patient video lessons and practice on limits, derivatives, the derivative rules and the chain rule.
The Matrix Calculus You Need For Deep Learning
Builds from single-variable derivatives to gradients, Jacobians and the vector chain rule, exactly as needed to understand backpropagation.
Neural Networks (video series)
Gorgeous animated explanations of neural nets, gradient descent, backprop, Transformers and attention.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/math/chain-rule.md