14Matrix multiplication forward and backward (custom autograd)

mediumtorch
40:00

14 Matrix multiplication forward and backward (custom autograd)

Reported in an April 2026 OpenAI ML engineer screen: implement matrix multiplication's forward and backprop in PyTorch from a skeleton (1 report). This is practice in that shape, not a leaked question.

Set a 40-minute timer. Read one level at a time, and run only that level's tests until they pass: pytest problems/14_matmul_backprop -k level1. Earlier levels must keep passing. Don't call autograd inside backward.

Level 1. Fill in MatMul, a torch.autograd.Function, in solution.py. forward(ctx, a, b) returns a @ b for a 2-D a of shape (n, k) and b of shape (k, m). backward(ctx, grad_out) returns (grad_a, grad_b), shaped like a and b. The tests check the forward and run torch.autograd.gradcheck in float64.

Level 2. a can carry a batch axis, (B, n, k), and every batch element shares the one (k, m) weight b. PyTorch's engine quietly sums a gradient back to the input's shape if you return the batched one, so no test at this level can catch a missing sum, but NumPy won't do it for you and an interviewer may ask.

Level 3. a can have any number of leading axes, (..., n, k), and b can carry the same batch axes, (..., k, m): one weight per batch element. b can also carry only the last of a's batch axes, as with a of shape (2, 3, n, k) and b of shape (3, k, m). grad_b sums only the leading axes that b doesn't have, which are always the first ones. Two tests call backward directly, with no engine to fix the shape.

Level 4. Linear(in_features, out_features), an nn.Module whose forward is MatMul.apply(x, W) + bias, with W of shape (in_features, out_features). Both are nn.Parameters. One test checks that the output's graph runs through your MatMul, so x @ W doesn't count. Another trains it with plain SGD to recover a known linear map.

Follow-ups: what to save in ctx and the memory cost of saving activations, the FLOPs of the forward and backward (about 2x the forward), activation checkpointing, and what changes in mixed precision.

solution.py
Run the tests to see which pass.