Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsCalculus

The chain rule

P1.C345 min●●○ IntermediateReviewed Nov 30, 2026

Why this matters for machine learning

A neural network is a long chain of simple functions, and training needs the slope of the loss with respect to a weight at the start of the chain. The chain rule says how: multiply the local slopes along the way. Backpropagation is that multiplication, organised so that every weight's slope comes out of one backward sweep.

  • Backpropagation multiplies each node's local derivative by the gradient arriving from above, one node at a time, from the loss back to the weights. (P4.8: Backpropagation: step by step with numbers)
  • When many sigmoids are chained, each multiplies the signal by at most 14\frac14 (times its weight), so a product of many such factors can vanish. The same product with factors above 1 can explode. (P4.16: Vanishing and exploding gradients, coming soon)
  • The gradient of a squared-error loss is 2(wx+b−y) x2(wx+b-y)\,x, and the gradient of the logistic loss is σ(z)−1\sigma(z)-1 times xx. Both are one chain-rule step. (P3.A2: Linear regression, coming soon)
  • Logistic regression is a sigmoid applied to wx+bwx+b with a log loss on top, a chain of three functions whose slope is found by the chain rule. (P3.A7: Logistic regression, coming soon)
  • Automatic differentiation stores one local rule per basic operation and combines them with the chain rule, so any program built from those operations can be differentiated. (P1.C10: Computational graphs and automatic differentiation)

Before this: Rates of change and the derivative, Derivative rules

After this lesson you can

  • Split a nested function f(g(x))f(g(x)) into its inside and outside, and say which one is evaluated first
  • State the chain rule (f∘g)′(x)=f′(g(x)) g′(x)(f\circ g)'(x)=f'(g(x))\,g'(x) and dydx=dydududx\frac{dy}{dx}=\frac{dy}{du}\frac{du}{dx}, and explain why the rates multiply
  • Differentiate ekx\mathrm{e}^{kx}, (3x+1)5(3x+1)^5, ln⁡(1+x2)\ln(1+x^2), 1+x2\sqrt{1+x^2}, softplus, the sigmoid, tanh and a squared-error loss, and check each with a finite difference
  • Multiply the local rates along a chain of three or more functions, starting from the output, and use this to see why gradients vanish
  • Avoid the classic mistakes: forgetting the inside rate, taking f′f' at xx instead of at g(x)g(x), and using the chain rule where the product rule is needed

In P1.C2 you learned that ex\mathrm{e}^x has slope ex\mathrm{e}^x. Then a central difference on e2x\mathrm{e}^{2x} at x=0x=0 gave a slope of 2, not 1. Where did the 2 come from?

It came from the inside. The exponent 2x2x changes twice as fast as xx, and the exponential then reacts to the exponent. Two rates, one after the other, and the slope of the whole is their product. That one idea, rates multiply, is the chain rule. A neural network is a long chain of such steps, so this is the lesson that backpropagation rests on.

A function inside a function

A composition feeds the output of one function into another. Write y=f(g(x))y=f(g(x)). The function gg is the inside, and ff is the outside. It is easier to follow with a name for the middle value:

u=g(x),y=f(u).u=g(x),\qquad y=f(u).

You compute from the inside out: first uu from xx, then yy from uu. Here are some you have already met, split into inside and outside:

  • e2x\mathrm{e}^{2x}: inside u=2xu=2x, outside eu\mathrm{e}^{u}.
  • (3x+1)5(3x+1)^5: inside u=3x+1u=3x+1, outside u5u^5.
  • ln⁡(1+x2)\ln(1+x^2): inside u=1+x2u=1+x^2, outside ln⁡u\ln u.
  • σ(wx+b)\sigma(wx+b): inside u=wx+bu=wx+b, outside σ(u)\sigma(u).
  • (wx−y)2(wx-y)^2: inside u=wx−yu=wx-y, outside u2u^2.

The order matters. Take f(u)=u2f(u)=u^2 and g(x)=x+1g(x)=x+1. Then f(g(2))=(2+1)2=9f(g(2))=(2+1)^2=9, but g(f(2))=22+1=5g(f(2))=2^2+1=5. The notation (f∘g)(x)(f\circ g)(x) is another way to write f(g(x))f(g(x)): “ff after gg”.

A neural network is a composition with many layers: y^=f3(f2(f1(x)))\hat{y}=f_3(f_2(f_1(x))), and the loss is one more function on top. If you nudge a weight in the first layer, the nudge travels through every function after it. To know what it does to the loss, we need a rule for the whole journey.

Rates multiply

Start with something you can touch: a bicycle. One turn of the pedals turns the rear wheel 3 times (a 48-tooth front gear driving a 16-tooth rear gear, and 48/16=348/16=3). One turn of the wheel carries the bike 2.1 m. So one pedal turn carries it 3×2.1=6.33\times2.1=6.3 m.

Let xx be pedal turns, uu wheel turns and yy metres. Then u=3xu=3x and y=2.1 uy=2.1\,u, so y=6.3 xy=6.3\,x. The rates are dudx=3\frac{du}{dx}=3, dydu=2.1\frac{dy}{du}=2.1 and dydx=6.3\frac{dy}{dx}=6.3. Look at the units:

wheel turnspedal turn×metreswheel turn=metrespedal turn.\begin{aligned} &\frac{\text{wheel turns}}{\text{pedal turn}}\times\frac{\text{metres}}{\text{wheel turn}}\\ &=\frac{\text{metres}}{\text{pedal turn}}. \end{aligned}

The “wheel turns” cancel, and the rates multiply. A chain of gears is a chain of functions, and a gear ratio is the slope of a straight line.

Curves are gears whose ratio changes

Most functions in machine learning are not straight lines. But P1.C1 showed that a smooth curve looks straight when you zoom in, so for a tiny nudge each function acts like a gear with a fixed ratio: its slope at that point. Two things follow:

  • The ratio of the inside gear is g′(x)g'(x), the slope at xx.
  • The ratio of the outside gear is f′(u)f'(u), the slope at the value u=g(x)u=g(x) that the inside delivers, not at xx.

Where does the gear picture break? Three places. A real gear train has fixed ratios, while here the ratios depend on where you stand, so the product is only right for tiny nudges. The outside gear must be read at uu, which is a different place from xx. And a real gear train never has a ratio of exactly 0, while a flat spot does: then nothing passes through, and the whole product becomes 0.

Numbers first: (3x+1)2(3x+1)^2 at x=1x=1

Let u=3x+1u=3x+1 and y=u2y=u^2. At x=1x=1: u=4u=4 and y=16y=16. Nudge xx by hh and watch both steps:

nudge hhΔu\Delta uΔy\Delta yΔy/h\Delta y/h
0.10.10.30.32.492.4924.924.9
0.010.010.030.030.24090.240924.0924.09
0.0010.0010.0030.0030.0240090.02400924.00924.009

(Δ\Delta means “the change in”.) The ratio Δu/h\Delta u/h is exactly 3, the slope of 3x+13x+1. The ratio Δy/Δu\Delta y/\Delta u is 8.38.3, then 8.038.03, then 8.0038.003, heading for 8, which is the slope of u2u^2 at u=4u=4: 2u=82u=8. And the overall ratio is the product of the two, for every row: 8.3×3=24.98.3\times3=24.9. As hh shrinks, the ratio heads for 8×3=248\times3=24.

Two wrong answers are tempting. Forgetting the inside gives 88. Taking the slope of u2u^2 at x=1x=1 instead of at u=4u=4 gives 2×1×3=62\times1\times3=6. Neither matches the table.

The chain rule

Collect what the table showed. If gg is differentiable at xx and ff is differentiable at u=g(x)u=g(x), then

(f∘g)′(x)=f′(g(x))⋅g′(x),ordydx=dydu⋅dudx.\begin{gathered} (f\circ g)'(x)=f'\bigl(g(x)\bigr)\cdot g'(x), \\ \text{or}\quad \frac{dy}{dx}=\frac{dy}{du}\cdot\frac{du}{dx}. \end{gathered}

In words: the slope of the outside, taken at the inside value, times the slope of the inside. A recipe that works every time:

  1. Name the inside u=g(x)u=g(x) and the outside y=f(u)y=f(u).
  2. Differentiate each on its own: g′(x)g'(x) and f′(u)f'(u).
  3. Evaluate f′f' at u=g(x)u=g(x), and multiply by g′(x)g'(x).

As a check, for two straight lines g(x)=bx+cg(x)=bx+c and f(u)=au+df(u)=au+d the composition is abx+(ac+d)abx+(ac+d), with slope abab: the product of the two slopes.

A note on dydx\frac{dy}{dx}

P1.C1 told you to read dydx\frac{dy}{dx} as one symbol, because the derivative is a limit and dydy alone has no meaning yet. That is still true. What has changed is that the nudge ratios are real fractions, and the table above shows that ΔyΔx=ΔyΔu⋅ΔuΔx\frac{\Delta y}{\Delta x}=\frac{\Delta y}{\Delta u}\cdot\frac{\Delta u}{\Delta x} is plain algebra: the Δu\Delta u cancels. Take the limit and each fraction becomes a derivative, so dydx=dydu⋅dudx\frac{dy}{dx}=\frac{dy}{du}\cdot\frac{du}{dx} looks like “cancel the dudu”.

That makes it a very good mnemonic: it tells you which factors belong together and in which units. It is not a proof by itself, for two reasons. The symbol dudu has not been given a meaning, and the algebra needs Δu≠0\Delta u\ne0, which can fail (see the careful proof below). Use the pattern to remember the rule, and the limit to justify it. With several variables (P1.C4 onwards) the cancelling needs more care.

Rates multiply: a nudge travels through two functions

Inside g:
Outside f:

u = g(x) = 3x + 1, y = f(u) = u²

x: 1 → 1.1 Δx = 0.1
↓ × g′(x) = 3 (the inside rate)
u: 4 → 4.3 Δu = 0.3
↓ × f′(u) = 8 (the outside rate, at u = 4)
y: 16 → 18.49 Δy = 2.49
0x = 12y up to 52.8

The product of the two rates, 24, predicts Δy to within 3.6% for this nudge.

x = 1, u = g(x) = 4, y = f(u) = 16
g′(x) = 3, f′(u) = 8
rates multiply: 3 × 8 = 24
central difference of y = f(g(x)) at x (no rule used): 24
Δx = 0.1 gives Δu = 0.3 and Δy = 2.49, so Δy / Δx = 24.9

Each row shows how far one value moves for the nudge, all on the same scale (the blue bar starts at the middle line; right means up). The orange tick is what the rates predict for that row: g′(x) × Δx for u, and g′(x) × f′(u) × Δx for y. The curve is y = f(g(x)); the orange band is its tangent, whose slope is the product of the two rates, and the pink line is the secant for your nudge.

Rates multiply. Pick an inside function g and an outside function f. Each row shows how far x, u and y move for your nudge, on one common scale; the orange tick is what the rates predict. The orange arrows between the rows are the two local rates g′(x) and f′(u). The curve is y = f(g(x)) with its tangent, whose slope is their product. A central difference (no rule used) and the two classic mistakes can be shown next to it.

Things to try with the rates multiply widget:

  1. Start as it opens (g=3x+1g=3x+1, f=u2f=u^2, x=1x=1, Δx=0.1\Delta x=0.1). The xx row moves 0.10.1, the uu row 0.30.3, the yy row 2.492.49. The orange tick on the yy row sits at 2.4=24×0.12.4=24\times0.1. Slide Δx\Delta x towards 0.010.01 and watch the tick and the bar meet.
  2. Switch the inside to −0.5x-0.5x. Its rate is negative, so uu moves the opposite way. With f=u2f=u^2 the outside rate 2u=−12u=-1 is negative too, and two negatives give an overall rate of +0.5+0.5.
  3. Choose g=x2g=x^2 and f=u2f=u^2 and move xx to 0. The inside rate 2x2x is 0 and the status line says the chain is blocked: the product is 0, and y=x4y=x^4 is flat there.
  4. Choose g=3x+1g=3x+1 and f=σ(u)f=\sigma(u) and move xx to 2. Then u=7u=7, where the sigmoid is nearly flat (rate about 0.00090.0009). The outside gear squashes the nudge.
  5. Press Show the two classic mistakes and compare the red lines with the central difference.

Why it is true

Here is the idea behind the rule. Nudge xx by a small hh.

  • The inside moves: Δu≈g′(x) h\Delta u\approx g'(x)\,h (the tangent-line approximation of P1.C1).
  • The outside then moves: Δy≈f′(u) Δu\Delta y\approx f'(u)\,\Delta u (the same approximation, for ff at uu).
  • Put together: Δy≈f′(u) g′(x) h\Delta y\approx f'(u)\,g'(x)\,h, so Δyh≈f′(u) g′(x)\frac{\Delta y}{h}\approx f'(u)\,g'(x).

In the table, with h=0.01h=0.01: Δu=0.03\Delta u=0.03, and f′(4) Δu=0.24f'(4)\,\Delta u=0.24 against a true Δy=0.2409\Delta y=0.2409. The leftover 0.00090.0009 is (Δu)2(\Delta u)^2, which shrinks like h2h^2, faster than hh itself. Each “≈\approx” hides an error that is small even compared with hh, so after dividing by hh and letting h→0h\to0 the errors vanish and the product remains.

This is the reason, not yet a proof. The second approximation is used with a Δu\Delta u that itself changes with hh, and that needs care.

Go deeper A careful proof, and the trap in the quick one

The quick proof writes ΔyΔx=ΔyΔu⋅ΔuΔx\frac{\Delta y}{\Delta x}=\frac{\Delta y}{\Delta u}\cdot\frac{\Delta u}{\Delta x} and takes limits. It divides by Δu\Delta u, which can be 0 even when h≠0h\ne0: take a function gg that is constant on a stretch, or one that wiggles through the same value again and again close to xx. The fix is to build the division into a function that is fine at 0.

Fix xx and put u=g(x)u=g(x). Define, for a number kk,

φ(k)={f(u+k)−f(u)k−f′(u)k≠0,0k=0.\begin{gathered} \varphi(k)= \\ \begin{cases}\frac{f(u+k)-f(u)}{k}-f'(u)&k\ne0,\\[2mm] 0&k=0.\end{cases} \end{gathered}

Because ff is differentiable at uu, φ(k)→0\varphi(k)\to0 as k→0k\to0. By the definition of φ\varphi, for every kk including 0,

f(u+k)−f(u)=(f′(u)+φ(k)) k.\begin{gathered} f(u+k)-f(u) \\ \quad=\bigl(f'(u)+\varphi(k)\bigr)\,k. \end{gathered}

Now let k=g(x+h)−g(x)k=g(x+h)-g(x), so u+k=g(x+h)u+k=g(x+h). Then

f(g(x+h))−f(g(x))h=(f′(u)+φ(k))⋅g(x+h)−g(x)h.\begin{gathered} \frac{f(g(x+h))-f(g(x))}{h} \\ \quad=\bigl(f'(u)+\varphi(k)\bigr) \\ \quad\cdot\frac{g(x+h)-g(x)}{h}. \end{gathered}

As h→0h\to0: k→0k\to0 because a differentiable gg is continuous (g(x+h)−g(x)=h⋅g(x+h)−g(x)h→0⋅g′(x)=0g(x+h)-g(x)=h\cdot\frac{g(x+h)-g(x)}{h}\to0\cdot g'(x)=0), so φ(k)→0\varphi(k)\to0; and the last fraction tends to g′(x)g'(x). The right side tends to f′(u) g′(x)f'(u)\,g'(x). No division by Δu\Delta u ever happened, so the case Δu=0\Delta u=0 is covered.

The rule at work

For each example: name the inside and the outside, differentiate each, read the outside rate at the inside value, multiply. Every answer was also checked with a central difference of the whole function, which uses no rule.

e2x\mathrm{e}^{2x}. Inside 2x2x (rate 2), outside eu\mathrm{e}^{u} (rate eu\mathrm{e}^{u} at u=2xu=2x). So (e2x)′=2 e2x(\mathrm{e}^{2x})'=2\,\mathrm{e}^{2x}: at x=0x=0 it is 22, the number P1.C2 found, and at x=1x=1 it is 2e2=14.7782\mathrm{e}^2=14.778. For any constant kk, (ekx)′=k ekx(\mathrm{e}^{kx})'=k\,\mathrm{e}^{kx}. With k=−1k=-1: (e−x)′=−e−x(\mathrm{e}^{-x})'=-\mathrm{e}^{-x}, the result P1.C2 got from the reciprocal rule. And ax=exln⁡aa^x=\mathrm{e}^{x\ln a} gives (ln⁡a) ax(\ln a)\,a^x, the result P1.C2 got by a limit.

(3x+1)5(3x+1)^5. Inside 3x+13x+1 (rate 3), outside u5u^5 (rate 5u45u^4). So the slope is 5(3x+1)4⋅3=15 (3x+1)45(3x+1)^4\cdot3=15\,(3x+1)^4: 1515 at x=0x=0 and 15⋅44=384015\cdot4^4=3840 at x=1x=1. Expanding the fifth power would take six terms.

ln⁡(1+x2)\ln(1+x^2). Inside 1+x21+x^2 (rate 2x2x), outside ln⁡u\ln u (rate 1u\frac1u). So the slope is 2x1+x2\frac{2x}{1+x^2}, which is 11 at x=1x=1 (P1.C2 saw 11, while the outside rule alone said 0.50.5) and 0.80.8 at x=2x=2.

1+x2\sqrt{1+x^2}. Outside u\sqrt{u} (rate 12u\frac{1}{2\sqrt{u}}), inside 1+x21+x^2 (rate 2x2x). The slope is 2x21+x2=x1+x2\frac{2x}{2\sqrt{1+x^2}}=\frac{x}{\sqrt{1+x^2}}, which is 0.70710.7071 at x=1x=1.

Softplus ln⁡(1+ex)\ln(1+\mathrm{e}^x). Outside ln⁡u\ln u (rate 1u\frac1u), inside 1+ex1+\mathrm{e}^x (rate ex\mathrm{e}^x). So the slope is ex1+ex=σ(x)\frac{\mathrm{e}^x}{1+\mathrm{e}^x}=\sigma(x). P1.C2 only checked this numerically: at x=1x=1 it is σ(1)=0.7311\sigma(1)=0.7311, where the outside rule alone would have said 0.26890.2689. Softplus is a smooth version of ReLU, and its slope rises smoothly from 0 to 1 instead of jumping.

Any real power xnx^n for x>0x>0. P1.C2 stated the power rule for every real nn and left the proof to this lesson. Write xn=enln⁡xx^n=\mathrm{e}^{n\ln x}. The inside nln⁡xn\ln x has rate nx\frac{n}{x}, and the outside eu\mathrm{e}^{u} has rate eu\mathrm{e}^{u}, so

(xn)′=enln⁡x⋅nx=xn⋅nx=n xn−1.(x^n)'=\mathrm{e}^{n\ln x}\cdot\frac nx=x^n\cdot\frac nx=n\,x^{n-1}.

Check: n=−12n=-\tfrac12 at x=4x=4 gives −12⋅4−3/2=−0.0625-\tfrac12\cdot4^{-3/2}=-0.0625, and n=2.5n=2.5 at x=2x=2 gives 7.0717.071. Central differences agree.

Patterns to remember. For a differentiable inside gg:

  • (gn)′=n gn−1 g′(g^n)'=n\,g^{n-1}\,g' (g>0g>0 if nn is not a whole number)
  • (eg)′=g′ eg(\mathrm{e}^{g})'=g'\,\mathrm{e}^{g}
  • (ln⁡g)′=g′g(\ln g)'=\dfrac{g'}{g} (where g>0g>0)
  • (σ(g))′=σ(g)(1−σ(g)) g′\bigl(\sigma(g)\bigr)'=\sigma(g)\bigl(1-\sigma(g)\bigr)\,g'

Chain rule or product rule?

Look at the last operation you would do when evaluating the function. If it is a product, use the product rule first. If it is a function applied to something, use the chain rule first. Often you need both.

Take x e2xx\,\mathrm{e}^{2x}. The last operation is a product of xx and e2x\mathrm{e}^{2x}. The product rule gives 1⋅e2x+x⋅(e2x)′1\cdot\mathrm{e}^{2x}+x\cdot(\mathrm{e}^{2x})', and the chain rule supplies (e2x)′=2e2x(\mathrm{e}^{2x})'=2\mathrm{e}^{2x}. So the slope is (1+2x) e2x(1+2x)\,\mathrm{e}^{2x}: 272.99272.99 at x=2x=2. Using the chain rule alone, as if xx were a constant, gives 2x e2x=218.392x\,\mathrm{e}^{2x}=218.39. Using the product rule and forgetting the factor 2 gives (1+x) e2x=163.79(1+x)\,\mathrm{e}^{2x}=163.79.

Longer chains: multiply them all

With three functions, y=f3(f2(f1(x)))y=f_3(f_2(f_1(x))), apply the rule twice. Name the values u1=f1(x)u_1=f_1(x) and u2=f2(u1)u_2=f_2(u_1). Then

dydx=f3′(u2)⋅f2′(u1)⋅f1′(x).\frac{dy}{dx}=f_3'(u_2)\cdot f_2'(u_1)\cdot f_1'(x).

Each rate is read at the value that arrives at that function. With four functions there are four factors, and so on. This is why a forward pass comes first: you need the values u1,u2,…u_1,u_2,\dots before you can read off the rates.

The sigmoid as four small steps

P1.C2 got σ′=σ(1−σ)\sigma'=\sigma(1-\sigma) from the reciprocal rule. Here is the chain-rule route, with the sigmoid cut into four steps, at z=2z=2:

z → −z  u → eu  v → 1+v  s → 1/s  σ.z\ \xrightarrow{\ -z\ }\ u\ \xrightarrow{\ \mathrm{e}^{u}\ }\ v\ \xrightarrow{\ 1+v\ }\ s\ \xrightarrow{\ 1/s\ }\ \sigma .

The forward values are u=−2u=-2, v=e−2=0.1353v=\mathrm{e}^{-2}=0.1353, s=1.1353s=1.1353 and σ=1/s=0.8808\sigma=1/s=0.8808. The four local rates are −1-1, eu=0.1353\mathrm{e}^{u}=0.1353, 11 and −1s2=−0.7758-\frac{1}{s^2}=-0.7758. Their product is

(−1)×0.1353×1×(−0.7758)=0.1050,\begin{aligned} &(-1)\times0.1353\times1\times(-0.7758)\\ &=0.1050, \end{aligned}

which is σ′(2)=0.8808×0.1192=0.104994\sigma'(2)=0.8808\times0.1192=0.104994. In symbols, σ′(z)=(−1s2)⋅1⋅e−z⋅(−1)=e−z(1+e−z)2=σ(z)(1−σ(z))\sigma'(z)=\bigl(-\tfrac1{s^2}\bigr)\cdot1\cdot\mathrm{e}^{-z}\cdot(-1)=\frac{\mathrm{e}^{-z}}{(1+\mathrm{e}^{-z})^2}=\sigma(z)\bigl(1-\sigma(z)\bigr), the same answer as before.

Backward: the seed of backpropagation

Multiplying the four rates from the output end gives a running product:

  • the slope of σ\sigma with respect to itself is 11 (the start);
  • with respect to ss: 1×(−0.7758)=−0.77581\times(-0.7758)=-0.7758;
  • with respect to vv: −0.7758×1=−0.7758-0.7758\times1=-0.7758;
  • with respect to uu: −0.7758×0.1353=−0.1050-0.7758\times0.1353=-0.1050;
  • with respect to zz: −0.1050×(−1)=0.1050-0.1050\times(-1)=0.1050.

One sweep from the end gave the slope of the output with respect to every value along the way, not just the first one. That is backpropagation: each node multiplies the slope arriving from above by its own local rate (P4.8 does this on a bigger graph, with the same numbers shown step by step).

Go deeper Why start at the end, when numbers can be multiplied in any order

For plain numbers the order does not change the product. It matters when many values feed one result. Going from the end, each running product is the slope of the end with respect to that value, and it is reused by everything that feeds into it. A network with a million weights and one loss then needs one backward sweep, not a million separate forward ones. With vectors the factors become matrices (the Jacobian of P1.C7), the order changes the cost, and the backward direction is cheap when the end is a single number. P1.C10 explains this as forward mode and reverse mode.

Three derivatives from machine learning

tanh from the sigmoid. P1.A5 showed tanh⁡z=2σ(2z)−1\tanh z=2\sigma(2z)-1. The inside is 2z2z (rate 2), and the outside 2σ(u)−12\sigma(u)-1 has rate 2σ′(u)2\sigma'(u). So

tanh⁡′(z)=2σ′(2z)⋅2=4 σ(2z)(1−σ(2z)).\begin{aligned} \tanh'(z)&=2\sigma'(2z)\cdot2\\ &=4\,\sigma(2z)\bigl(1-\sigma(2z)\bigr). \end{aligned}

With s=σ(2z)s=\sigma(2z) we have tanh⁡z=2s−1\tanh z=2s-1 and 1−tanh⁡2z=1−(2s−1)2=4s(1−s)1-\tanh^2z=1-(2s-1)^2=4s(1-s), which is the same thing, so this agrees with P1.C2’s tanh⁡′=1−tanh⁡2\tanh'=1-\tanh^2. At z=0z=0 it gives 4×0.25=14\times0.25=1 and at z=2z=2 it gives 4×0.9820×0.0180=0.07074\times0.9820\times0.0180=0.0707 (more digits: 0.0706510.070651). The factor 4 at the middle is two factors of 2: the 22 inside squeezes the curve sideways, and the 22 outside stretches it upward. That is why tanh is four times as steep as the sigmoid at 0.

The squared error. For one example the loss is L=(wx+b−y)2L=(wx+b-y)^2. Let e=wx+b−ye=wx+b-y be the error. The outside e2e^2 has rate 2e2e. The inside has rate xx with respect to ww and rate 11 with respect to bb (the other values held fixed: nudging one parameter at a time is P1.C4). So

dLdw=2e x,dLdb=2e.\frac{dL}{dw}=2e\,x,\qquad\frac{dL}{db}=2e.

With x=2x=2, y=3y=3, w=1.5w=1.5 and b=−1b=-1 (the numbers of P4.8): e=−1e=-1, so the slopes are −4-4 and −2-2. P1.C2 got 2x(wx−y)2x(wx-y) by expanding the square first; here no expansion is needed. For x=3x=3, y=6y=6 the chain rule gives 2(3w−6)⋅3=18w−362(3w-6)\cdot3=18w-36, the same as the expanded 9w2−36w+369w^2-36w+36 differentiated. For the three-example loss of P0.2, averaging 2x(wx−y)2x(wx-y) over the examples gives 23(1⋅(−1)+2⋅(−1)+3⋅(−4))=−10\frac23\bigl(1\cdot(-1)+2\cdot(-1)+3\cdot(-4)\bigr)=-10 at w=1w=1, the slope that took a page in P1.C1. The slope of an average is the average of the slopes.

The logistic loss. If the right answer is “yes” and the model gives probability p=σ(z)p=\sigma(z), the loss is −ln⁡σ(z)-\ln\sigma(z). The outside −ln⁡p-\ln p has rate −1p-\frac1p, and the inside σ(z)\sigma(z) has rate σ(1−σ)\sigma(1-\sigma). The factors σ\sigma cancel:

ddz(−ln⁡σ(z))=−1σ⋅σ(1−σ)=σ(z)−1.\begin{aligned} \frac{d}{dz}\bigl(-\ln\sigma(z)\bigr)&=-\frac{1}{\sigma}\cdot\sigma(1-\sigma)\\ &=\sigma(z)-1. \end{aligned}

At z=0z=0 it is −0.5-0.5, at z=2z=2 it is −0.1192-0.1192, and at z=−2z=-2 it is −0.8808-0.8808. It is “prediction minus target” again, and it does not fade when the model is confidently wrong: at z=−5z=-5 the slope is −0.9933-0.9933. Compare the squared error on the same sigmoid, (σ(z)−1)2(\sigma(z)-1)^2. Its slope is 2(σ−1) σ(1−σ)2(\sigma-1)\,\sigma(1-\sigma), and at z=−5z=-5 it is only −0.0132-0.0132, because the flat sigmoid tail squashes it. This is one reason classification uses the log loss (P3.A7, P4.6).

A chain of local rates

The next widget shows the whole procedure on small chains: the forward values in blue, the local rates and the backward products in orange. A slider replays the backward pass from the end.

Chain of local rates: forward values, backward products

L = (w·x + b − y)², with x = 2 and y = 3 held fixed

Slope with respect to:
Value forward local rate end slope
w 1.5 −4
u = w·xmultiply by x = 2 3 2 −2
ŷ = u + badd b = −1 2 1 −2
e = ŷ − ysubtract y = 3 −1 1 −2
L = e²square 1 −2 1
end slope at w = (−2) × 1 × 1 × 2 = −4
central difference of the whole chain: −4

The product of the local rates, −4, agrees with a central difference of the whole chain, −4.

Blue numbers go forward, from the first value to the end. Orange numbers go backward: the local rate is how much a step's result changes per unit change of its input, and the end slope is how much the end changes per unit change of that value. Each end slope is the one below it in the table times the local rate between them. The slider replays the backward pass from the end.

Chain of local rates. Choose a chain: squared error (the numbers of P4.8), a sigmoid with a logistic loss, or a stack of sigmoid layers. The blue column is the forward pass. The orange columns are each step's local rate and the end slope: how much the end changes per unit change of that value, found by multiplying the local rates from the end. A central difference of the whole chain checks the product. In the stack, a bar shows how many powers of ten of the slope are left.

Things to try with the chain of local rates widget:

  1. Squared error, as it opens (w=1.5w=1.5, b=−1b=-1). The values are 1.51.5, 33, 22, −1-1, 11, the local rates are 22, 11, 11, −2-2, and the end slopes are −4-4, −2-2, −2-2, −2-2, 11. The slope with respect to ww is −4-4, the number in P4.8. Drag the backward slider one step at a time, then switch to the bias bb: its slope is −2-2.
  2. Sigmoid and logistic loss (w=0.5w=0.5): z=0z=0, p=0.5p=0.5, and the rates 22, 11, 0.250.25, −2-2 multiply to −1-1. Move ww to 33 (confidently right) and the slope with respect to ww almost vanishes, about −0.013-0.013. Move ww to −3-3 (confidently wrong) and it is about −2.0-2.0.
  3. Stack of sigmoids, one number per layer with w=1w=1, b=0b=0 and input 00. Five layers give a product of about 6.8×10−46.8\times10^{-4} and ten layers about 3.9×10−73.9\times10^{-7}. Raise ww to 88, set b=−4b=-4 and the input to 0.50.5: every layer sits at z=0z=0 with rate wσ′(0)=2w\sigma'(0)=2, and ten layers give 210=10242^{10}=1024.

Vanishing and exploding products

The sigmoid slope σ′(z)=σ(1−σ)\sigma'(z)=\sigma(1-\sigma) is never more than 0.250.25 (P1.A5, P1.C2). So each sigmoid layer multiplies the backward signal by at most 0.250.25, times the weight that feeds it. In the best case, 0.250.25 per layer:

  • 1 layer: 0.250.25
  • 2 layers: 0.06250.0625
  • 3 layers: 0.01560.0156
  • 5 layers: 0.255≈0.0010.25^5\approx0.001
  • 10 layers: 0.2510≈0.0000010.25^{10}\approx0.000001

That is the picture P1.A5 sketched. Two corrections make it honest. The weights are factors too: each layer contributes w σ′(z)w\,\sigma'(z), so it is the size of ∣w∣/4|w|/4 that sets the bound, and with ∣w∣|w| above 4 the bound allows growth. And a unit pushed into the flat tail has a rate far below 0.250.25: at z=6z=6 the slope is 0.00250.0025, so three saturated layers give 0.00253≈1.6×10−80.0025^3\approx1.6\times10^{-8}.

So a long product of rates below 1 shrinks fast (vanishing gradients), and a long product of rates above 1 grows fast (exploding gradients). The chain rule is not at fault: the product is exactly right, and it is tiny or huge. The layers near the input then barely learn, or learn wildly. This is the subject of P4.16.

Why does ReLU help? Its slope is 1 where the unit is on, so an active ReLU unit passes the signal back at the size of its weight, with no extra factor of 14\frac14. A unit that is off has slope 0 and blocks the signal, which is the flat spot again. P4.4 compares the activations.

Go deeper One variable feeding two paths (a preview)

Sometimes a value reaches the end by two routes. Let u=x2u=x^2 and v=x3v=x^3, and let y=u vy=u\,v. Nudging xx changes yy through uu and through vv, and the two effects add. The effect through uu is the rate of yy with respect to uu (which is vv) times dudx=2x\frac{du}{dx}=2x. The effect through vv is uu times dvdx=3x2\frac{dv}{dx}=3x^2. At x=1x=1: 1⋅2+1⋅3=51\cdot2+1\cdot3=5. Check: y=x5y=x^5 has slope 5x4=55x^4=5.

The rule for such cases is to multiply along each path and add the paths. The notation for “the rate of yy with respect to uu while vv is held fixed” is the partial derivative of P1.C4, and the general statement uses the Jacobian of P1.C7. Backpropagation adds the gradients that arrive from each use of a value (the box “What if a value is used in more than one place?” in P4.8).

Go deeper Slopes of inverse functions, and a second proof for the logarithm

If gg undoes ff, so that f(g(y))=yf(g(y))=y, apply the chain rule to both sides: f′(g(y))⋅g′(y)=1f'(g(y))\cdot g'(y)=1, so g′(y)=1f′(g(y))g'(y)=\dfrac{1}{f'(g(y))} wherever f′(g(y))≠0f'(g(y))\ne0 (assuming gg is differentiable). With f=exf=\mathrm{e}^{x} and g=ln⁡g=\ln: (ln⁡y)′=1eln⁡y=1y(\ln y)'=\dfrac{1}{\mathrm{e}^{\ln y}}=\dfrac1y. P1.C2 proved this from a limit, and the mirror-image picture there says the same: slopes of a function and its inverse are reciprocals.

The chain rule in three depths

Intuition

A nudge passes through a chain of machines. Each machine multiplies the size of the nudge by its own gear ratio at the moment, so the final change is the starting nudge times all the ratios. If one machine does nothing (ratio 0), nothing comes out. If one is very flat, the nudge is squeezed, however large the others are.

For a network this means: the effect of a weight on the loss is the product of how much it moves its neuron, how much that moves the next, and so on to the loss. Multiplying from the loss backward gives that number for every value in one pass.

Math

If gg is differentiable at xx and ff is differentiable at g(x)g(x), then f∘gf\circ g is differentiable at xx and

(f∘g)′(x)=f′(g(x)) g′(x).(f\circ g)'(x)=f'\bigl(g(x)\bigr)\,g'(x).

With u=g(x)u=g(x) and y=f(u)y=f(u): dydx=dydududx\frac{dy}{dx}=\frac{dy}{du}\frac{du}{dx}. For a chain of nn functions, with u0=xu_0=x and uk=fk(uk−1)u_k=f_k(u_{k-1}):

dydx=∏k=1nfk′(uk−1).\frac{dy}{dx}=\prod_{k=1}^{n}f_k'(u_{k-1}).

Proof idea: f(u+k)−f(u)=(f′(u)+φ(k))kf(u+k)-f(u)=\bigl(f'(u)+\varphi(k)\bigr)k with φ(k)→0\varphi(k)\to0, applied with k=g(x+h)−g(x)k=g(x+h)-g(x) (the careful proof above).

Code

import math

def central(f, x, h=1e-5):
    return (f(x + h) - f(x - h)) / (2 * h)

def sigmoid(z):
    return 1 / (1 + math.exp(-z))

# slope of sigmoid(3x - 1) at x = 1: sigmoid'(2) * 3
z = 3 * 1 - 1
rule = sigmoid(z) * (1 - sigmoid(z)) * 3
print(rule, central(lambda x: sigmoid(3 * x - 1), 1.0))   # both about 0.3150

PyTorch multiplies the local rates for you (backpropagation, P4.8). This runs in Colab or on your machine, not in the browser here:

import torch
x = torch.tensor(1.0, requires_grad=True)
y = torch.sigmoid(3 * x - 1)
y.backward()
print(x.grad)     # about 0.3150

Try it: the chain rule against a finite difference

The first cell checks the rule on seven functions and also shows the “f′f' at xx” mistake. The second runs the four-step sigmoid backward and compares a stack of sigmoid layers with the best case 0.25n0.25^n. Predict the output first, then change the numbers.

Try it: f′(g(x)) · g′(x) against a central difference

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

Challenge: add e−x2\mathrm{e}^{-x^2} at x=1x=1 (inside −x2-x^2, outside eu\mathrm{e}^{u}). The slope should be −2/e=−0.7358-2/\mathrm{e}=-0.7358.

Try it: a backward pass, and a stack of sigmoids

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

Challenge: find a weight ww and bias bb that keep ten layers near a product of 1 (hint: make every layer sit at z=0z=0 and set wσ′(0)=1w\sigma'(0)=1, so w=4w=4 and b=−2b=-2 with input 0.50.5).

Common mistakes

Check your understanding

  1. Let f(u)=u3f(u)=u^3 and g(x)=2x+2g(x)=2x+2. What is the slope of f(g(x))f(g(x)) at x=1x=1?

  2. What is the slope of e−3x\mathrm{e}^{-3x} at x=0x=0?

  3. A chain of three steps has local rates 0.50.5, −4-4 and 0.250.25. What is the rate of the end with respect to the start?

  4. What is the slope of x e2xx\,\mathrm{e}^{2x} at x=2x=2?

  5. Why can a long stack of sigmoid layers make the layers near the input learn very slowly?

Exercises

  1. Differentiate (2x−5)4(2x-5)^4 and evaluate the slope at x=3x=3.
    Show answerInside 2x−52x-5 (rate 2), outside u4u^4 (rate 4u34u^3). The slope is 4(2x−5)3⋅2=8(2x−5)34(2x-5)^3\cdot2=8(2x-5)^3. At x=3x=3, u=1u=1, so it is 88.
  2. Differentiate e−x2\mathrm{e}^{-x^2} and find its value at x=1x=1.
    Show answerInside −x2-x^2 (rate −2x-2x), outside eu\mathrm{e}^{u}. The slope is −2x e−x2-2x\,\mathrm{e}^{-x^2}, which is −2/e=−0.7358-2/\mathrm{e}=-0.7358 at x=1x=1. (This bell shape reappears in probability, and its slope is 0 at x=0x=0, its peak.)
  3. Show that ddxln⁡σ(x)=1−σ(x)\frac{d}{dx}\ln\sigma(x)=1-\sigma(x) and evaluate it at x=0x=0 and x=2x=2.
    Show answer(ln⁡g)′=g′g(\ln g)'=\frac{g'}{g} with g=σg=\sigma gives σ(1−σ)σ=1−σ\frac{\sigma(1-\sigma)}{\sigma}=1-\sigma. At x=0x=0: 0.50.5. At x=2x=2: 1−0.8808=0.11921-0.8808=0.1192. This is minus the slope of the logistic loss −ln⁡σ-\ln\sigma.
  4. Find the slope of σ(3x−1)\sigma(3x-1) at x=1x=1.
    Show answerInside 3x−13x-1 (rate 3), which is 22 at x=1x=1. The outside slope is σ′(2)=0.104994\sigma'(2)=0.104994. The product is 3×0.104994=0.31503\times0.104994=0.3150.
  5. Find the slope of ln⁡(1+(2x+1)2)\ln\bigl(1+(2x+1)^2\bigr) at x=0x=0, using three links.
    Show answeru=2x+1u=2x+1 (rate 2), v=1+u2v=1+u^2 (rate 2u2u), y=ln⁡vy=\ln v (rate 1v\frac1v). At x=0x=0: u=1u=1, v=2v=2. The rates are 22, 22 and 12\frac12, so the slope is 2×2×12=22\times2\times\frac12=2.
  6. Find ddztanh⁡(3z)\frac{d}{dz}\tanh(3z) at z=0z=0 in two ways: with tanh⁡′=1−tanh⁡2\tanh'=1-\tanh^2 and through tanh⁡u=2σ(2u)−1\tanh u=2\sigma(2u)-1.
    Show answerFirst way: the inside 3z3z has rate 3, and 1−tanh⁡2(0)=11-\tanh^2(0)=1, so the slope is 33. Second way: tanh⁡(3z)=2σ(6z)−1\tanh(3z)=2\sigma(6z)-1 has slope 2⋅6⋅σ′(0)=12×0.25=32\cdot6\cdot\sigma'(0)=12\times0.25=3. Both agree.
  7. Let f(u)=u2f(u)=u^2 and g(x)=x+1g(x)=x+1. Find the slope of f(g(x))f(g(x)) and of g(f(x))g(f(x)) at x=2x=2. Why do they differ?
    Show answerf(g(x))=(x+1)2f(g(x))=(x+1)^2 has slope 2(x+1)=62(x+1)=6 at x=2x=2. g(f(x))=x2+1g(f(x))=x^2+1 has slope 2x=42x=4. The functions are different (the order of the composition matters), so their slopes differ.
  8. Five sigmoid layers each have rate 0.250.25 (an idealised best case: every unit at z=0z=0 and weight 1; with w=1w=1, b=0b=0 and input 0 the actual product is about 6.8×10−46.8\times10^{-4}). By about what factor is a nudge at the input scaled at the output? What changes if the weight in each layer is 4?
    Show answer0.255=0.0009770.25^5=0.000977, about a thousandth. With weight 4 each layer’s rate is 4×0.25=14\times0.25=1 (when z=0z=0), so the product is 11 and the nudge arrives unchanged.
  9. A student writes ddxln⁡(1+x2)=11+x2\frac{d}{dx}\ln(1+x^2)=\frac{1}{1+x^2}. Find the error, give the right slope, and compare the two at x=1x=1.
    Show answerThe inside rate 2x2x was forgotten. The slope is 2x1+x2\frac{2x}{1+x^2}. At x=1x=1 the student’s answer is 0.50.5 and the right one is 11.
  10. Find the point where x e−3xx\,\mathrm{e}^{-3x} has slope 0, and the value of the function there.
    Show answerProduct rule with the chain rule: e−3x+x⋅(−3)e−3x=(1−3x)e−3x\mathrm{e}^{-3x}+x\cdot(-3)\mathrm{e}^{-3x}=(1-3x)\mathrm{e}^{-3x}. This is 00 at x=13x=\tfrac13, where the value is 13e−1=0.1226\tfrac13\mathrm{e}^{-1}=0.1226.

Next: P1.C4 lets a function have several inputs and nudges them one at a time (partial derivatives), and P1.C5 collects those slopes into the gradient. The chain rule you just learned then runs through all of them, and P4.8 uses it on a whole network.

Key takeaways

  • A composition f(g(x))f(g(x)) computes the inside u=g(x)u=g(x) first and then the outside y=f(u)y=f(u). The order matters: with f(u)=u2f(u)=u^2 and g(x)=x+1g(x)=x+1, f(g(2))=9f(g(2))=9 but g(f(2))=5g(f(2))=5.
  • Chain rule: (f∘g)′(x)=f′(g(x)) g′(x)(f\circ g)'(x)=f'(g(x))\,g'(x), or dydx=dydu⋅dudx\frac{dy}{dx}=\frac{dy}{du}\cdot\frac{du}{dx}. In words: the slope of the outside, taken at the value u=g(x)u=g(x) that reaches it, times the slope of the inside. It holds where gg is differentiable at xx and ff is differentiable at g(x)g(x).
  • Rates multiply, like gears. A nudge hh to xx moves uu by about g′(x) hg'(x)\,h, and that moves yy by about f′(u)⋅g′(x) hf'(u)\cdot g'(x)\,h. If any one rate is 0, nothing gets through, so the whole product is 0.
  • dydx\frac{dy}{dx} is still a limit, but the nudge ratios ΔyΔx=ΔyΔu⋅ΔuΔx\frac{\Delta y}{\Delta x}=\frac{\Delta y}{\Delta u}\cdot\frac{\Delta u}{\Delta x} are real fractions. Cancelling dudu is a good way to remember the rule, not a proof of it.
  • Useful patterns: (eg)′=g′ eg(\mathrm{e}^{g})'=g'\,\mathrm{e}^{g}, (ln⁡g)′=g′g(\ln g)'=\frac{g'}{g} (for g>0g>0), (gn)′=n gn−1g′(g^n)'=n\,g^{n-1}g' (g>0g>0 if nn is not a whole number), σ(g)′=σ(g)(1−σ(g))g′\sigma(g)'=\sigma(g)\bigl(1-\sigma(g)\bigr)g'. The chain rule also gives (xn)′=n xn−1(x^n)'=n\,x^{n-1} for any real nn (with x>0x>0) and ddz(2σ(2z)−1)=1−tanh⁡2z\frac{d}{dz}\bigl(2\sigma(2z)-1\bigr)=1-\tanh^2 z.
  • A squared error (wx+b−y)2(wx+b-y)^2 has slopes 2e x2e\,x and 2e2e with e=wx+b−ye=wx+b-y. A logistic loss −ln⁡σ(z)-\ln\sigma(z) has slope σ(z)−1\sigma(z)-1: its slope stays large when the model is confidently wrong.
  • For a long chain, multiply all the local rates. Doing it from the output backward gives the slope of the end with respect to every value on the way, in one sweep: this is backpropagation (P4.8). A sigmoid has σ′≤14\sigma'\le\frac14, so a long stack of them can shrink the product towards 0: vanishing gradients (P4.16).
Found a mistake? Tell us