TExcelTAD
Home › Calculus Essentials › Backpropagation Is the Chain Rule

Backpropagation Is the Chain Rule

Backpropagation is the algorithm that computes the gradient of a neural network's loss with respect to every weight. Behind the name is nothing more than the chain rule from single-variable calculus, applied from the output backwards so that every intermediate result is computed once and reused. This lesson does it by hand with real numbers on a tiny network and checks every gradient with finite differences.

The chain rule as a pipeline

A network is a chain of simple functions. If LL depends on y^\hat{y}, which depends on zz, which depends on ww, the chain rule says

dLdw=dLdy^⋅dy^dz⋅dzdw\frac{dL}{dw} = \frac{dL}{d\hat{y}} \cdot \frac{d\hat{y}}{dz} \cdot \frac{dz}{dw}

Each factor is a local derivative: it only involves one small step of the computation and the numbers that flowed through it in the forward pass. Backpropagation evaluates the product from the left, starting at the loss, and passes the running product (the "upstream gradient") down the chain.

One neuron, by hand

A single neuron with a sigmoid: z=wx+bz = wx + b, y^=σ(z)=1/(1+e−z)\hat{y} = \sigma(z) = 1/(1 + e^{-z}), loss L=(y^−t)2L = (\hat{y} - t)^2. The useful fact σ′(z)=σ(z)(1−σ(z))\sigma'(z) = \sigma(z)(1 - \sigma(z)) follows from the derivative of the exponential.

python · try it yourself
import math

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

# forward pass
z = w * x + b
y = 1 / (1 + math.exp(-z))
L = (y - t) ** 2
print(f"forward:  z = {z:.4f}  y = {y:.4f}  L = {L:.6f}")

# backward pass, one local derivative at a time
dL_dy = 2 * (y - t)
dy_dz = y * (1 - y)
dL_dz = dL_dy * dy_dz
dL_dw = dL_dz * x          # dz/dw = x
dL_db = dL_dz * 1          # dz/db = 1
print(f"backward: dL/dy = {dL_dy:.4f}  dy/dz = {dy_dz:.4f}  dL/dz = {dL_dz:.4f}")
print(f"          dL/dw = {dL_dw:.6f}  dL/db = {dL_db:.6f}")

# check with a central finite difference
def loss(w, b):
    return (1 / (1 + math.exp(-(w * x + b))) - t) ** 2
h = 1e-6
print(f"numeric   dL/dw = {(loss(w + h, b) - loss(w - h, b)) / (2 * h):.6f}")
forward:  z = 0.6000  y = 0.6457  L = 0.125559
backward: dL/dy = -0.7087  dy/dz = 0.2288  dL/dz = -0.1621
          dL/dw = -0.324273  dL/db = -0.162137
numeric   dL/dw = -0.324273

Notice that dL/dzdL/dz was computed once and then used for both dL/dwdL/dw and dL/dbdL/db. In a big network that sharing is the whole point.

A two-layer network

Now two inputs, a hidden layer of two tanh units and one linear output:

z1=W1x+b1(2 numbers)h=tanh⁡(z1)(2 numbers)y^=w2⋅h+b2(1 number)L=12(y^−t)2\begin{aligned} z_1 &= W_1 x + b_1 && \text{(2 numbers)} \\ h &= \tanh(z_1) && \text{(2 numbers)} \\ \hat{y} &= w_2 \cdot h + b_2 && \text{(1 number)} \\ L &= \tfrac{1}{2} (\hat{y} - t)^2 \end{aligned}

The backward pass, layer by layer (⊙\odot is element-wise multiplication, and tanh⁡′(z)=1−tanh⁡2(z)\tanh'(z) = 1 - \tanh^2(z)):

δ=dLdy^=y^−tdLdw2=δ⋅hdLdb2=δdLdh=δ⋅w2dLdz1=dLdh⊙(1−h2)dLdW1=dLdz1⋅xT(outer product)dLdb1=dLdz1\begin{aligned} \delta &= \frac{dL}{d\hat{y}} = \hat{y} - t \\ \frac{dL}{dw_2} &= \delta \cdot h && \frac{dL}{db_2} = \delta \\ \frac{dL}{dh} &= \delta \cdot w_2 \\ \frac{dL}{dz_1} &= \frac{dL}{dh} \odot (1 - h^2) \\ \frac{dL}{dW_1} &= \frac{dL}{dz_1} \cdot x^\mathsf{T} \quad \text{(outer product)} && \frac{dL}{db_1} = \frac{dL}{dz_1} \end{aligned}

Every line uses only the upstream gradient and values saved during the forward pass.

python · try it yourself
import numpy as np

x = np.array([0.5, -1.0]); t = 1.0
W1 = np.array([[0.3, -0.2], [0.4, 0.1]]); b1 = np.array([0.0, 0.1])
w2 = np.array([0.7, -0.5]); b2 = 0.2

z1 = W1 @ x + b1
h = np.tanh(z1)
y = w2 @ h + b2
L = 0.5 * (y - t) ** 2
print("z1 =", np.round(z1, 4), " h =", np.round(h, 4), f" y = {y:.4f}  L = {L:.6f}")

d = y - t
g_w2, g_b2 = d * h, d
g_h = d * w2
g_z1 = g_h * (1 - h**2)
g_W1, g_b1 = np.outer(g_z1, x), g_z1
print(f"delta = {d:.4f}")
print("dL/dw2 =", np.round(g_w2, 5), f" dL/db2 = {g_b2:.5f}")
print("dL/dz1 =", np.round(g_z1, 5))
print("dL/dW1 =\n", np.round(g_W1, 5))
print("dL/db1 =", np.round(g_b1, 5))
z1 = [0.35 0.2 ]  h = [0.3364 0.1974]  y = 0.3368  L = 0.219934
delta = -0.6632
dL/dw2 = [-0.22309 -0.1309 ]  dL/db2 = -0.66322
dL/dz1 = [-0.41173  0.31869]
dL/dW1 =
 [[-0.20586  0.41173]
 [ 0.15935 -0.31869]]
dL/db1 = [-0.41173  0.31869]

Gradient checking

Never trust a hand-written backward pass until it agrees with finite differences. Nudge each parameter by ±h\pm h, recompute the loss, and compare (L(θ+h)−L(θ−h))/2h(L(\theta + h) - L(\theta - h)) / 2h with the analytic gradient. This is the standard debugging tool for new layers.

python · try it yourself
import numpy as np

x = np.array([0.5, -1.0]); t = 1.0
params = {"W1": np.array([[0.3, -0.2], [0.4, 0.1]]), "b1": np.array([0.0, 0.1]),
          "w2": np.array([0.7, -0.5]), "b2": np.array([0.2])}

def loss(p):
    h = np.tanh(p["W1"] @ x + p["b1"])
    return 0.5 * (p["w2"] @ h + p["b2"][0] - t) ** 2

def backprop(p):
    h = np.tanh(p["W1"] @ x + p["b1"])
    d = p["w2"] @ h + p["b2"][0] - t
    gz = d * p["w2"] * (1 - h**2)
    return {"W1": np.outer(gz, x), "b1": gz, "w2": d * h, "b2": np.array([d])}

g, eps, worst = backprop(params), 1e-5, 0.0
for name, arr in params.items():
    for i in np.ndindex(arr.shape):
        old = arr[i]
        arr[i] = old + eps; up = loss(params)
        arr[i] = old - eps; down = loss(params)
        arr[i] = old
        num = (up - down) / (2 * eps)
        worst = max(worst, abs(num - g[name][i]))
        print(f"{name}{list(i)}: backprop {g[name][i]: .6f}   numeric {num: .6f}")
print(f"largest difference: {worst:.1e}")
W1[0, 0]: backprop -0.205864   numeric -0.205864
W1[0, 1]: backprop  0.411727   numeric  0.411727
W1[1, 0]: backprop  0.159347   numeric  0.159347
W1[1, 1]: backprop -0.318694   numeric -0.318694
b1[0]: backprop -0.411727   numeric -0.411727
b1[1]: backprop  0.318694   numeric  0.318694
w2[0]: backprop -0.223093   numeric -0.223093
w2[1]: backprop -0.130904   numeric -0.130904
b2[0]: backprop -0.663225   numeric -0.663225
largest difference: 1.3e-11

All nine gradients agree; the largest difference is about 10−1110^{-11}. A bug in the backward pass, such as forgetting the (1−h2)(1 - h^2) factor, would show up as a difference of order 0.01 or more.

Why backwards?

The loss is one number but the network can have billions of weights. Going backwards from the loss computes all of their gradients for roughly the cost of one extra forward pass, because each layer's upstream gradient is shared by everything below it. Finite differences would need two forward passes per weight. Doing the chain rule from the output end is reverse-mode automatic differentiation.

In software

  • Every deep-learning framework (PyTorch, TensorFlow, JAX) runs exactly this procedure automatically: loss.backward() walks the recorded graph of operations in reverse and multiplies local derivatives.
  • LLM training applies the same rule through attention, layer norm and softmax; each of those layers is just another local derivative (neural networks, training).
  • Vanishing and exploding gradients come from multiplying many local derivatives: tanh⁡′\tanh' and σ′\sigma' are at most 1 and 0.25, so a long chain of them shrinks the gradient towards zero.
  • Custom layers still need gradient checks like the one above.

Next, build the machinery that does this for any expression: automatic differentiation, and then a full tiny engine in the mini project.

Go further: Backpropagation, Layer by Layer organises these local derivatives into reusable layers, checked against PyTorch.

Exercises

Exercise 1: Chain of three

L=(3w−4)2L = (3w - 4)^2, starting at w=2w = 2. Compute dL/dwdL/dw with the chain rule by naming u=3w−4u = 3w - 4.

Answer

dL/dw=12dL/dw = 12.

Solution
u=3⋅2−4=2,L=u2=4dLdu=2u=4,dudw=3dLdw=4⋅3=12\begin{aligned} u &= 3 \cdot 2 - 4 = 2, & L &= u^2 = 4 \\ \frac{dL}{du} &= 2u = 4, & \frac{du}{dw} &= 3 \\ \frac{dL}{dw} &= 4 \cdot 3 = 12 \end{aligned}

Exercise 2: A ReLU neuron

y^=ReLU⁡(wx+b)\hat{y} = \operatorname{ReLU}(wx + b) with ReLU⁡(z)=max⁡(0,z)\operatorname{ReLU}(z) = \max(0, z), loss L=(y^−t)2L = (\hat{y} - t)^2. For x=3x = 3, t=2t = 2, w=1w = 1, b=−0.5b = -0.5, find dL/dwdL/dw and dL/dbdL/db. What are they if b=−4b = -4 instead?

Answer

b=−0.5b = -0.5: dL/dw=3dL/dw = 3, dL/db=1dL/db = 1. b=−4b = -4: both are 0.

Solution
b=−0.5:z=2.5>0,y^=2.5,dL/dy^=2(2.5−2)=1,ReLU⁡′=1dL/dz=1,dL/dw=1⋅x=3,dL/db=1b=−4:z=−1<0,y^=0,ReLU⁡′(z)=0  ⇒  every gradient below it is 0\begin{aligned} b = -0.5{:}\quad & z = 2.5 > 0, \quad \hat{y} = 2.5, \quad dL/d\hat{y} = 2(2.5 - 2) = 1, \quad \operatorname{ReLU}' = 1 \\ & dL/dz = 1, \quad dL/dw = 1 \cdot x = 3, \quad dL/db = 1 \\ b = -4{:}\quad & z = -1 < 0, \quad \hat{y} = 0, \quad \operatorname{ReLU}'(z) = 0 \;\Rightarrow\; \text{every gradient below it is } 0 \end{aligned}

A unit stuck in the negative region gets no gradient at all: a "dead ReLU".

Exercise 3: Check by finite differences

For the one-neuron example in this lesson, compute dL/dbdL/db numerically and compare with the backward pass.

Answer

Both give dL/db≈−0.162137dL/db \approx -0.162137 (they differ by about 10−1210^{-12}).

Solution
python · try it yourself
import math

x, t, w, b = 2.0, 1.0, 0.5, -0.4
loss = lambda w, b: (1 / (1 + math.exp(-(w * x + b))) - t) ** 2
y = 1 / (1 + math.exp(-(w * x + b)))
analytic = 2 * (y - t) * y * (1 - y)
h = 1e-6
numeric = (loss(w, b + h) - loss(w, b - h)) / (2 * h)
print(f"analytic {analytic:.6f}   numeric {numeric:.6f}   diff {abs(analytic - numeric):.1e}")
analytic -0.162137   numeric -0.162137   diff 1.7e-12

Exercise 4: One training step

Using the two-layer gradients printed above, take one gradient-descent step with η=0.5\eta = 0.5 on w2w_2 and b2b_2 only (keep W1W_1, b1b_1 fixed). What are the new values, and what happens to the loss?

Answer

w2≈(0.8115,−0.4345)w_2 \approx (0.8115, -0.4345), b2≈0.5316b_2 \approx 0.5316; the loss drops from 0.219934 to about 0.0395.

Solution
w2←(0.7,−0.5)−0.5⋅(−0.22309,−0.13090)=(0.81155,−0.43455)b2←0.2−0.5⋅(−0.66322)=0.53161\begin{aligned} w_2 &\leftarrow (0.7, -0.5) - 0.5 \cdot (-0.22309, -0.13090) = (0.81155, -0.43455) \\ b_2 &\leftarrow 0.2 - 0.5 \cdot (-0.66322) = 0.53161 \end{aligned}

Both moves raise y^\hat{y} toward the target t=1t = 1, so the loss must fall:

python · try it yourself
import numpy as np

x = np.array([0.5, -1.0]); t = 1.0
W1 = np.array([[0.3, -0.2], [0.4, 0.1]]); b1 = np.array([0.0, 0.1])
w2 = np.array([0.7, -0.5]); b2 = 0.2
h = np.tanh(W1 @ x + b1)
d = w2 @ h + b2 - t
w2_new, b2_new = w2 - 0.5 * d * h, b2 - 0.5 * d
print("new w2 =", np.round(w2_new, 4), f" new b2 = {b2_new:.4f}")
y_new = w2_new @ h + b2_new
print(f"loss before {0.5 * d**2:.6f}  after {0.5 * (y_new - t)**2:.6f}")
new w2 = [ 0.8115 -0.4345]  new b2 = 0.5316
loss before 0.219934  after 0.039529

Test yourself

In backpropagation, what is multiplied together along a path from the loss to a weight?

  1. The weights only
  2. The local derivatives of each step (the chain rule)
  3. The inputs only
  4. The losses of all examples

For z=wx+bz = wx + b, what is ∂z/∂w\partial z/\partial w?

  1. ww
  2. 1
  3. bb
  4. xx

Why is gradient checking with finite differences not used for training itself?

  1. It gives wrong answers
  2. It needs two forward passes per parameter, far too slow for millions of weights
  3. It only works for linear models
  4. It cannot handle tanh