Linear algebra for LLMsPart 2: Matrices and matrix multiplication
What a matmul costs
6 min
One entry: multiplies and adds
One entry of , with and , takes multiplications and additions. The standard count rounds this to floating-point operations (FLOPs): GPUs do a multiply and an add together as one fused multiply-add, which counts as 2 FLOPs.
Write
The whole product:
There are entries and each costs . Memorize this one; every cost estimate for a transformer is built from it.
Write
A transformer-sized product
Projecting 2,048 tokens of width 4,096 through one weight takes 68,719,476,736 FLOPs, about 69 billion. That’s a single weight in a single layer.
✏️ Your turn
One token through one weight
How many FLOPs? And how many parameters does the weight have?
Work it out on paper, then go to the next card to check.
Answer: 2 FLOPs per parameter
33,554,432 FLOPs and 16,777,216 parameters: exactly 2 FLOPs per parameter per token, one multiply and one add for each weight.
In a transformer
Add this up over every weight in the model and you get the rule of thumb forward pass FLOPs per token for parameters (Part 6).
Write
Order matters for cost: vs
and are , is a vector, .
| Order | Work | FLOPs |
|---|---|---|
| a matrix product, then matrix × vector | ||
| two matrix × vector products |
Same answer, about times the work. Associativity lets you choose the cheap order.
Write
Where cheap ordering shows up
In a transformer
LoRA stores a weight update as two thin matrices instead of one matrix: maps features down to , and maps back up to , with small (say 8). Passing a token through , then , costs FLOPs. Multiplying the two matrices together first would build a full matrix: FLOPs to make, then per token. For and that’s about 131 thousand FLOPs per token against 34 million. (At inference you can instead merge the update into the weight once; Part 7.)
📌 Recap
What a matmul costs in one card
- costs FLOPs: a multiply-add is 2 FLOPs.
- One token through a weight: 2 FLOPs per parameter, so a forward pass FLOPs per token.
- , but is far cheaper: choose the order.
Write