TL;DR
Rotary position embedding, usually called RoPE, encodes position by rotating the query and key vectors inside attention. The rotation angle grows with each token's position. The dot product between a rotated query and a rotated key then depends only on how far apart the two tokens are, not on where they sit in the sequence. Nothing is added to the input, and no new parameters are learned.
Where you'll see it: the attention layers of the LLaMA family and many other open language models, and in the long-context extensions built on top of them.
Intuition
A merry-go-round
Put two riders on a merry-go-round. Each rider points in some direction. Now spin the whole ride by an unknown amount. Both riders turn by the same angle, so the angle between them is unchanged. What you can measure is how far apart they are around the ring, and that does not depend on where the ride happens to have stopped.
RoPE works the same way. Each query and each key is a vector, and the token at position spins its vector by an angle proportional to . When a query at position is compared with a key at position , the comparison sees the difference of the two angles, which is . The absolute positions cancel out, and only the gap survives.
Why not add a position vector
The previous lesson, positional encoding, adds a position-dependent vector to each token embedding. That works, but the position signal then gets mixed into the content vector before attention ever sees it. A query and a key each carry their own absolute position fingerprint, and the attention score has to untangle content from position on its own. Relative distance is only learned indirectly, through the query and key projections.
RoPE asks for something more direct. It wants the score between positions and to be a function of alone. Rotation gives exactly that, because of a property of rotation matrices that you can check with the material on rotation matrices.
flowchart LR A["Token embedding"] --> B["Project to query and key"] B --> C["Rotate by angle set by position"] C --> D["Dot product depends on offset"] D --> E["Softmax over attention scores"]
The math
Setting up the rotation
Take a query or key vector with even. Group its entries into pairs, for . Each pair is a point in a plane, so it can be rotated with the 2D rotation matrix.
Pair gets its own frequency,
so the first pair spins fastest and the last pair spins slowest. At position , pair is rotated by the angle .
For a position , define the block-diagonal matrix whose -th block is
The rotary embedding of a query at position is , and the rotary embedding of a key at position is . Both are computed from the usual projections and .
Here and are the query and key vectors of one attention head, and are token positions, and is the frequency of pair . The frequencies match the sinusoidal schedule from positional encoding, which is why the two ideas look alike.
The score depends only on the offset
The attention score between positions and is the dot product of the rotated vectors. Write it with transposes and use two facts about rotations from the rotation-matrix lesson: the transpose of a rotation is the rotation by the negative angle, , and rotations compose by adding angles, . Then
The absolute positions have disappeared. Only remains. The same holds block by block, because is block-diagonal.
For one pair with , and offset , the contribution to the score is
The total score is the sum of over all pairs. Each pair contributes a cosine and a sine of its own offset, so the score is a sum of waves in the gap .
Efficient form
Multiplying by a full matrix is wasteful, because the matrix is sparse. In practice each vector is rotated with two elementwise products,
where is elementwise multiplication and swaps the two members of each pair with one negated. Many codebases pair the first half of the vector with the second half instead of adjacent entries. That is a fixed permutation of the dimensions, so it gives an equivalent model, provided queries and keys use the same pairing.
Only queries and keys are rotated. Values are left alone. Rotation preserves length, so it changes which keys match a query, not how large the vectors are.
Frequencies and wavelengths
A pair with frequency completes a full turn every positions. The fastest pair, , turns once about every 6.3 tokens. The slowest pair turns once every tens of thousands of tokens. Between them, the pairs cover a wide range of scales, so the model can tell apart both neighbouring tokens and tokens thousands of positions away.
Worked examples
Use , so there are two pairs with frequencies and . Let the query and key both be . The query sits at position and the key at position .
- Rotate the query by .
- Pair 0 is rotated by radian: .
- Pair 1 is rotated by radian: .
- So .
- Rotate the key by .
- Pair 0 is rotated by radians: .
- Pair 1 is rotated by radian: .
- So .
- Take the dot product. .
- Check with the offset formula. The gap is , so the score should be . The two results agree.
- Interpretation: the score came out the same as it would for any pair of positions with gap 2. Taking and instead gives the identical score, even though the absolute positions are different.
A head of dimension has pairs. Here are four of them, with .
| Pair | Frequency | Wavelength (tokens) | Rotation after 4096 tokens |
|---|---|---|---|
| 0 | 1.0 | 6.3 | about 4096 radians, many full turns |
| 1 | 0.866 | 7.3 | about 3547 radians |
| 32 | 0.01 | 628 | 40.96 radians, about 6.5 turns |
| 63 | 0.000115 | about 54,400 | 0.47 radian, a slow drift |
- The fast pairs cycle many times within a few tokens. They tell apart nearby words, such as a word and the one just before it.
- The middle pairs complete a turn every few hundred tokens. They carry medium-range structure, such as the start of a sentence or a paragraph.
- The slowest pair barely moves over 4096 tokens. Its cosine is close to 1 across the whole context, so it contributes a nearly constant term to the score and acts as a coarse, long-range signal.
- Interpretation: each pair gives the score a different view of the gap, and together they describe the offset at many scales.
Tradeoffs and failure modes
| Situation | Problem | Better choice |
|---|---|---|
| Attention should depend on relative distance | Additive absolute encodings mix position into content | RoPE, which makes the score a function of the offset |
| Autoregressive generation with a key cache | Rotations applied to keys must stay valid as the cache grows | Store rotated keys once. Each key depends only on its own position, so the cache stays correct |
| Inference beyond the training length | Angles for positions past the training range were never seen | Position interpolation, which scales positions down into the trained range, followed by a short fine-tune |
| Very short fixed-length inputs with plenty of data | RoPE adds machinery a learned table would avoid | Learned position embeddings |
| Simple baseline, or a task that needs a position bias | A rotation may not be the right inductive bias | Additive sinusoidal encodings or an explicit distance bias |
Failure modes to watch for. The most common bug is a mismatch between the pairing used for queries and keys, or between the position indices used at training and inference. Either one silently scrambles the scores without raising an error. A second one is an off-by-one in the position counter during generation. A model can still produce fluent text while its distance sense is shifted by one token. Finally, long-context behaviour depends on the frequencies. Lowering the frequencies or rescaling positions changes what the slow pairs can represent, so these changes need a check on a long-context benchmark, not just short prompts.
History
Position signals in transformers started with the sinusoidal encoding in the 2017 transformer paper, by Vaswani and colleagues, which added a fixed vector to each input embedding. Learned position tables followed in models such as BERT, and both approaches gave positions in absolute terms.
In 2021 Jianlin Su and colleagues posted the RoFormer paper on arXiv. It introduced rotary position embedding and argued that a rotation of queries and keys gives a relative-position signal with no extra parameters and a clean dependence on the offset. Open language models adopted it over the following years, including the GPT-NeoX family and the LLaMA family, which made RoPE the default in much of the open model ecosystem. Its later use in context-extension methods is the main reason it is studied closely today.
Check yourself
QuestionRecall: which vectors does rotary position embedding rotate, and which does it leave unchanged?Show answer
RoPE rotates the query and key vectors inside each attention head, using an angle proportional to the token's position. It leaves the value vectors unchanged. The values carry the content that gets mixed together, and the rotation only affects how well each query matches each key.
QuestionComputation: a pair with frequency has query at position 2 and key at position 6. What is their attention contribution from this pair?Show answer
The offset is , so the angle is radians. With , the formula reduces to . The contribution is negative, meaning this pair of tokens looks dissimilar through this pair of dimensions.
QuestionWhy: explain why the attention score between a query at position and a key at position depends only on .Show answer
The score is . Rewriting the transpose gives . A rotation's transpose is the rotation by the negative angle, and rotations compose by adding angles, so . The absolute positions and never appear separately, only their difference.
QuestionApplied: a model was trained with a 2048-token context and is run on 8192-token inputs. Explain why plain RoPE can degrade, and name one fix.Show answer
Positions beyond 2048 produce rotation angles the model never saw during training. The fast and middle pairs in particular spin through angles outside the trained range, so their contributions to the score are unfamiliar. One fix is position interpolation: scale the positions down by the ratio of the two lengths, so the new positions fall inside the trained range, and then fine-tune briefly. Changing the frequencies is a related option, and either one should be checked on long-context tasks.