277. 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 1
Input: A = [[1, 2]], B = [[3], [4]], dC = [[1]]
Output: dA [[3, 4]] and dB [[1], [2]]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
Hint 1
Check shapes: dA must match A and dB must match B.
Hint 2
Let the shapes guide you.
Common mistakes
- Returning dB transposed.
- Multiplying in the wrong order.
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.
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]].
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)
Topics
Companies1
- OpenAI a candidate reported this question OpenAI Research Engineer Interview Guide (Dataford)
From public interview reports and guides. Not affiliated with or endorsed by these companies.