Roadmap / Backpropagation by Hand

✓

Linear Layer Forward & Backward

mediumbackpropgradientsgradient-check

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 NN inputs:

Y=XW+b,X∈RN×Din,  W∈RDin×Dout,  b∈RDoutY = XW + b, \qquad X \in \mathbb{R}^{N \times D_{in}},\; W \in \mathbb{R}^{D_{in} \times D_{out}},\; b \in \mathbb{R}^{D_{out}}

Implement:

  • linear_forward(x, W, b) returns YY.
  • linear_backward(x, W, b, grad_out): given the upstream gradient ∂L∂Y\frac{\partial L}{\partial Y} (grad_out, shape N×DoutN \times D_{out}), return the tuple (dx, dW, db) with the gradients of LL with respect to XX, WW and bb.

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: Ynk=∑dXndWdk+bkY_{nk} = \sum_d X_{nd} W_{dk} + b_k. Which YY entries does WdkW_{dk} touch?
  • bb is broadcast over the batch. In the backward pass, broadcasting becomes a sum.

The tests check your gradients against finite differences, L(θ+ϵ)−L(θ−ϵ)2ϵ\frac{L(\theta + \epsilon) - L(\theta - \epsilon)}{2\epsilon}. That is how you debug any hand-written backward pass.

solution.py
Python idle

Press Run (⌘/Ctrl + Enter) to test your code.