Skip to main content
Fanout
The Chain Rule
Curriculum overview

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 y=f(u)y = f(u) with u=g(x)u = g(x):

dydx=dydududx\frac{dy}{dx} = \frac{dy}{du} \cdot \frac{du}{dx}

The intuition: a change in xx changes uu at rate du/dxdu/dx, and that change in uu changes yy at rate dy/dudy/du. Multiply the rates.

When one variable feeds several paths, add the contributions. If zz depends on intermediate variables u1,,uku_1, \dots, u_k, each of which depends on xx:

dzdx=i=1kzuiduidx\frac{dz}{dx} = \sum_{i=1}^{k} \frac{\partial z}{\partial u_i} \frac{du_i}{dx}

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 y=(3x+1)2y = (3x + 1)^2. Set u=3x+1u = 3x + 1. Then

dydu=2u,dudx=3,dydx=6u=6(3x+1)=18x+6\frac{dy}{du} = 2u, \qquad \frac{du}{dx} = 3, \qquad \frac{dy}{dx} = 6u = 6(3x + 1) = 18x + 6

At x=2x = 2 that is 4242. Expanding first confirms it: y=9x2+6x+1y = 9x^2 + 6x + 1, and y=18x+6=42y' = 18x + 6 = 42.

The sum form shows up with a shared node. If z=u2+3uz = u^2 + 3u and u=2xu = 2x, then dz/du=2u+3=4x+3dz/du = 2u + 3 = 4x + 3 and du/dx=2du/dx = 2, giving dz/dx=8x+6dz/dx = 8x + 6. The two terms of dz/dudz/du are two paths through the graph, and both get multiplied by the same du/dxdu/dx.

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 uu 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

  1. Differentiate ex2e^{x^2} and sin(2x)\sin(2x) using the chain rule.
  2. Why does backward mode need the forward intermediates, and what does that imply for memory?
  3. Use the chain rule on z=uvz = uv with u=u(x)u = u(x) and v=v(x)v = v(x) 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.