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.
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.
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.
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.
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.