Linear algebra for LLMsPart 2: Matrices and matrix multiplication
Matrices and shapes
5 min
A matrix is a grid of numbers
has 2 rows and 3 columns: an matrix with and . We write .
Write
Rows go across, columns go down
Row 1 (blue) is . Column 2 (pink) is . They cross at (green), row first, then column.
Write
✏️ Your turn
Read the entries
Write (math, counting from 1) and A[0, 2] (code, counting from 0).
Work it out on paper, then go to the next card to check.
Answer
(row 2, column 1, in blue) and A[0, 2] = 3 (row 0, column 2 in code, in pink). Same grid, two counting conventions.
A stack of rows: one token per row
Read by rows and each row is one token’s vector. Row “cat” is everything the model holds about that token. Most layers act on each row separately.
Write
A stack of columns: one feature per column
Read by columns and each column is one feature across all the tokens: here feature 3 is . Normalization layers and some interpretability tools look along this direction.
Shapes you'll meet in a transformer
| Matrix | Shape | One row is |
|---|---|---|
| , the hidden states | one token | |
| , the embedding table | one vocabulary entry | |
| , a projection (code layout) | one input feature’s weights | |
| , the attention scores | one query against every key |
Write
In PyTorch
A = torch.tensor([[1, 2, 3], [4, 5, 6]])
A.shape # torch.Size([2, 3])
A[0] # first row: tensor([1, 2, 3])
A[:, 1] # second column: tensor([2, 5])
A[1, 0] # one entry: tensor(4): means “every index along this axis”.
📌 Recap
Matrices and shapes in one card
- An matrix has rows and columns; is row , column .
- Math counts from 1 (); code counts from 0 (
A[1, 0]). - Hidden states are : each row is a token, each column a feature.
Write