Write the backward pass of a matrix multiply
Why it matters Linear layers are most of an LLM's FLOPs, and their backward pass is exactly these two matmuls.
Every autograd engine needs the vector-Jacobian product of C = A @ B.
Write matmul_vjp(A, B, dC). Return (dA, dB) where dA = dC @ B^T and dB = A^T @ dC.
def matmul_vjp(A, B, dC)Example
A = [[1, 2]], B = [[3], [4]], dC = [[1]] gives dA [[3, 4]] and dB [[1], [2]].
Understand the idea
Autograd engines never build full Jacobians. For C = A @ B they only need to turn the upstream gradient dC into dA and dB, which is called a vector-Jacobian product. The shapes almost tell you the answer: dA must have A's shape and dB B's shape. Worked example: A = [[1, 0], [2, 1]] (2 by 2), B = [[1], [3]] (2 by 1), dC = [[1], [2]] (2 by 1). dA = dC @ B^T = [[1], [2]] @ [[1, 3]] = [[1, 3], [2, 6]]. dB = A^T @ dC = [[1, 2], [0, 1]] @ [[1], [2]] = [[1 + 4], [0 + 2]] = [[5], [2]]. Rule: for A of shape (n, k), B of shape (k, m) and dC of shape (n, m), dA = dC @ B^T gives (n, k) and dB = A^T @ dC gives (k, m). Check the shapes match A and B exactly; returning dB transposed is a common slip. Used in: the backward pass of every linear layer and attention projection in PyTorch, JAX and similar libraries.
Shapes and data flow
A (n, k) @ B (k, m) -> C (n, m) dA = dC (n, m) @ B^T (m, k) dB = A^T (k, n) @ dC (n, m)