Rotary Position Embedding (RoPE), introduced by Su et al. (2021), is the de-facto position-encoding standard for modern decoder-only LLMs. Llama 1/2/3/4, Mistral, Mixtral, Qwen, Phi, and Falcon all use RoPE or a close variant. It is worth understanding properly because nearly every long-context paper builds on top of it.
The core idea
Instead of adding a position vector to the input embedding, RoPE rotates the Q and K vectors at every position by a position-dependent angle. The rotation is applied inside attention, after the Q and K projections. The key property: the dot product between rotated Q at position m and rotated K at position n depends only on the relative distance m − n, not on the absolute positions.
(rotated_Q · rotated_K) at positions (m, n) ≡ f(content, m − n)
Why RoPE replaced its competitors
- Relative position falls out for free, without dedicated relative-position parameters.
- Zero learned parameters for position — it's a deterministic geometric transform.
- Extrapolation works much better than learned PE. With YaRN-style scaling tricks (next lesson but one), models trained on 8K can be extended to 128K with modest fine-tuning.
- Easy to implement. Element-wise complex-number multiplication; no extra layer.
Llama 4 uses iRoPE — interleaved RoPE — alternating layers with and without RoPE for even better long-context behavior. The base architecture remains the same; only the position-injection knob is being tuned.