Linear algebra for LLMsPart 2: Matrices and matrix multiplication
Matrix × vector
7 min
A matrix times a vector
is and is a column of 3 numbers. The result has one entry per row of : 2 entries.
Write
Row view: entry 1
Entry 1 of is row 1 of dotted with : .
Row view: entry 2
Entry 2 is row 2 dotted with : . One dot product per row.
Write
The shape rule
Each row of must be as long as , so the inner sizes have to match. The outer sizes are what’s left: one output per row of .
Column view: a mix of 's columns
Now read it by columns. ’s entries say how much of each column of to take: 2 of column 1, 1 of column 2, 4 of column 3. . The same answer.
Write
Two views, one product
| View | is | Good for |
|---|---|---|
| Rows | a list of dot products, one per row | computing by hand; “each output scores the input” |
| Columns | a mix of ’s columns, weighted by | seeing what outputs are possible at all |
Every output is some combination of ’s columns. Those combinations are ’s column space (Part 3).
✏️ Your turn
Multiply
Write the product, using the row view. Then check it with the column view.
Work it out on paper, then go to the next card to check.
Answer
Rows: , , . Columns: 1 of the first column plus 2 of the second. A matrix turns 2 numbers into 3.
The code layout: a row vector times a matrix
With the vector on the left as a row, everything flips: is a mix of ’s rows, weighted by ’s entries. . Entry is also dotted with column of .
Write
What a linear layer does to one token
In a transformer
For one token and a weight , the layer outputs . Each output feature is : column of acts as a detector, scoring how much points its way. One head’s slice of is in a Llama 3 8B-sized model.
y = x @ W # x: (d_in,), W: (d_in, d_out) → y: (d_out,)📌 Recap
Matrix × vector in one card
- Shapes: . Inner sizes match.
- Row view: each output is a row of dotted with .
- Column view: mixes ’s columns, weighted by .
- Code layout: mixes ’s rows; output = .
Write