Linear algebra for LLMsPart 5: Attention, one operation at a time
Tokens to vectors
5 min
Token ids
A tokenizer turns text into integer ids, positions in a vocabulary of size . Our toy vocabulary from Part 1 has : the, cat, sat, on, mat.
A token as a one-hot vector
A one-hot vector has a 1 in the token’s position and 0 everywhere else: length . It’s a way to write a token as a vector without giving it any meaning yet.
Write
One-hot times E picks a row
Row view of (Part 2): a mix of ’s rows weighted by . Only one weight is 1, so you get exactly row 1, cat’s embedding. An embedding lookup is a matrix product.
Write
A whole sequence at once
Stack the one-hot rows into a matrix and multiply: . That’s , the input to the first layer.
Code indexes instead
X = E[ids] # what the code does: pick rows
X = F.one_hot(ids, V).float() @ E # the same numbers, the slow wayIn a transformer
The product would cost FLOPs and multiply almost entirely by zeros, so frameworks just index. But thinking of it as a product explains two things: the gradient reaches only the rows that were used, and the output layer can reuse transposed (weight tying, Part 6).
Where does position come in?
Attention compares every token with every other, and nothing in it knows which token came first: shuffle the input rows and the outputs shuffle the same way. Order has to be added.
- GPT-2 adds a learned position vector to each embedding: .
- Llama and most current LLMs add nothing to . They rotate the queries and keys instead (RoPE, Part 6).
Write
✏️ Your turn
Look up “sat”
Write the product.
Work it out on paper, then go to the next card to check.
Answer
Row 2 of : .
📌 Recap
Tokens to vectors in one card
- A token id becomes a one-hot vector of length .
- One-hot × = the token’s row: a lookup is a matrix product.
- A sequence: .
- Position comes from added vectors (GPT-2) or rotations (RoPE).
Write