A linear (fully connected) layer is the most common block in an LLM: the Q/K/V projections, the MLP and the final vocabulary head are all linear layers. Here you write its forward pass and derive its backward pass by hand.
For a batch of inputs:
Implement:
linear_forward(x, W, b)returns .linear_backward(x, W, b, grad_out): given the upstream gradient (grad_out, shape ), return the tuple(dx, dW, db)with the gradients of with respect to , and .
Requirements
- Each gradient has the same shape as its parameter. Use this to sanity-check your formulas.
- No loops: three matrix expressions are enough.
Hints
- Work out one element first: . Which entries does touch?
- is broadcast over the batch. In the backward pass, broadcasting becomes a sum.
The tests check your gradients against finite differences, . That is how you debug any hand-written backward pass.