Linear algebra for LLMsPart 2: Matrices and matrix multiplication
Four ways to see AB
8 min
One product, four readings
This is the product from the last deck. The numbers won’t change in this deck; only how you read them. Each reading explains a different part of a transformer.
We’ll write for row of and for column , the same slicing as code: A[i, :] and A[:, j].
Write
1. Every entry is a dot product
: row of dotted with column of . This is the view you compute with.
Write
Dot products of every pair:
With , the columns of are the rows of , so entry of is : every pair of rows, dotted. It’s called a Gram matrix, and it’s symmetric because .
In a transformer
is the same idea with two different matrices: every query dotted with every key.
Write
2. Each column of mixes 's columns
Column of is times column of . Column 1 of is , so column 1 of is . It’s matrix × vector, once per column.
Write
3. Each row of mixes 's rows
Row of is row of times . Row 1 of is , so row 1 of is .
In a transformer
This is the token view. In , each output row depends only on the same row of : a linear layer treats every token independently, with the same weights.
Write
4. A sum of outer products: the first piece
A column times a row is an outer product : every entry of times every entry of . Here column 1 of times row 1 of . Every row of the result is a multiple of .
Write
The second and third pieces
Column 2 of with row 2 of , column 3 of with row 3 of . There’s one piece for each value of the inner index .
Add the pieces
: column of times row of , added up over . The same .
Write
Why the outer-product view matters
Every outer product has rank 1: all its rows are multiples of one vector. So a product with inner size is a sum of rank-1 pieces, and has rank at most .
In a transformer
LoRA (Part 7) adds to a weight, with a small inner size : a sum of rank-1 pieces, cheap to train. And an attention head’s output (Part 5) is one outer product per position: .
✏️ Your turn
Outer product
Write the outer product and its shape.
Work it out on paper, then go to the next card to check.
Answer
. Row 2 is twice row 1: rank 1.
📌 Recap
Four ways to see in one card
| View | Shows up as | |
|---|---|---|
| Dot products | , Gram matrices | |
| Columns | the column space (Part 3) | |
| Rows | : every token on its own | |
| Outer products | rank, LoRA (Part 7) |
Write