CodeRigor

LESSON

Backpropagation through an MLP

Cache the forward pass, push the loss derivative back through softmax cross-entropy, linear layers and activations, and prove every gradient two independent ways.

Gradient descent needs the derivative of the loss with respect to every weight in the network. Backpropagation delivers all of them in one backward sweep that costs about as much as the forward pass. This lesson pairs with Lecture 5 of CMU's 11-785 (Fall 2026), linked under Watch & read. The lecture derives the recursion; here you implement it in NumPy and check it two independent ways.

Fix the notation first. Layer k has a weight matrix Wₖ of shape (out, in) and a bias bₖ, the layout torch.nn.Linear uses. For a batch of N rows the layer computes zₖ = aₖ₋₁ Wₖᵀ + bₖ and aₖ = f(zₖ), starting from a₀ = x. The last layer skips the activation, so its z values are the logits. Store the input of every layer as you go, because the backward pass reads each one again.

Forward: compute, and keep what each layer was given
start / 4
A two-layer network. The values in the accented boxes are stored; the backward pass needs a₀ for dW₁ and a₁ for both dW₂ and the tanh slope.
Forward: compute, and keep what each layer was given
A two-layer network. The values in the accented boxes are stored; the backward pass needs a₀ for dW₁ and a₁ for both dW₂ and the tanh slope.

Start the backward pass at the loss. For softmax followed by mean cross-entropy over N examples, the derivative with respect to the logits is (p - y) / N, where p holds the predicted probabilities and y is one-hot. The division by N belongs to the loss, which is a mean. Leave it out and every gradient is N times too large, which behaves exactly like a learning rate that is N times too high.

Call the derivative of the loss with respect to a layer's z values delta. Every layer then needs the same three lines:

  • dWₖ = deltaₖᵀ aₖ₋₁, which sums (output error × input) over the batch
  • dbₖ = the column sums of deltaₖ
  • deltaₖ₋₁ = (deltaₖ Wₖ) ⊙ f′(zₖ₋₁)

The first two are the gradients you return. The third carries the error down one layer: multiplying by Wₖ gives the derivative with respect to the layer's input, and multiplying elementwise by the activation's slope steps back across the nonlinearity. A gradient always has the shape of the thing it differentiates, so dWₖ has the shape of Wₖ. Checking shapes catches most transposition mistakes before a single number is wrong.

Python
import numpy as np

delta = np.array([[0.2, -0.2], [-0.1, 0.1]])          # N = 2 examples, 2 outputs
a_in = np.array([[1.0, 0.0, 2.0], [0.0, 1.0, 1.0]])   # the layer's 3 inputs
print((delta.T @ a_in).round(6).tolist())             # dW, shape (2, 3)
print(delta.sum(axis=0).round(6).tolist())            # db, shape (2,)

Both activation slopes can be written with the stored output, so z itself does not have to be kept. For tanh the slope is 1 - a². For ReLU it is 1 where a > 0 and 0 everywhere else, including at the kink, which is the convention PyTorch uses. Writing a >= 0 instead is a classic mistake: every ReLU output is at least zero, so the test is always true and units that were switched off pass gradient anyway.

Backward: one delta per layer
start / 5
The same two-layer network, read right to left. Each delta produces that layer's two gradients, then moves down through W and the activation slope.
Backward: one delta per layer
The same two-layer network, read right to left. Each delta produces that layer's two gradients, then moves down through W and the activation slope.

How do you know the derivatives are right? Compare them with a slope you measure. Nudge one parameter by ±ε, rerun the forward pass, and take (L(w + ε) - L(w - ε)) / 2ε. Its error shrinks with ε², while the one-sided version (L(w + ε) - L(w)) / ε only improves with ε. Run the check in float64: in float32, rounding in the loss swamps the difference long before ε is small enough.

Python
def loss(w):
    return w ** 3          # the true slope at w = 2 is 12

w, eps = 2.0, 1e-3
central = (loss(w + eps) - loss(w - eps)) / (2 * eps)
one_sided = (loss(w + eps) - loss(w)) / eps
print(round(central, 6), round(one_sided, 6))

A finite difference costs two forward passes per parameter, so it is a test and never a training method. A network with a million weights would need two million forward passes for one gradient, where backpropagation needs one forward pass and one backward pass. That gap is the reason the algorithm matters.

The hidden tests add a second, independent check: PyTorch's autograd differentiates the same function with a different implementation. When your hand-written gradients, the measured slopes and autograd all agree, a shared mistake is unlikely. Know the limit of that evidence, though. Every one of these checks confirms that your gradient matches the function you wrote. None of them can tell you that the function is the model you meant to build.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

The lecture this lesson is built around: the forward pass, the backward pass and the calculus of backpropagation for vector activations. Watch it first, then implement the same recursion here and check it against finite differences and autograd.