Linear algebra for LLMsPart 2: Matrices and matrix multiplication
Matrix × matrix
8 min
Two matrices
is and is . will have ’s 2 rows and ’s 2 columns. Each of its 4 entries is one dot product.
Write
Entry : row 1 column 1
Row 1 of dotted with column 1 of : .
Entry : row 1 column 2
Same row, next column: .
Row 2: two more dot products
Row 2 with column 1: . Row 2 with column 2: .
Write
The shape rule
The inner sizes must match, because each row of is dotted with each column of . They disappear in the result; the outer sizes stay. Check shapes first: it catches most bugs before any arithmetic.
Write
✏️ Your turn
Shapes, then a product
Write both shapes (or “doesn’t fit”), then compute .
Work it out on paper, then go to the next card to check.
Answer
fails because the inner sizes are 2 and 3. For , row 1: and ; row 2: and .
Order matters:
is , not even the same shape as . Even square matrices usually give different answers in the other order. Matrix multiplication is not commutative.
Write
Regrouping is fine:
You may move the brackets but not the matrices. Multiplication is associative. The result is the same either way, but the cost can be very different, as you’ll see in What a matmul costs.
The transpose of a product flips the order
The shapes force the flip: is and is , so only fits to give a . It’s the same rule as taking off socks and shoes: the last one on comes off first.
Write
In PyTorch and in a transformer
C = A @ B # matrix product; torch.matmul(A, B) is the same
Q = X @ W_q # every token's query at onceIn a transformer
holds tokens as rows (). One product , , computes every token’s query at once: each row of the result is that token’s row of times . Batching rows into one matmul is what makes GPUs fast.
📌 Recap
Matrix × matrix in one card
- .
- : check shapes first.
- , but .
- .
- applies to every token (row) at once.
Write