An MLP with Backprop by Hand
🧠 What is backprop? Backpropagation computes the gradient of a network's loss with respect to every weight by applying the chain rule from the loss backward, layer by layer. Each layer receives the gradient with respect to its output, computes the gradients of its own weights, and passes the gradient with respect to its input to the layer before it.
Anthropic asked a machine learning engineer, in a phone screen that went straight into coding, to derive and write a neural network by hand (cost, gradient and backpropagation), which only just fit in the hour; it also asked a research engineer, in a phone-screen ML fundamentals round, to hand-write a small network with a loss and its forward and backward passes (the question).
The Prompt
Writing backprop by hand tests whether you can keep the shapes straight under time pressure and prove the gradients right without autograd.
"In NumPy, write a network with one ReLU hidden layer and a softmax cross-entropy loss. Implement the forward pass, the backward pass by hand, and train it on a small dataset."
Clarifying Questions
You: What are the shapes? I'll take X as (N, D), integer labels y of shape (N,) with C classes, and
a hidden width H.
Interviewer: Yes. Use biases.
You: Is the loss the mean over the batch? That puts a 1 / N in every gradient.
Interviewer: The mean.
You: Plain gradient descent for training, and any initialization I like?
Interviewer: Plain gradient descent is fine. Tell me why you chose your initialization.
You: How do I show the gradients are right? I'd check them against finite differences.
Interviewer: Do that. If you have time, compare with PyTorch too.
What You'll Build
init_params(D, H, C, seed) -> dict:W1(D, H),b1(H,),W2(H, C),b2(C,).forward(params, X) -> (logits, cache)andsoftmax_ce(logits, y) -> (loss, probs).backward(params, cache, probs, y) -> dict: one gradient per parameter, each the shape of its parameter.grad_check(f, param, grad) -> float: the largest relative error against central differences.train(X, y, ...): gradient descent that returns the loss history.