Linear algebra for LLMsPart 6: The rest of the transformer
RoPE
7 min
Rotate queries and keys by position
Take the 2D rotation from Part 3. The query of the token at position is turned by ; the key at position by . Values aren’t rotated. Nothing is added to the embeddings.
Write
The score sees only the distance
The identity from Part 3: the two rotations combine into one by the difference of the angles. The same pair of tokens gets the same score at positions 3 and 7 as at 103 and 107. Attention learns relative position for free.
Write
Picture it in 2D
With : the query at position 1 is turned 0.4 rad, the key at position 3 is turned 1.2 rad. Move both tokens along by any number of positions and both arrows turn by the same extra angle, so the angle between them, and their dot product, stays the same.
Many pairs, many frequencies
A head of width is cut into pairs, and each pair gets its own speed. Pair 0 turns 1 radian per position; the last pairs turn very slowly. Like the hands of a clock, fast pairs tell nearby positions apart and slow ones cover long distances. The original paper used ; Llama 3 uses for longer contexts.
Write
A tiny head
✏️ Your turn
Your angle
What is , and how far does pair 1 turn at position ?
Work it out on paper, then go to the next card to check.
Answer
How code does it
def rotate_half(x):
x1, x2 = x.chunk(2, dim=-1) # the two halves
return torch.cat((-x2, x1), dim=-1)
# cos, sin: (T, d_h), one angle per position and pair
q = q * cos + rotate_half(q) * sin
k = k * cos + rotate_half(k) * sinIn a transformer
No rotation matrix is ever built: each pair’s 2×2 rotation is written out as . Hugging Face’s Llama code pairs dimension with instead of neighbours, which is the same idea with the dimensions listed in a different order.
📌 Recap
RoPE in one card
- Rotate each pair of query and key dimensions by , the position times the pair’s speed.
- depends only on .
- ; originally, 500,000 in Llama 3.
- Code applies it as .
Write