RoPE: position as a rotation
Rotary positional embeddings (RoPE) encode position through rotations. Could they tell attention how far apart two tokens are?
Attention lets a token ask questions of other tokens. But “the rabbit followed the hare” and “the hare followed the rabbit” contain the same tokens.
Their order changes the meaning. Where does that information enter the comparison?
Give the comparison a sense of position
The attention score is a dot product between a query and a key. In the attention experiment, changing the angle between two vectors changed their match.
Could we use that angle to carry position information too?
Take two coordinates from the query and draw them as an arrow. Rotate it according to the query token’s position. Do the same for a pair in the key, using the key token’s position.
Move the tokens, watch the match
Change the query and key positions below. Their arrows rotate, changing the angle between them.
Now move both positions forward together. The arrows turn by the same amount. Their angle difference—and their dot product—stays the same.
The comparison has gained information about how far apart the tokens are, rather than just where either one sits.
A vector has room for several rotations
A query or key contains many coordinates. Split them into pairs and rotate each pair at a different speed.
The learned content still decides the starting vectors. Position adds rotations before the query and key are compared.
Move the token position forward. The pairs turn at different speeds, and their rotated coordinates rejoin in the same order. The vector keeps its width.
This is rotary position embedding, usually shortened to RoPE. It changes queries and keys; the values still carry the information that attention combines.
Where does it sit in a head?
Each head projects the token into a query, key and value. RoPE rotates the query and key by the token’s position, just before they are compared.
Keys are usually rotated before they go into the KV cache. Each cached key keeps the rotation for its own position, so a new token only rotates its own query and key.
Sources
Sources: RoFormer, Llama’s rotary implementation.