TExcelTAD
Home › Calculus in Depth › The Chain Rule

The Chain Rule

When a quantity depends on intermediate variables that themselves depend on other variables, the chain rule says how to differentiate through the whole chain: add up the contributions of every path from the output back to the input. This lesson states the general multivariable chain rule, proves it from differentiability, turns it into a tool for implicit differentiation, and shows that backpropagation in neural networks is this rule applied to a computational graph.

For the one-variable rule see The Chain Rule; the survey version of this lesson is The Multivariable Chain Rule.

Case 1: one parameter

Let z=f(x,y)z = f(x, y) be differentiable, and let x=g(t)x = g(t), y=h(t)y = h(t) be differentiable. Then zz is a function of tt and

dzdt=∂f∂x⋅dxdt+∂f∂y⋅dydt\frac{dz}{dt} = \frac{\partial f}{\partial x} \cdot \frac{dx}{dt} + \frac{\partial f}{\partial y} \cdot \frac{dy}{dt}

In vector form, with r(t)=⟨x(t),y(t)⟩\mathbf{r}(t) = \langle x(t), y(t) \rangle: dzdt=∇f(r(t))⋅r′(t)\frac{dz}{dt} = \nabla f(\mathbf{r}(t)) \cdot \mathbf{r}'(t). The rate of change of ff along a moving point is the gradient dotted with the velocity.

Proof. Let Δt\Delta t produce changes Δx\Delta x, Δy\Delta y. Differentiability of ff means

Δz=fx Δx+fy Δy+ε1Δx+ε2Δy,ε1,ε2→0 as (Δx,Δy)→(0,0)\Delta z = f_x\,\Delta x + f_y\,\Delta y + \varepsilon_1 \Delta x + \varepsilon_2 \Delta y, \qquad \varepsilon_1, \varepsilon_2 \to 0 \text{ as } (\Delta x, \Delta y) \to (0, 0)

Divide by Δt\Delta t and let Δt→0\Delta t \to 0. Since gg and hh are differentiable they are continuous, so Δx,Δy→0\Delta x, \Delta y \to 0 and ε1,ε2→0\varepsilon_1, \varepsilon_2 \to 0, while Δx/Δt→dx/dt\Delta x/\Delta t \to dx/dt and Δy/Δt→dy/dt\Delta y/\Delta t \to dy/dt. The ε\varepsilon-terms vanish, leaving the formula. Note that the proof needs ff to be differentiable, not merely to have partial derivatives.

Example: the temperature on a plate is T(x,y)=x2y+3yT(x, y) = x^2y + 3y, and an ant walks along x=cos⁡tx = \cos t, y=sin⁡ty = \sin t. At t=π/2t = \pi/2 the ant is at (0,1)(0, 1) with velocity ⟨−1,0⟩\langle -1, 0 \rangle:

Tx=2xy=0,Ty=x2+3=3dTdt=0⋅(−1)+3⋅0=0\begin{aligned} &T_x = 2xy = 0, \quad T_y = x^2 + 3 = 3 \\ &\frac{dT}{dt} = 0 \cdot (-1) + 3 \cdot 0 = 0 \end{aligned}

Case 2 and the general rule

If z=f(x,y)z = f(x, y) with x=g(s,t)x = g(s, t), y=h(s,t)y = h(s, t), then holding the other parameter fixed gives

∂z∂s=∂z∂x⋅∂x∂s+∂z∂y⋅∂y∂s∂z∂t=∂z∂x⋅∂x∂t+∂z∂y⋅∂y∂t\begin{aligned} \frac{\partial z}{\partial s} &= \frac{\partial z}{\partial x} \cdot \frac{\partial x}{\partial s} + \frac{\partial z}{\partial y} \cdot \frac{\partial y}{\partial s} \\[1ex] \frac{\partial z}{\partial t} &= \frac{\partial z}{\partial x} \cdot \frac{\partial x}{\partial t} + \frac{\partial z}{\partial y} \cdot \frac{\partial y}{\partial t} \end{aligned}

General version. If uu depends on x1,…,xnx_1, \ldots, x_n and each xjx_j depends on t1,…,tmt_1, \ldots, t_m, then for each ii

∂u∂ti=∑j∂u∂xj⋅∂xj∂ti\frac{\partial u}{\partial t_i} = \sum_{j} \frac{\partial u}{\partial x_j} \cdot \frac{\partial x_j}{\partial t_i}

A tree diagram makes this mechanical: draw uu at the top, its variables below, their variables below those. The derivative of uu with respect to tit_i is the sum over all branches from uu down to tit_i of the product of the derivatives along each branch.

In matrix language this is a product of Jacobians, Ju∘x(t)=Ju(x)⋅Jx(t)J_{u \circ x}(t) = J_u(x) \cdot J_x(t): a (1×n)(1 \times n) row times an (n×m)(n \times m) matrix.

python · try it yourself
import sympy as sp

s, t = sp.symbols("s t")
x = s**2 * t
y = s + sp.exp(t)
X, Y = sp.symbols("X Y")
f = X * sp.sin(Y) + Y**2

# chain rule: sum over the two branches
chain_s = (sp.diff(f, X) * sp.diff(x, s) + sp.diff(f, Y) * sp.diff(y, s)).subs({X: x, Y: y})
direct_s = sp.diff(f.subs({X: x, Y: y}), s)
print("dz/ds via chain rule:", sp.simplify(chain_s))
print("difference from direct:", sp.simplify(chain_s - direct_s))

# Jacobian product at (s, t) = (1, 0)
Jf = sp.Matrix([[sp.diff(f, X), sp.diff(f, Y)]]).subs({X: x, Y: y})
Jx = sp.Matrix([x, y]).jacobian([s, t])
print("J at (1, 0):", (Jf * Jx).subs({s: 1, t: 0}).applyfunc(sp.nsimplify))
dz/ds via chain rule: s**2*t*cos(s + exp(t)) + 2*s*t*sin(s + exp(t)) + 2*s + 2*exp(t)
difference from direct: 0
J at (1, 0): Matrix([[4, sin(2) + 4]])

At (s,t)=(1,0)(s, t) = (1, 0) we have x=0x = 0 and y=2y = 2. By hand, with fX=sin⁡Yf_X = \sin Y and fY=Xcos⁡Y+2Yf_Y = X\cos Y + 2Y:

∂z∂s=fXxs+fYys=sin⁡2⋅(2st)+(0⋅cos⁡2+4)⋅1=0+4=4∂z∂t=fXxt+fYyt=sin⁡2⋅s2+4⋅et=sin⁡2+4\begin{aligned} \frac{\partial z}{\partial s} &= f_X x_s + f_Y y_s = \sin 2 \cdot (2st) + (0 \cdot \cos 2 + 4) \cdot 1 = 0 + 4 = 4 \\ \frac{\partial z}{\partial t} &= f_X x_t + f_Y y_t = \sin 2 \cdot s^2 + 4 \cdot e^t = \sin 2 + 4 \end{aligned}

which is the row of the Jacobian product.

Implicit differentiation

Suppose F(x,y)=0F(x, y) = 0 defines yy implicitly as a differentiable function of xx. Differentiate F(x,y(x))=0F(x, y(x)) = 0 with the chain rule: Fx⋅1+Fy⋅dy/dx=0F_x \cdot 1 + F_y \cdot dy/dx = 0, so

dydx=−FxFy(where Fy≠0)\frac{dy}{dx} = -\frac{F_x}{F_y} \qquad \text{(where } F_y \ne 0\text{)}

Likewise, if F(x,y,z)=0F(x, y, z) = 0 defines z=z(x,y)z = z(x, y):

∂z∂x=−FxFz,∂z∂y=−FyFz(where Fz≠0)\frac{\partial z}{\partial x} = -\frac{F_x}{F_z}, \qquad \frac{\partial z}{\partial y} = -\frac{F_y}{F_z} \qquad \text{(where } F_z \ne 0\text{)}

The Implicit Function Theorem guarantees that such a function exists near a point where F=0F = 0, FF has continuous partials, and Fy≠0F_y \ne 0 (or Fz≠0F_z \ne 0).

Example: x3+y3=6xyx^3 + y^3 = 6xy, the folium. Fx=3x2−6yF_x = 3x^2 - 6y, Fy=3y2−6xF_y = 3y^2 - 6x, so dy/dx=−(x2−2y)/(y2−2x)dy/dx = -(x^2 - 2y)/(y^2 - 2x). At (3,3)(3, 3): dy/dx=−(9−6)/(9−6)=−1dy/dx = -(9 - 6)/(9 - 6) = -1.

In software: backpropagation is the chain rule

A neural network computes the loss through a graph of simple operations. Reverse-mode automatic differentiation (backpropagation) walks the graph from the output back to the inputs, multiplying local derivatives along each edge and summing where branches meet, exactly the tree-diagram rule. Reverse mode computes the whole gradient of one scalar output in about the cost of one or two forward passes, however many inputs there are; that is why training networks with billions of weights is feasible.

python · try it yourself
import math

# forward pass for L = (w*x + b - y)^2 * 0.5 with a tanh activation
w, b, x, y = 0.8, -0.2, 1.5, 0.3
z = w * x + b          # node 1
a = math.tanh(z)       # node 2
L = 0.5 * (a - y)**2   # node 3

# backward pass: multiply local derivatives along the chain
dL_da = a - y
da_dz = 1 - a**2
dL_dz = dL_da * da_dz
dL_dw, dL_db = dL_dz * x, dL_dz * 1.0
print(f"L = {L:.6f}   dL/dw = {dL_dw:.6f}   dL/db = {dL_db:.6f}")

# check with central differences
def loss(w, b):
    return 0.5 * (math.tanh(w * x + b) - y)**2
h = 1e-6
print(f"numeric dL/dw = {(loss(w + h, b) - loss(w - h, b)) / (2 * h):.6f}")
print(f"numeric dL/db = {(loss(w, b + h) - loss(w, b - h)) / (2 * h):.6f}")
L = 0.106535   dL/dw = 0.290787   dL/db = 0.193858
numeric dL/dw = 0.290787
numeric dL/db = 0.193858

More: Backpropagation and Automatic Differentiation.

Other places it appears:

  • Physics and graphics: changing coordinates (world ↔ local, Cartesian ↔ polar) transforms derivatives with the Jacobian of the map, e.g. normals and velocities under a transform.
  • Related rates in simulations: dV/dtdV/dt of a changing shape from dr/dtdr/dt and dh/dtdh/dt.

Exercises

Exercise 1: Along a curve

Let w=xyzw = xyz with x=tx = t, y=t2y = t^2, z=t3z = t^3. Compute dw/dtdw/dt by the chain rule and check by substituting first.

Answer

dw/dt=6t5dw/dt = 6t^5.

Solution
dwdt=yz⋅1+xz⋅2t+xy⋅3t2=t5+2t5+3t5=6t5direct: w=t6,dwdt=6t5\begin{aligned} &\frac{dw}{dt} = yz \cdot 1 + xz \cdot 2t + xy \cdot 3t^2 = t^5 + 2t^5 + 3t^5 = 6t^5 \\ &\text{direct: } w = t^6, \quad \frac{dw}{dt} = 6t^5 \end{aligned}

Exercise 2: Polar coordinates

Let z=f(x,y)z = f(x, y) with x=rcos⁡θx = r\cos\theta, y=rsin⁡θy = r\sin\theta. Express ∂z/∂r\partial z/\partial r and ∂z/∂θ\partial z/\partial\theta in terms of fxf_x and fyf_y, and show that fx2+fy2=(∂z/∂r)2+(1/r2)(∂z/∂θ)2f_x^2 + f_y^2 = (\partial z/\partial r)^2 + (1/r^2)(\partial z/\partial\theta)^2.

Answer

∂z/∂r=fxcos⁡θ+fysin⁡θ\partial z/\partial r = f_x\cos\theta + f_y\sin\theta and ∂z/∂θ=−fxrsin⁡θ+fyrcos⁡θ\partial z/\partial\theta = -f_x r\sin\theta + f_y r\cos\theta; the identity follows by squaring and adding.

Solution
∂z∂r=fxcos⁡θ+fysin⁡θ∂z∂θ=fx⋅(−rsin⁡θ)+fy⋅(rcos⁡θ)(∂z∂r)2=fx2cos⁡2θ+2fxfysin⁡θcos⁡θ+fy2sin⁡2θ1r2(∂z∂θ)2=fx2sin⁡2θ−2fxfysin⁡θcos⁡θ+fy2cos⁡2θsum=fx2+fy2\begin{aligned} \frac{\partial z}{\partial r} &= f_x \cos\theta + f_y \sin\theta \\ \frac{\partial z}{\partial \theta} &= f_x \cdot (-r\sin\theta) + f_y \cdot (r\cos\theta) \\[1ex] \left(\frac{\partial z}{\partial r}\right)^2 &= f_x^2 \cos^2\theta + 2 f_x f_y \sin\theta\cos\theta + f_y^2 \sin^2\theta \\ \frac{1}{r^2}\left(\frac{\partial z}{\partial \theta}\right)^2 &= f_x^2 \sin^2\theta - 2 f_x f_y \sin\theta\cos\theta + f_y^2 \cos^2\theta \\ \text{sum} &= f_x^2 + f_y^2 \end{aligned}

So ∥∇f∥\lVert \nabla f \rVert is the same in both coordinate systems, as it must be.

Exercise 3: Implicit slope

Find dy/dxdy/dx for the curve x2y+sin⁡y=2x−2x^2y + \sin y = 2x - 2 at the point (1,0)(1, 0).

Answer

dy/dx=1dy/dx = 1.

Solution
F(x,y)=x2y+sin⁡y−2x+2F(1,0)=0+0−2+2=0 ✓Fx=2xy−2→−2Fy=x2+cos⁡y→2dy/dx=−Fx/Fy=2/2=1\begin{aligned} F(x, y) &= x^2y + \sin y - 2x + 2 && F(1, 0) = 0 + 0 - 2 + 2 = 0 \ \checkmark \\ F_x &= 2xy - 2 \to -2 \\ F_y &= x^2 + \cos y \to 2 \\ dy/dx &= -F_x / F_y = 2/2 = 1 \end{aligned}

Exercise 4: Backprop by hand (code)

For L=(σ(wx)−y)2L = (\sigma(wx) - y)^2 with σ(z)=1/(1+e−z)\sigma(z) = 1/(1 + e^{-z}), x=2x = 2, y=1y = 1, w=0.5w = 0.5, compute dL/dwdL/dw with the chain rule (use σ′=σ(1−σ)\sigma' = \sigma(1 - \sigma)) and confirm with a central difference.

Answer

dL/dw≈−0.2115dL/dw \approx -0.2115.

Solution
z=wx=1,a=σ(1)≈0.731059dL/da=2(a−y),da/dz=a(1−a),dz/dw=xdL/dw=2(a−1)⋅a(1−a)⋅2\begin{aligned} &z = wx = 1, \quad a = \sigma(1) \approx 0.731059 \\ &dL/da = 2(a - y), \quad da/dz = a(1 - a), \quad dz/dw = x \\ &dL/dw = 2(a - 1) \cdot a(1 - a) \cdot 2 \end{aligned}
python · try it yourself
import math
x, y, w = 2.0, 1.0, 0.5
sig = lambda z: 1 / (1 + math.exp(-z))
a = sig(w * x)
print(round(2 * (a - y) * a * (1 - a) * x, 4))
L = lambda w: (sig(w * x) - y)**2
print(round((L(w + 1e-6) - L(w - 1e-6)) / 2e-6, 4))
-0.2115
-0.2115

Test yourself

z=f(x,y)z = f(x, y), x=g(t)x = g(t), y=h(t)y = h(t). What is dz/dtdz/dt?

  1. fx+fyf_x + f_y
  2. fxg′(t)+fyh′(t)f_x g'(t) + f_y h'(t)
  3. fxfyg′(t)h′(t)f_x f_y g'(t) h'(t)
  4. ∇f⋅⟨g(t),h(t)⟩\nabla f \cdot \langle g(t), h(t) \rangle

F(x,y)=0F(x, y) = 0 defines yy implicitly. dy/dxdy/dx equals…

  1. Fy/FxF_y / F_x
  2. −Fy/Fx-F_y / F_x
  3. −Fx/Fy-F_x / F_y
  4. Fx⋅FyF_x \cdot F_y

Why is reverse-mode autodiff (backpropagation) used to train neural networks?

  1. It avoids the chain rule
  2. It gives the gradient of one scalar loss with respect to all weights at roughly the cost of a forward pass
  3. It is exact while forward mode is approximate
  4. It needs no memory