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 depends on , which depends on , which depends on , the chain rule says
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: , , loss . The useful fact follows from the derivative of the exponential.
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 was computed once and then used for both and . 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:
The backward pass, layer by layer ( is element-wise multiplication, and ):
Every line uses only the upstream gradient and values saved during the forward pass.
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 , recompute the loss, and compare with the analytic gradient. This is the standard debugging tool for new layers.
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 . A bug in the backward pass, such as forgetting the 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: and 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
, starting at . Compute with the chain rule by naming .
Answer
.
Solution
Exercise 2: A ReLU neuron
with , loss . For , , , , find and . What are they if instead?
Answer
: , . : both are 0.
Solution
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 numerically and compare with the backward pass.
Answer
Both give (they differ by about ).
Solution
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 on and only (keep , fixed). What are the new values, and what happens to the loss?
Answer
, ; the loss drops from 0.219934 to about 0.0395.
Solution
Both moves raise toward the target , so the loss must fall:
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?
- The weights only
- The local derivatives of each step (the chain rule)
- The inputs only
- The losses of all examples
For , what is ?
- 1
Why is gradient checking with finite differences not used for training itself?
- It gives wrong answers
- It needs two forward passes per parameter, far too slow for millions of weights
- It only works for linear models
- It cannot handle tanh