Math Fundamentals · lesson 07/15
The Chain Rule
A neural network is a composition of functions, so its derivative is a product of local derivatives. The chain rule is that product. It is the single fact that makes backpropagation possible, and it is worth seeing both the scalar form and the sum-over-paths form.
The idea
For with :
The intuition: a change in changes at rate , and that change in changes at rate . Multiply the rates.
When one variable feeds several paths, add the contributions. If depends on intermediate variables , each of which depends on :
This total-derivative form is what a computational graph encodes. Reverse-mode autodiff walks the graph from the output backward, and at each node multiplies the incoming gradient by that node's local derivative and adds it to the parent's accumulator. One backward pass yields the gradient with respect to every parameter, at roughly the cost of one forward pass.
Worked example
Differentiate . Set . Then
At that is . Expanding first confirms it: , and .
The sum form shows up with a shared node. If and , then and , giving . The two terms of are two paths through the graph, and both get multiplied by the same .
In code
import torch
x = torch.tensor(2.0, requires_grad=True)
u = 3 * x + 1
y = u**2
y.backward()
print(u.item()) # 7.0
print(x.grad) # tensor(42.)Autograd stored during the forward pass so the backward pass could reuse it. That storage is why training costs memory proportional to depth: the graph holds the intermediates.
Check yourself
- Differentiate and using the chain rule.
- Why does backward mode need the forward intermediates, and what does that imply for memory?
- Use the chain rule on with and to recover the product rule.
Key takeaways
- The chain rule multiplies local derivatives along a path and sums across paths.
- Reverse mode computes all parameter gradients in one backward pass.
- Backprop is the chain rule on a computational graph, not a special algorithm.