Backpropagate through a 2-layer tanh net for regression and binary classification
Why it matters Interviewers still ask for a hand-derived 2-layer backward pass, and it is the base case for debugging custom layers.
Doing backprop by hand for one small network is the fastest way to trust what autograd does for you.
Write two_layer_grads(X, y, W1, b1, W2, b2, task). X is (n, d), y is (n, 1), W1 (d, h), b1 (h,), W2 (h, 1), b2 (1,). Forward: H = tanh(X @ W1 + b1), out = H @ W2 + b2. If task is "regression", loss = mean over samples of 0.5 * (out - y)^2. If task is "binary", p = sigmoid(out) and loss = mean binary cross-entropy of p against y. Return a dict with keys "loss", "dW1", "db1", "dW2", "db2" (gradients of the mean loss, same shapes as the parameters, loss a float).
def two_layer_grads(X, y, W1, b1, W2, b2, task)Example
X = [[1, 2]], y = [[1]], W1 = [[0.5, -0.5], [0.25, 0]], b1 = [0, 0], W2 = [[1], [1]], b2 = [0], task "regression" gives loss 0.2454 (rounded) and db2 = [-0.7005] (rounded).
Understand the idea
Backprop is the chain rule run backwards, one layer at a time. Picture a factory line: when the final product is off, each station gets blamed in proportion to how much it changed the product.
Tiny example with one sample: x = [1, 2], H = tanh([1, -0.5]) = [0.7616, -0.4621], out = 0.2995, y = 1. With loss 0.5 (out - y)^2, dout = out - y = -0.7005, so db2 = -0.7005 and dW2 = H times dout. Then each hidden unit gets dout * W2, multiplied by 1 - H^2.
Rules: dout = (out - y) / n for MSE, or (p - y) / n for sigmoid plus BCE. dW2 = H^T dout, dH = dout W2^T, dZ = dH * (1 - H^2), dW1 = X^T dZ, db = column sums.
The same four lines appear in every dense layer of every network, including the MLP blocks inside transformers.
Shapes and data flow
X (n,d) -> Z1, H (n,h) -> out (n,1); dZ (n,h); dW1 (d,h); dW2 (h,1)