TExcelTAD
Home › Math for Deep Learning & LLMs › Backpropagation Through an MLP

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 X∈RB×dX \in \mathbb{R}^{B \times d} (rows are examples), layer ll computes A(l)=H(l−1)W(l)T+1b(l)TA^{(l)} = H^{(l-1)}W^{(l)T} + \mathbf{1}\mathbf{b}^{(l)T} and H(l)=ϕ(A(l))H^{(l)} = \phi(A^{(l)}). Write G(l)=∂L/∂A(l)G^{(l)} = \partial\mathcal{L}/\partial A^{(l)} (same shape as A(l)A^{(l)}). Then, going backward:

∂L∂W(l)=G(l)TH(l−1)∂L∂b(l)=G(l)T1(sum over the batch)∂L∂H(l−1)=G(l)W(l)G(l−1)=∂L∂H(l−1)⊙ϕ′(A(l−1))\begin{aligned} \frac{\partial\mathcal{L}}{\partial W^{(l)}} &= G^{(l)T}H^{(l-1)} \\ \frac{\partial\mathcal{L}}{\partial\mathbf{b}^{(l)}} &= G^{(l)T}\mathbf{1} \quad \text{(sum over the batch)} \\ \frac{\partial\mathcal{L}}{\partial H^{(l-1)}} &= G^{(l)}W^{(l)} \\ G^{(l-1)} &= \frac{\partial\mathcal{L}}{\partial H^{(l-1)}} \odot \phi'(A^{(l-1)}) \end{aligned}

The output layer starts the recursion. For softmax cross-entropy averaged over the batch, G(L)=1B(P−Y)G^{(L)} = \frac{1}{B}(P - Y), with PP the predicted probabilities and YY 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. G(l)TH(l−1)G^{(l)T}H^{(l-1)} is (n×B)(B×m)=n×m(n \times B)(B \times m) = n \times m, the shape of W(l)W^{(l)}.

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.

python · try it yourself
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 10−910^{-9} or smaller mean the backward pass is right; anything above 10−410^{-4} means a bug (Gradient Checking).

Training on two spirals

python · try it yourself
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 H(l−1)H^{(l-1)} and A(l)A^{(l)} 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.checkpoint trades compute for activation memory.
  • Fused kernels compute P−YP - Y inside the cross-entropy without materializing PP separately.

Go further: Backpropagation, Layer by Layer turns these equations into reusable layer classes with forward and backward, checked against PyTorch autograd.

Exercises

Exercise 1: Shapes

B=32B = 32, layer ll maps 128 to 64 units. Give the shapes of G(l)G^{(l)}, ∂L/∂W(l)\partial\mathcal{L}/\partial W^{(l)} and ∂L/∂H(l−1)\partial\mathcal{L}/\partial H^{(l-1)}.

Answer

(32,64)(32, 64), (64,128)(64, 128), (32,128)(32, 128).

Solution

GG has the shape of A(l)A^{(l)}; the weight gradient GTHG^TH is (64×32)(32×128)(64 \times 32)(32 \times 128); GWGW is (32×64)(64×128)(32 \times 64)(64 \times 128).

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

b\mathbf{b} is broadcast to all BB rows, so by the fan-out rule its gradient is the sum of the per-row gradients: GT1G^T\mathbf{1}.

Exercise 3: A tanh layer (code)

Replace ReLU by tanh in the gradient check and verify the backward pass (use ϕ′(a)=1−tanh⁡2a\phi'(a) = 1 - \tanh^2 a).

Answer

The relative error stays tiny.

Solution
python · try it yourself
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 A=HWTA = HW^T, the gradient with respect to WW is…

  1. GHTGH^T
  2. GTHG^TH
  3. HGHG
  4. WTGW^TG

Why must the forward pass keep its activations during training?

  1. For logging
  2. The backward equations use them to compute the weight gradients
  3. To speed up inference
  4. They are not kept

A gradient check shows relative error 10−210^{-2}. What do you conclude?

  1. Everything is fine
  2. The backward pass very likely has a bug
  3. The learning rate is too high
  4. The data is noisy