AI State of the Art
Math/Differential and Integral Calculus/13 min
Section 321

The Chain Rule: The Heart of Backpropagation

Listen as a podcast β†’

Composite functions are everywhere

When you bake a cake, the internal temperature of the cake depends on the time spent in the oven. And the doneness of the cake (fluffy, overdone, raw) depends on the internal temperature. Ultimately, the doneness depends on time, but through the temperature. It's a composite function: doneness = f(temperature(time))f(\text{temperature}(\text{time})).

In mathematics, a composite function is simply a function applied to the result of another function. If ff and gg are two functions, the composition is written:

h(x)=f(g(x))h(x) = f(g(x))

You first apply gg to xx, then ff to the result. It's a chain of transformations.

Why it's crucial in AI

A neural network is a composition of functions. Each layer applies a linear transformation (multiplication by a weight matrix + bias), followed by a nonlinear activation function. A 3-layer network is:

y^=f3(f2(f1(x)))\hat{y} = f_3(f_2(f_1(x)))

Where each fif_i represents a layer: matrix multiplication + activation. The input xx passes through layer after layer, each transformation applying to the result of the previous one. The deeper the network, the longer the composition.

The chain rule

How do you differentiate a composite function? The chain rule answers this question. If h(x)=f(g(x))h(x) = f(g(x)), then:

hβ€²(x)=fβ€²(g(x))β‹…gβ€²(x)h'(x) = f'(g(x)) \cdot g'(x)

In words: the derivative of the composition is the derivative of the outer function (evaluated at the intermediate point) multiplied by the derivative of the inner function.

The gear analogy

Imagine two connected gears. The first turns at 3 revolutions per minute. The second, connected to the first with a 2:1 ratio, turns at 3Γ—2=63 \times 2 = 6 revolutions per minute. To find the final speed, you multiply the ratios at each stage. The chain rule works exactly the same way: you multiply the "rates of change" at each step of the composition.

Leibniz notation

Leibniz notation makes the chain rule even more intuitive. If y=f(u)y = f(u) and u=g(x)u = g(x), then:

dydx=dyduβ‹…dudx\frac{dy}{dx} = \frac{dy}{du} \cdot \frac{du}{dx}

It almost looks like the dudu's "cancel out" like in a fraction. That's not exactly what happens mathematically, but this intuition always works for the chain rule and helps you never make a mistake.

Concrete examples

Example 1: differentiate (3x+1)2(3x + 1)^2

Let u=3x+1u = 3x + 1 and y=u2y = u^2. Then:

dydx=dyduβ‹…dudx=2uβ‹…3=6(3x+1)\frac{dy}{dx} = \frac{dy}{du} \cdot \frac{du}{dx} = 2u \cdot 3 = 6(3x + 1)

Example 2: differentiate eβˆ’x2e^{-x^2}

Let u=βˆ’x2u = -x^2 and y=euy = e^u. Then:

dydx=euβ‹…(βˆ’2x)=βˆ’2xβ‹…eβˆ’x2\frac{dy}{dx} = e^u \cdot (-2x) = -2x \cdot e^{-x^2}

This function is the shape of the Gaussian distribution, ubiquitous in ML.

Example 3: differentiate ln⁑(Οƒ(x))\ln(\sigma(x)) (cross-entropy)

Let u=Οƒ(x)=11+eβˆ’xu = \sigma(x) = \frac{1}{1 + e^{-x}} and y=ln⁑(u)y = \ln(u). Then:

dydx=1uβ‹…Οƒβ€²(x)=1Οƒ(x)β‹…Οƒ(x)(1βˆ’Οƒ(x))=1βˆ’Οƒ(x)\frac{dy}{dx} = \frac{1}{u} \cdot \sigma'(x) = \frac{1}{\sigma(x)} \cdot \sigma(x)(1 - \sigma(x)) = 1 - \sigma(x)

This elegant result explains why cross-entropy works so well with the sigmoid: the gradient has a simple form and doesn't saturate.

When the composition is longer, the rule generalizes naturally. For h(x)=f(g(k(x)))h(x) = f(g(k(x))):

hβ€²(x)=fβ€²(g(k(x)))β‹…gβ€²(k(x))β‹…kβ€²(x)h'(x) = f'(g(k(x))) \cdot g'(k(x)) \cdot k'(x)

You multiply the derivatives of each link in the chain, from the outside inward. For a network with nn layers, you get a product of nn terms, one for each layer traversed.

βˆ‚Lβˆ‚ΞΈ1=βˆ‚Lβˆ‚anβ‹…βˆ‚anβˆ‚anβˆ’1β‹…β€¦β‹…βˆ‚a2βˆ‚a1β‹…βˆ‚a1βˆ‚ΞΈ1\frac{\partial \mathcal{L}}{\partial \theta_1} = \frac{\partial \mathcal{L}}{\partial a_n} \cdot \frac{\partial a_n}{\partial a_{n-1}} \cdot \ldots \cdot \frac{\partial a_2}{\partial a_1} \cdot \frac{\partial a_1}{\partial \theta_1}

It's a product of matrices (or scalars in the simple case). And it's exactly what backpropagation computes.

Backpropagation, step by step

Let's take a simple 2-layer network to make things concrete. The input xx passes through:

  1. Layer 1: z1=w1β‹…x+b1z_1 = w_1 \cdot x + b_1, then a1=ReLU(z1)a_1 = \text{ReLU}(z_1)
  2. Layer 2: z2=w2β‹…a1+b2z_2 = w_2 \cdot a_1 + b_2, then y^=Οƒ(z2)\hat{y} = \sigma(z_2)
  3. Loss: L=βˆ’(yln⁑(y^)+(1βˆ’y)ln⁑(1βˆ’y^))\mathcal{L} = -(y \ln(\hat{y}) + (1-y)\ln(1-\hat{y}))

To update w1w_1, we need βˆ‚Lβˆ‚w1\frac{\partial \mathcal{L}}{\partial w_1}. By the chain rule:

βˆ‚Lβˆ‚w1=βˆ‚Lβˆ‚y^β‹…βˆ‚y^βˆ‚z2β‹…βˆ‚z2βˆ‚a1β‹…βˆ‚a1βˆ‚z1β‹…βˆ‚z1βˆ‚w1\frac{\partial \mathcal{L}}{\partial w_1} = \frac{\partial \mathcal{L}}{\partial \hat{y}} \cdot \frac{\partial \hat{y}}{\partial z_2} \cdot \frac{\partial z_2}{\partial a_1} \cdot \frac{\partial a_1}{\partial z_1} \cdot \frac{\partial z_1}{\partial w_1}

Each term is simple to compute individually:

  • βˆ‚Lβˆ‚y^\frac{\partial \mathcal{L}}{\partial \hat{y}}: derivative of the loss with respect to the prediction
  • βˆ‚y^βˆ‚z2\frac{\partial \hat{y}}{\partial z_2}: derivative of the sigmoid
  • βˆ‚z2βˆ‚a1=w2\frac{\partial z_2}{\partial a_1} = w_2: the weight of layer 2
  • βˆ‚a1βˆ‚z1\frac{\partial a_1}{\partial z_1}: derivative of ReLU (11 if z1>0z_1 > 0, 00 otherwise)
  • βˆ‚z1βˆ‚w1=x\frac{\partial z_1}{\partial w_1} = x: the input

Backpropagation consists of computing these terms from right to left (from output to input) and propagating them layer by layer. Hence the name: backward propagation of the gradient.

The computational graph

To organize all these computations, you use a computational graph. It's a directed acyclic graph (DAG) where:

  • Each node represents an operation (addition, multiplication, activation)
  • Each edge represents the data flow

The forward pass traverses the graph from input to output. The backward pass traverses it in reverse, multiplying local derivatives along each path. This is exactly what frameworks like PyTorch and TensorFlow do: they automatically build this graph during the forward pass, then traverse it backward to compute all gradients.

Directed graph titled Chain Rule with Multiple Paths. The node x splits into two arrows towards the nodes y1 and y2, which both feed into the node z, which in turn points to the node L. Each arrow is labelled in red with the corresponding local partial derivative: d y1 over d x, d y2 over d x, d z over d y1, d z over d y2 and d L over d z.
Here is the computational graph with its derivatives. Each circle is an intermediate value, each arrow carries in red the local derivative of its head with respect to its tail. To get the effect of x on L, you multiply the derivatives along a path, then add the paths together: here x acts on z both through y1 and through y2, so the two branches add up. The backward pass is simply this traversal run from right to left.Source : Michael Brenndoerfer, Backpropagation: The Algorithm That Makes Deep Learning Possible

Autograd: automatic differentiation

In PyTorch, when you write loss.backward(), the framework:

  1. Traverses the computational graph backward
  2. Applies the chain rule at each node
  3. Accumulates gradients in the .grad attribute of each parameter

You never need to differentiate by hand. But understanding the chain rule lets you diagnose problems when training isn't going well.

The vanishing gradient problem

The chain rule implies a product of derivatives. For a deep network (50, 100 layers), this product contains dozens of terms. If each derivative is less than 1 (which happens with the sigmoid, whose maximum derivative is 0.250.25), the product tends exponentially toward zero:

0.2550β‰ˆ10βˆ’300.25^{50} \approx 10^{-30}

The gradient arriving at the first layers is nearly zero: they learn almost nothing. This is the vanishing gradient problem, the bane of deep networks before modern innovations.

Plot titled Gradient Magnitude vs Depth. The horizontal axis is the layer index counting from the output, from 1 to 20; the vertical axis is the gradient norm. The blue Sigmoid curve starts around 1.7 and drops to practically zero by the fourth layer. The orange ReLU curve starts around 5.2 and decays much more slowly, staying visibly non-zero out to about the fifteenth layer.
The product of derivatives, measured. You walk from the output back towards the input and watch what is left of the gradient. With the sigmoid (blue curve) almost nothing survives past three or four layers: the early layers receive no signal and stop learning. With ReLU (orange curve), whose derivative is 1 on the positive side, the decay is far slower. This is exactly the 0.25 to the power 50 argument above, seen on a real network.Source : Michael Brenndoerfer, Backpropagation: Chain Rule, Gradient Flow, and Autograd

The solutions that enabled deep learning all rest on managing this product of derivatives:

  • ReLU: its derivative is 11 for positive values, which avoids multiplication by fractions
  • Batch Normalization: stabilizes intermediate activations so that gradients stay in a reasonable range
  • Residual connections (ResNet): add a direct path from input to output, creating a "shortcut" for the gradient that bypasses the destructive product
  • LSTM and GRU: in sequences, gates control the gradient flow to prevent it from vanishing over long dependencies

Key takeaways

  • The chain rule allows differentiating composite functions by multiplying the derivatives of each step
  • A neural network is a function composition, so backpropagation is a direct application of the chain rule
  • The computational graph organizes the forward and backward pass
  • Automatic differentiation (autograd) applies the chain rule automatically in modern frameworks
  • The vanishing gradient is a direct consequence of the product of derivatives in the chain rule: derivatives less than 1, multiplied many times, tend toward zero
  • ReLU, batch norm, and residual connections are direct solutions to this mathematical problem

Where this is used. This rule is the engine of backpropagation, the algorithm that computes the correction to apply to every weight in a network.