Chain Rule

The mathematical engine behind backpropagation

Why

A neural network is a composition of functions — layer 1 feeds into layer 2, feeds into layer 3, and so on. To compute how the loss at the end depends on weights at layer 1, you need the chain rule. Backpropagation is literally "apply the chain rule through a computational graph." This is the single most important rule to understand if you want to explain how neural networks learn.

Intuition

The chain rule handles composed functions: if y depends on u, and u depends on x, then how does y change when x changes? Answer: multiply the rates. If u doubles when x increases by 1, and y triples when u doubles — then y increases by 6 when x increases by 1. You chain the rates together by multiplying.

In a neural network: loss depends on the output layer, which depends on the hidden layer, which depends on the weights. The chain rule lets you trace this dependency all the way back.

Explanation
The rule

If y = f(u) and u = g(x), then:

dy/dx = (dy/du) · (du/dx)

The derivative of the outer function times the derivative of the inner function. For deeper compositions:

y = f(g(h(x))) dy/dx = f'(g(h(x))) · g'(h(x)) · h'(x)

A chain of multiplications — one factor per function in the composition.

Concrete example
f(x) = (3x + 1)⁴ Let u = 3x + 1, so f = u⁴ df/dx = (df/du) · (du/dx) = 4u³ · 3 = 12(3x+1)³
Chain Rule through a two-layer network
z₁ = w₁·x (linear layer 1) a₁ = σ(z₁) (activation — sigmoid) z₂ = w₂·a₁ (linear layer 2) L = (y - z₂)² (MSE loss)

To find ∂L/∂w₁ (how loss depends on weight in layer 1):

∂L/∂w₁ = (∂L/∂z₂) · (∂z₂/∂a₁) · (∂a₁/∂z₁) · (∂z₁/∂w₁) = -2(y-z₂) · w₂ · σ(z₁)(1-σ(z₁)) · x

Each factor is a local derivative — easy to compute at each node. Backprop walks this chain from right to left, accumulating products. This is the full mechanism of backpropagation.

Why multiplying many numbers is dangerous

Backprop multiplies many numbers together as it propagates backward. Two problems arise:

Vanishing gradient
If each factor is < 1 (e.g. sigmoid derivative ≤ 0.25), multiplying many → exponentially small gradient → early layers learn nothing. Solved by: ReLU activations, batch norm, residual connections.
Exploding gradient
If each factor is > 1, multiplying many → exponentially large gradient → unstable training, NaN loss. Solved by: gradient clipping (cap the gradient norm to a max value).