Linear algebra for LLMsPart 2: Matrices and matrix multiplication
Special matrices
7 min
The identity matrix
Ones on the diagonal, zeros everywhere else. for any of the right shape: it’s the “1” of matrix multiplication.
Write
A diagonal matrix scales each feature
. Multiplying by it scales feature 1 by 2, feature 2 by 0.5 and feature 3 by . Nothing mixes between features.
…which is just elementwise multiplication
. Code never builds the diagonal matrix; it multiplies entry by entry.
In a transformer
The learnable gain in LayerNorm and RMSNorm is exactly this: one scale per feature (Part 6).
Write
and @ are different products
(the Hadamard product) multiplies matching entries: , , , . @ is the matrix product: rows times columns. In PyTorch, * is and @ is the matrix product.
Write
A * B): entry by entry. (code A @ B): rows times columns.✏️ Your turn
Both products
Write and .
Work it out on paper, then go to the next card to check.
Answer
With square matrices both run without an error, so mixing up * and @ gives wrong numbers silently. A shape check won’t catch it.
Triangular matrices
A lower-triangular matrix has only zeros above the diagonal. Read row as “token may look at tokens 1 to , never later ones”.
In a transformer
This is the shape of the causal mask in a decoder: token attends only to itself and earlier tokens. Part 5 builds it with instead of 0.
torch.tril(torch.ones(4, 4)) # the matrix aboveWrite
Block matrices multiply block by block
Split a matrix into blocks and multiply the blocks as if they were numbers. Splitting ’s columns into two blocks splits the output’s columns the same way.
In a transformer
Multi-head attention uses this. () is column blocks of width , one per head, so one big computes every head’s queries at once. Part 4 shows how to cut the result back into heads.
Write
📌 Recap
Special matrices in one card
- .
- scales each feature: .
- (
*) is entry by entry;@is the matrix product. Square shapes hide the mix-up. - Lower-triangular = the causal mask’s shape.
- Blocks multiply like numbers: .
Write