06Backprop by hand: a two-layer MLP (NumPy)

mediumnumpy
45:00

06 Backprop by hand: a two-layer MLP (NumPy)

One OpenAI ML engineer candidate reports an ML coding round on a matrix multiplication's forward pass and backprop, written in PyTorch from a code skeleton (1 report), and says NumPy fluency was essential (1 report). This is practice in that shape, not a leaked question.

Set a 45-minute timer. Read one level at a time, and run only that level's tests until they pass: pytest problems/06_backprop -k level1. Earlier levels must keep passing.

params holds W1 (D, H), b1 (H,), W2 (H, K) and b2 (K,) (see init_params). x is (N, D), and y is (N,) integer labels in [0, K). No autograd.

Level 1. forward_backward(params, x, y) returns (loss, grads). The forward pass is h = relu(x @ W1 + b1), then logits = h @ W2 + b2, and the loss is the mean softmax cross-entropy over the batch. This level checks only the loss, so grads can hold zeros, with the same keys and shapes as params.

Level 2. grads holds the real gradient of the loss for each parameter, with the same keys and shapes as params. The tests check every entry against central differences, then train on three blobs of points with plain gradient descent.

Level 3. The loss and every gradient stay finite when the logits are in the tens of thousands. The tests multiply W2 by 10,000.

Level 4. train_step(params, x, y, lr, max_norm=None) takes one step of gradient descent: it updates params in place and returns the loss from before the step. With max_norm set, when the total length of all the gradients together passes it, scale every gradient by the same factor, so their total length becomes max_norm. Clip the gradients, then step by lr times the clipped gradients: max_norm limits the gradient, not the step.

Follow-ups: vanishing and exploding gradients, why the max-subtraction doesn't change the gradient, and what changes for a batch-norm or layer-norm layer.

solution.py
Run the tests to see which pass.