◆ AI All-in-One

Level 3 In-Depth AI · Math Foundations

The Chain Rule

The chain rule says how to find the slope of a function built from other functions — multiply the slopes of each step. Applied backwards through a network of operations, it is backpropagation, the algorithm that trains every neural network.

Level
●●●●● Easy
Reading
11 min
To learn it well
45 minutes to read, an hour to practise
Builds on
1 concept →
↗ Plan a path here

Read first

Derivatives and Slopes

This leads to

Backpropagation
The full path from zero — 1 concept before this one
  1. Derivatives and Slopes
  2. The Chain Rule

Read them roughly in this order. See it on the concept map →

Why it matters

A neural network is a long chain of simple steps. The input is multiplied by weights, a bias is added, an activation function is applied, the result is multiplied by more weights, and so on, layer after layer, until a final step compares the prediction with the right answer and produces a loss. To train the network with Gradient Descent, you need the derivative of that loss with respect to every weight, including weights buried 100 layers deep.

The chain rule is the tool that makes this possible. It tells you how to get the slope of a long chain of functions from the slopes of the individual steps. Run it backwards through the network, reuse the intermediate results, and you get every derivative at once for roughly the cost of running the network twice. That procedure is called Backpropagation, and it is how every modern network, from image classifiers to GPT-style language models, is trained.

The chain rule is the single most important piece of calculus in AI. Fortunately it is also one of the easiest to understand.

The intuition

Imagine three gears in a row. Turning gear A once turns gear B three times. Turning gear B once turns gear C twice. How many times does gear C turn when you turn A once? Obviously 3×2=63 \times 2 = 6. The rates multiply.

The chain rule is exactly that, for functions. Suppose a quantity xx affects uu, and uu affects yy. If uu changes 3 times as fast as xx, and yy changes 8 times as fast as uu, then yy changes 8×3=248 \times 3 = 24 times as fast as xx.

Or think of a nudge travelling down the chain. Nudge xx by 0.01. That nudges uu by 3×0.01=0.033 \times 0.01 = 0.03. That nudges yy by 8×0.03=0.248 \times 0.03 = 0.24. Each step amplifies (or shrinks) the nudge by its own local rate, and the overall effect is the product of all of them.

x value: 1 input u = 3x + 1 value: 4 inner function y = u² value: 16 outer function du/dx = 3 dy/du = 2u = 8 u moves 3× as much as x y moves 8× as much as u nudge x by 0.01 u changes by 0.03 y changes by 0.24 × 3 × 8 Chain rule: dy/dx = dy/du · du/dx = 8 × 3 = 24. Rates multiply along the chain.
Fig. 1 A nudge travelling down a chain. x feeds u = 3x + 1, which feeds y = u². At x = 1, u moves 3 times as much as x and y moves 8 times as much as u. A nudge of 0.01 in x becomes 0.03 in u and 0.24 in y. The overall rate is 8 × 3 = 24.

Key idea To find the slope of a chain of functions, multiply the slopes of the links: dydx=dydu⋅dudx\frac{dy}{dx} = \frac{dy}{du} \cdot \frac{du}{dx}. Backpropagation is this rule, applied from the loss backwards through every step of a network.

How it works

Composed functions

Plugging the output of one function into another is called function composition. If u=g(x)u = g(x) and y=f(u)y = f(u), then y=f(g(x))y = f(g(x)). You meet this constantly:

  • y=(3x+1)2y = (3x + 1)^2 is "multiply by 3 and add 1" followed by "square".
  • A neuron's output σ(wx+b)\sigma(wx + b) is "multiply and add" followed by the sigmoid σ\sigma.
  • A whole network is layer 1 followed by layer 2 followed by … followed by the loss.

The rule

If yy depends on uu and uu depends on xx:

dydx=dydu⋅dudx\frac{dy}{dx} = \frac{dy}{du} \cdot \frac{du}{dx}

Leibniz's notation makes it look as if the dudu's cancel, like fractions. They don't really, but it's a useful memory aid. Both slopes must be measured at the right place: dudx\frac{du}{dx} at the current xx, and dydu\frac{dy}{du} at the current uu.

A worked example by hand

Find the slope of y=(3x+1)2y = (3x + 1)^2 at x=1x = 1.

  1. Name the inner step. Let u=3x+1u = 3x + 1, so y=u2y = u^2.
  2. Go forward and record the values. At x=1x = 1: u=3⋅1+1=4u = 3 \cdot 1 + 1 = 4, and y=42=16y = 4^2 = 16.
  3. Local slopes. dudx=3\frac{du}{dx} = 3. dydu=2u=2⋅4=8\frac{dy}{du} = 2u = 2 \cdot 4 = 8.
  4. Multiply. dydx=8×3=24\frac{dy}{dx} = 8 \times 3 = 24.

Check with a nudge: at x=1.001x = 1.001, y=(4.003)2=16.024009y = (4.003)^2 = 16.024009. The change is 0.0240090.024009 for a nudge of 0.0010.001, a slope of about 24. ✓

You could instead expand (3x+1)2=9x2+6x+1(3x + 1)^2 = 9x^2 + 6x + 1 and differentiate to get 18x+6=2418x + 6 = 24. Same answer. But with 100 nested steps expanding is impossible, while the chain rule just keeps multiplying.

Longer chains

The rule extends to any length. If x→u→v→yx \to u \to v \to y:

dydx=dydv⋅dvdu⋅dudx\frac{dy}{dx} = \frac{dy}{dv} \cdot \frac{dv}{du} \cdot \frac{du}{dx}

One slope per link, all multiplied together. This has a famous consequence. If each of 50 links has a slope of about 0.25 (the sigmoid's maximum), the product is 0.2550≈10−300.25^{50} \approx 10^{-30}, effectively zero. The first layers of the network receive no learning signal. These are Vanishing and Exploding Gradients. If each link has a slope of 1.5, the product is 1.550≈6371.5^{50} \approx 637 million, and training explodes. Much of modern network design, such as ReLU activations, careful Weight Initialization, normalisation layers and Residual Connections, exists to keep this product sensible.

Computation graphs

To apply the chain rule systematically, draw the calculation as a computation graph: each operation is a node, and arrows show which values feed into which. Here is one neuron with a squared-error loss:

z=wx+b,a=σ(z),L=(a−t)2z = wx + b, \qquad a = \sigma(z), \qquad L = (a - t)^2

with input x=2x = 2, target t=1t = 1, weight w=0.5w = 0.5 and bias b=−0.5b = -0.5. We want ∂L∂w\frac{\partial L}{\partial w} and ∂L∂b\frac{\partial L}{\partial b}. (The curly ∂\partial is read "d" too. It is used when a quantity depends on several inputs and we change just one of them. The Partial Derivatives and Gradients chapter explains it fully. For now, treat it like dd.)

Forward pass. Compute and keep every intermediate value:

Step Value
z=wx+b=0.5×2−0.5z = wx + b = 0.5 \times 2 - 0.5 0.50.5
a=σ(z)=1/(1+e−0.5)a = \sigma(z) = 1 / (1 + e^{-0.5}) 0.62250.6225
L=(a−t)2=(0.6225−1)2L = (a - t)^2 = (0.6225 - 1)^2 0.14250.1425

Backward pass. Start at the loss, where ∂L∂L=1\frac{\partial L}{\partial L} = 1, and move backwards, multiplying by one local slope per step:

Step Local slope Running product
L=(a−t)2L = (a - t)^2 ∂L∂a=2(a−t)=−0.7551\frac{\partial L}{\partial a} = 2(a - t) = -0.7551 ∂L∂a=−0.7551\frac{\partial L}{\partial a} = -0.7551
a=σ(z)a = \sigma(z) dadz=a(1−a)=0.2350\frac{da}{dz} = a(1 - a) = 0.2350 ∂L∂z=−0.7551×0.2350=−0.1774\frac{\partial L}{\partial z} = -0.7551 \times 0.2350 = -0.1774
z=wx+bz = wx + b ∂z∂w=x=2\frac{\partial z}{\partial w} = x = 2 ∂L∂w=−0.1774×2=−0.3549\frac{\partial L}{\partial w} = -0.1774 \times 2 = -0.3549
z=wx+bz = wx + b ∂z∂b=1\frac{\partial z}{\partial b} = 1 ∂L∂b=−0.1774×1=−0.1774\frac{\partial L}{\partial b} = -0.1774 \times 1 = -0.1774

Both derivatives are negative, so increasing ww and bb would lower the loss. That makes sense: the neuron output 0.62 but the target is 1, so it should output more. A Gradient Descent step with learning rate 1 would set w=0.5+0.3549=0.8549w = 0.5 + 0.3549 = 0.8549.

w x × b + σ t (·−t)² L 0.5 2 wx = 1.0 z = 0.5 a = 0.6225 0.1425 −0.5 1 −0.1774 −0.1774 −0.7551 1 ∂L/∂w = −0.3549 ∂L/∂b = −0.1774 Forward pass (blue): compute and keep each value Backward pass (red): multiply local slopes from L back to each input × σ′ = 0.2350 × 1 × x = 2
Fig. 2 The computation graph of one neuron with a squared-error loss. Blue numbers are the forward pass: each node's value. Red numbers are the backward pass: the derivative of the loss with respect to each value, found by multiplying local slopes from L back towards w and b.

Notice two things that make this efficient:

  1. The forward values are reused. The local slope a(1−a)a(1 - a) needs aa, which the forward pass already computed. That is why frameworks keep intermediate values in memory during training, and why training needs much more memory than just running a model.
  2. The running product is shared. ∂L∂z=−0.1774\frac{\partial L}{\partial z} = -0.1774 was computed once and then used for both ww and bb. In a big network, the product for a layer's output is computed once and reused for every weight in that layer. That is why one backward pass gives all the derivatives, for roughly twice the cost of the forward pass.

When paths branch: add them up

Sometimes a value feeds into more than one place. Then a nudge to it travels down several paths at once, and the total effect is the sum of the effects along each path.

For example, let y=u+vy = u + v with u=x2u = x^2 and v=3xv = 3x. Then xx affects yy through uu (slope 1⋅2x1 \cdot 2x) and through vv (slope 1⋅31 \cdot 3), so

dydx=2x+3\frac{dy}{dx} = 2x + 3

which matches differentiating x2+3xx^2 + 3x directly. In neural networks this happens all the time: one neuron's output feeds every neuron of the next layer, so its derivative is a sum over all of them. The rule is: multiply along a path, add across paths.

In code

The from-scratch version follows the tables exactly:

import numpy as np

x, t = 2.0, 1.0          # input and target
w, b = 0.5, -0.5         # parameters

# forward pass: keep every intermediate value
z = w * x + b                    # 0.5
a = 1 / (1 + np.exp(-z))         # sigmoid
L = (a - t) ** 2                 # squared error
print(f"z={z:.4f}  a={a:.4f}  L={L:.4f}")
# z=0.5000  a=0.6225  L=0.1425

# backward pass: chain rule, from the loss back to the parameters
dL_da = 2 * (a - t)
da_dz = a * (1 - a)
dL_dz = dL_da * da_dz
dL_dw = dL_dz * x                # dz/dw = x
dL_db = dL_dz * 1                # dz/db = 1
print(f"dL/da={dL_da:.4f}  da/dz={da_dz:.4f}  dL/dw={dL_dw:.4f}  dL/db={dL_db:.4f}")
# dL/da=-0.7551  da/dz=0.2350  dL/dw=-0.3549  dL/db=-0.1774

# check dL/dw with a finite difference
def loss(w):
    a = 1 / (1 + np.exp(-(w * x + b)))
    return (a - t) ** 2
h = 1e-5
print((loss(w + h) - loss(w - h)) / (2 * h))    # -0.3548938347003316  matches

PyTorch records the computation graph as you compute, then runs the backward pass for you. This is automatic differentiation:

import torch

x, t = torch.tensor(2.0), torch.tensor(1.0)
w = torch.tensor(0.5, requires_grad=True)
b = torch.tensor(-0.5, requires_grad=True)

L = (torch.sigmoid(w * x + b) - t) ** 2
L.backward()                     # the chain rule, applied automatically
print(w.grad, b.grad)            # tensor(-0.3549) tensor(-0.1774)

Common pitfalls

  • Evaluating a local slope at the wrong point. In dydu=2u\frac{dy}{du} = 2u, use the value of uu at the current input (u=4u = 4), not xx. Keeping the forward values in a table avoids this.
  • Forgetting the inner derivative. The derivative of (3x+1)2(3x + 1)^2 is not 2(3x+1)2(3x + 1). You must multiply by the inner slope, 3. This is the most common hand-calculation error.
  • Forgetting to add across branches. When a value is used twice, its derivative is the sum over both uses. PyTorch does this by accumulating into .grad, which is also why you must zero gradients between steps.
  • Breaking the graph. In PyTorch, converting to NumPy, calling .item(), or using .detach() in the middle of a computation cuts the chain. Gradients stop flowing to everything before that point, silently.

Watch out Because the chain rule multiplies many local slopes, a single bad link can ruin the whole product. One saturated sigmoid (slope near 0) blocks the signal for everything before it. One exploding link makes everything before it blow up. When a deep network won't train, check the size of gradients layer by layer.

Where it leads

A bit of history

The chain rule was known to Gottfried Wilhelm Leibniz, who used it in a 1676 manuscript, and it appeared in Guillaume de l'Hôpital's 1696 textbook, the first calculus textbook ever published. The idea of applying it mechanically to a computer program goes back to the 1960s. Seppo Linnainmaa's 1970 master's thesis described reverse-mode automatic differentiation, which is backpropagation in general form. Paul Werbos proposed using it to train neural networks in his 1974 PhD thesis, and David Rumelhart, Geoffrey Hinton and Ronald Williams made it famous in 1986. Today's frameworks, from PyTorch to JAX, are at heart very efficient chain-rule machines.

Try it

  1. By hand, find the slope of y=(2x−1)3y = (2x - 1)^3 at x=2x = 2. Check with a nudge of 0.001.
  2. In the neuron example, change the target to t=0t = 0. Recompute ∂L∂w\frac{\partial L}{\partial w} by hand. What sign do you expect, and why?
  3. Extend the from-scratch code with a second neuron after the first: a2=σ(w2a+b2)a_2 = \sigma(w_2 a + b_2), loss (a2−t)2(a_2 - t)^2. Compute ∂L∂w\frac{\partial L}{\partial w} for the first weight by hand, then confirm with PyTorch.

Hint for 1: with u=2x−1=3u = 2x - 1 = 3, dydu=3u2=27\frac{dy}{du} = 3u^2 = 27 and dudx=2\frac{du}{dx} = 2, so the slope is 54.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Find the slope of y = (2x + 1)² at x = 1 using the chain rule.

  2. A network has 50 links in a row, each with a local slope of about 0.25 (the sigmoid's maximum). What happens to the gradient reaching the first layer?

  3. A value x feeds into two places: y = u + v with u = x² and v = 3x. What is dy/dx?

  4. Why does training a network need much more memory than just running it?

  5. Midway through a PyTorch computation you call .item() on a value and keep computing with the Python number. What happens to gradients?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Video

Essence of Calculus

3Blue1Brown · Beginner · Free

Derivatives, the chain rule and integrals, explained visually in short videos.

Tool

micrograd

Andrej Karpathy · Intermediate · Free

A tiny autograd engine in about 100 lines. Reading it is the best way to demystify backprop.

Course

Differential Calculus

Khan Academy · Beginner · Free

Patient video lessons and practice on limits, derivatives, the derivative rules and the chain rule.

Article

The Matrix Calculus You Need For Deep Learning

Terence Parr & Jeremy Howard · 2018 · Intermediate · Free

Builds from single-variable derivatives to gradients, Jacobians and the vector chain rule, exactly as needed to understand backpropagation.

Video

Neural Networks (video series)

3Blue1Brown · Beginner · Free

Gorgeous animated explanations of neural nets, gradient descent, backprop, Transformers and attention.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/math/chain-rule.md