BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Autograd3 of 11 in topic

277. Write the backward pass of a matrix multiply

EasyAutograd
Asked atOpenAI

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.

Functiondef 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.

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]].

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
Autograd
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.

Similar questions
  • Order a compute graph for backprop with a topological sortEasy
  • Run reverse mode over an op tape where values are reusedEasy
  • Run forward-mode autodiff over a tiny instruction listEasy
  • Build a tiny reverse-mode autograd engineMedium
All Autograd problems
Report
277 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
import numpy as np
​
def matmul_vjp(A, B, dC):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 3 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS