Chain rule
Quick answer
The chain rule differentiates a composition of functions. If z=g(w) and L=f(z), then dL/dw=(dL/dz)(dz/dw). Automatic differentiation (AD) applies derivative rules to the operations that compute a value; it is neither symbolic expression simplification nor finite-difference sampling. Reverse-mode AD is useful when a scalar loss depends on many parameters.
A prediction followed by a loss
Take prediction z=3w+1 and target t=7. The loss is L=(z−t)². The local derivatives are dL/dz=2(z−t) and dz/dw=3. Multiply them to get 6(z−t). When an intermediate is reused along multiple paths, add the contributions before propagating farther.
w=1z=3*w+1target=7local=2*(z-target)print(z, (z-target)**2, local*3)Expected output:
4 9 -18The loss is 9 and its slope is −18. Increasing w slightly lowers the loss. For L=w*w, both uses of w contribute w, so the derivative is w+w.
Reverse-mode automatic differentiation
Optional local PyTorch 2.10.0+cpu lab; CPU float64; no random operations. A tensor is a numerical array, including a scalar. requires_grad=True tracks operations involving the parameter. backward() propagates the derivative of this scalar output and accumulates it in the leaf tensor’s .grad. item() reads a scalar value for display after differentiation. Rebuild the forward computation for each new pass and clear accumulated gradients when they should not be summed.
import torchw=torch.tensor(1.0,dtype=torch.float64,requires_grad=True)z=3*w+1loss=(z-7)**2loss.backward()print(loss.item(),w.grad.item())w.grad=None((3*w+1-7)**2).backward()print(w.grad.item())Expected output:
9.0 -18.0-18.0The automatically computed derivative agrees with the hand calculation. Resetting .grad avoids summing derivatives from the two passes. AD computes derivatives of supported recorded operations up to numerical precision; it is not a proof that the loss or model is appropriate.
Common mistakes
Do not add the two local slopes in a single chain; multiply them. Do add contributions from distinct paths into a shared variable. Converting an intermediate to an ordinary Python number before the loss computation can disconnect the graph. Forward-mode AD propagates tangents from inputs; reverse mode propagates sensitivities backward from outputs. Neither changes parameters by itself.
Practice and next steps
For z=2w−1, L=(z−5)² at w=2, calculate both local derivatives and their product before running a library. Next, organize derivatives of vector-valued functions.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Chain rule — knowledge check
Apply calculus and differentiation to small original examples.
If L=f(g(w)), which rule applies?
For z=2w+1, L=(z−5)² at w=1, what is dL/dw?
What does reverse-mode AD propagate?
What happens if the same leaf receives two backward contributions without clearing its gradient?
When w is used twice in w*w, what is its derivative?