Linear algebra for LLMsPart 5: Attention, one operation at a time
Q, K and V
7 min
Three projections of the same X
Every token’s row is projected three times, with three different weights. Each result has one row per token. For the rest of Part 5 we follow one head with , and .
Write
The input
Three tokens, four features each. Small 0/1 entries so every product below is quick to write.
Write
Queries:
Row “the” is : rows 1 and 3 of added, .
Write
Keys:
Row “cat” picks rows 2 and 4 of : .
Write
Values:
Write
What each one is for
| Matrix | Row is token ’s… | Used to |
|---|---|---|
| query: what it is looking for | score against every key | |
| key: what it can be found by | be scored by every query | |
| value: what it passes on | be mixed into the outputs |
Queries and keys only ever meet in dot products, so they must have the same width . Values can have their own width (usually equal).
Write
✏️ Your turn
One row by hand
Write the query for “sat”.
Work it out on paper, then go to the next card to check.
Answer:
Rows 1 and 2 of , added. It matches row 3 of .
In PyTorch
q_proj = nn.Linear(d, d_k, bias=False) # weight (d_k, d): out, in
q = q_proj(x) # x @ q_proj.weight.TIn a transformer
Llama’s attention projections have no bias, so each one is a single matrix multiply. In a real model one q_proj computes every head’s queries at once (Part 2’s block matrices); the next decks use one head to keep the numbers small.
📌 Recap
Q, K and V in one card
- , , , each .
- Queries and keys are compared; values are mixed.
- Our example: , , .
Write