Backpropagation Through an MLP
This lesson derives the backward pass of a multilayer perceptron in matrix form, the four equations every deep-learning library implements for its dense layers, and then trains a two-layer network on a real nonlinear problem with nothing but NumPy. The single-node rules are in Computational Graphs.
The four backprop equations
For a batch (rows are examples), layer computes and . Write (same shape as ). Then, going backward:
The output layer starts the recursion. For softmax cross-entropy averaged over the batch, , with the predicted probabilities and the one-hot labels (Softmax and Cross-Entropy Gradient).
A quick sanity check for every equation: the gradient of a quantity has the quantity's shape. is , the shape of .
Gradient check first
Hand-written backward code is easy to get subtly wrong. Always compare it with finite differences on a tiny network before training.
import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(size=(5, 3)); y = np.array([0, 2, 1, 2, 0])
W1, b1 = rng.normal(size=(4, 3)), rng.normal(size=4)
W2, b2 = rng.normal(size=(3, 4)), rng.normal(size=3)
def loss_and_grads(W1, b1, W2, b2):
A1 = X @ W1.T + b1; H1 = np.maximum(0, A1)
Z = H1 @ W2.T + b2
Z = Z - Z.max(1, keepdims=True); P = np.exp(Z) / np.exp(Z).sum(1, keepdims=True)
loss = -np.mean(np.log(P[np.arange(5), y]))
G2 = (P - np.eye(3)[y]) / 5
gW2, gb2 = G2.T @ H1, G2.sum(0)
G1 = (G2 @ W2) * (A1 > 0)
gW1, gb1 = G1.T @ X, G1.sum(0)
return loss, (gW1, gb1, gW2, gb2)
loss, grads = loss_and_grads(W1, b1, W2, b2)
params = [W1, b1, W2, b2]
for name, p, g in zip(["W1", "b1", "W2", "b2"], params, grads):
num = np.zeros_like(p)
for idx in np.ndindex(p.shape):
old = p[idx]
p[idx] = old + 1e-5; lp = loss_and_grads(*params)[0]
p[idx] = old - 1e-5; lm = loss_and_grads(*params)[0]
p[idx] = old; num[idx] = (lp - lm) / 2e-5
rel = np.linalg.norm(g - num) / np.linalg.norm(g + num)
print(f"{name}: relative error {rel:.1e}")W1: relative error 1.9e-11
b1: relative error 6.3e-11
W2: relative error 2.6e-11
b2: relative error 1.8e-10
Relative errors around or smaller mean the backward pass is right; anything above means a bug (Gradient Checking).
Training on two spirals
import numpy as np
rng = np.random.default_rng(1)
n = 100
t = np.linspace(0.25, 3 * np.pi, n)
X = np.vstack([np.c_[t * np.cos(t), t * np.sin(t)], np.c_[-t * np.cos(t), -t * np.sin(t)]]) / 5
X += rng.normal(0, 0.05, X.shape); y = np.repeat([0, 1], n)
W1 = rng.normal(0, np.sqrt(2 / 2), (64, 2)); b1 = np.zeros(64)
W2 = rng.normal(0, np.sqrt(2 / 64), (2, 64)); b2 = np.zeros(2)
lr = 0.5
for step in range(4001):
A1 = X @ W1.T + b1; H1 = np.maximum(0, A1); Z = H1 @ W2.T + b2
Z -= Z.max(1, keepdims=True); P = np.exp(Z); P /= P.sum(1, keepdims=True)
loss = -np.mean(np.log(P[np.arange(2 * n), y]))
G2 = (P - np.eye(2)[y]) / (2 * n)
G1 = (G2 @ W2) * (A1 > 0)
W2 -= lr * G2.T @ H1; b2 -= lr * G2.sum(0); W1 -= lr * G1.T @ X; b1 -= lr * G1.sum(0)
if step % 1000 == 0:
print(f"step {step}: loss {loss:.4f}, accuracy {np.mean(P.argmax(1) == y):.3f}")step 0: loss 0.7870, accuracy 0.640
step 1000: loss 0.1182, accuracy 0.985
step 2000: loss 0.0446, accuracy 0.990
step 3000: loss 0.0330, accuracy 0.990
step 4000: loss 0.0278, accuracy 0.990
A linear classifier cannot beat about 50% on interleaved spirals; the hidden layer bends the decision boundary around them.
Memory: why activations are stored
The backward equations need and from the forward pass, so training keeps every layer's activations in memory until the backward pass reaches it. Activation memory grows with batch size and depth and often dominates training memory; activation checkpointing stores only some layers and recomputes the rest during the backward pass.
In software
nn.Linear's backward implements exactly the first three equations; the activation module's backward implements the fourth.torch.utils.checkpointtrades compute for activation memory.- Fused kernels compute inside the cross-entropy without materializing separately.
Go further: Backpropagation, Layer by Layer turns these equations into reusable layer classes with
forwardandbackward, checked against PyTorch autograd.
Exercises
Exercise 1: Shapes
, layer maps 128 to 64 units. Give the shapes of , and .
Answer
, , .
Solution
has the shape of ; the weight gradient is ; is .
Exercise 2: Bias gradient
Why is the bias gradient a sum over the batch?
Answer
The same bias is added to every example (fan-out).
Solution
is broadcast to all rows, so by the fan-out rule its gradient is the sum of the per-row gradients: .
Exercise 3: A tanh layer (code)
Replace ReLU by tanh in the gradient check and verify the backward pass (use ).
Answer
The relative error stays tiny.
Solution
import numpy as np
rng = np.random.default_rng(4)
X, W = rng.normal(size=(6, 3)), rng.normal(size=(2, 3))
L = lambda W: np.sum(np.tanh(X @ W.T) ** 2)
A = X @ W.T; H = np.tanh(A)
G = 2 * H * (1 - H**2)
g = G.T @ X
num = np.array([[(L(W + e) - L(W - e)) / 2e-6 for e in E] for E in np.eye(6).reshape(2, 3, 2, 3) * 1e-6])
print(f"{np.linalg.norm(g - num) / np.linalg.norm(g + num):.1e}")6.2e-11
Test yourself
For , the gradient with respect to is…
Why must the forward pass keep its activations during training?
- For logging
- The backward equations use them to compute the weight gradients
- To speed up inference
- They are not kept
A gradient check shows relative error . What do you conclude?
- Everything is fine
- The backward pass very likely has a bug
- The learning rate is too high
- The data is noisy