Matrix multiplication's backward, from a skeleton
One OpenAI ML engineer candidate reports an ML coding round that asked for a matrix multiplication's forward pass and backprop in PyTorch, starting from a code skeleton (1 report). Matmuls do most of a transformer's arithmetic, so the question tests whether you can write a backward pass that autograd usually writes for you. Our version hands you this skeleton:
class MatMul(torch.autograd.Function):
@staticmethod
def forward(
ctx: FunctionCtx, a: torch.Tensor, b: torch.Tensor
) -> torch.Tensor:
...
@staticmethod
def backward(
ctx: FunctionCtx, grad_out: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
...
forward returns a @ b. That's one line. backward is the whole job: it gets the gradient of the loss with respect to the output, and it returns one gradient for a and one for b. ctx is the object that carries tensors from one to the other. Its type, FunctionCtx, comes from torch.autograd.function.
The practice comes in four levels. Level 1 is a 2-D a and b, checked by gradcheck. Level 2 gives a a batch axis, with one weight b shared by the whole batch. Level 3 allows any number of leading axes, and a b with a batch of its own. Level 4 puts a Linear layer on top and trains it.
You don't write it yet. The lesson derives the two gradients from one entry, handles a batch that shares the weight, plugs both into autograd, puts a Linear layer on top, and proves it all with gradcheck. At the end you solve the whole problem, level by level, in an interview simulation with a 40-minute timer.
This lesson builds on the backprop lesson, where the same two gradients came out of the shape rule in NumPy. Here you derive them from one entry, and hand them to PyTorch's autograd as a node of your own.