(a.k.a. “rotary position encodings”, Su et al., 2021)
1. Why do we need positional information in Transformers?
Self-attention is permutation-invariant:
softmax(Q Kᵀ / √d) uses only dot-products between token representations.
Without any extra signal, the model cannot tell “token ₁ came before token ₂”.
Hence every transformer inserts some positional signal before or inside the attention:
• Absolute position encodings (added to token vectors)
• Relative position biases (added to the attention scores)
• Rotary position encodings (RoPE – rotate queries & keys themselves)
RoPE is “relative” in spirit but is injected at the vector level rather than the score level.
⇒ the whole dot-product depends only on the offset (p−q)!
Content interaction is modulated by a deterministic trig function of the relative distance. That’s why RoPE behaves like relative positional encoding.
4. Mathematical summary
Let d be even, D=d/2.
Define diagonal of angular frequencies θ ∈ ℝᴰ:
θᵢ = 1 / 10000^{2i/d}. (Same as sinusoidal)
Define rotation matrix R(p) ∈ ℝ^{d×d} as block-diag of 2×2 rotations:
Q̂ = Q · R(p), K̂ = K · R(p) (for every token position p)
Attention:
A_{p,q} = Q̂ₚ · K̂_qᵀ / √d.
Because R(p)ᵀ R(q) = R(q−p), the position factors disentangle nicely.
No new parameters are introduced; the same θ vector is a constant.
5. How it differs from absolute embeddings
Aspect
Absolute (add)
RoPE (rotate)
Where injected
After embedding, before Q/K/V
On Q and K (not V)
Extra params
0 for sinusoidal, O(n) if learned
0
Dot-product depends on
p and q
(p−q) only
Long-sequence extrapolation
Weak (linear extrapolation)
Strong (phase keeps rotating)
Computation & memory
O(L d) add
O(L d) multiply (same)
Interaction with content
Additive mixture
Content preserved in magnitude, position in phase
6. Implementation snippet (PyTorch-like)
python
def apply_rope(x, sin, cos):
"""
x : (batch, seq, num_heads, head_dim) # head_dim must be even
sin, cos : (seq, head_dim//2)
"""
x1, x2 = x[..., ::2], x[..., 1::2] # even/odd
# broadcasting: (batch, seq, nH, D) vs (seq, D)
x_rot_even = x1 * cos - x2 * sin
x_rot_odd = x1 * sin + x2 * cos
# interleave back
x_out = torch.stack([x_rot_even, x_rot_odd], dim=-1)
return x_out.flatten(-2)
# pre-compute angles (same as sinusoidal but only once)
head_dim = 64
theta = 10000 ** (-torch.arange(0, head_dim, 2) / head_dim)
positions = torch.arange(0, seq_len, dtype=torch.float)
angles = positions[:, None] * theta[None, :] # (seq, D)
sin, cos = angles.sin(), angles.cos()
The same apply_rope is called for queries and keys right after the linear projections.
7. Practical tweaks you’ll see in modern models
• LLama: uses θ base 10000 but rescales for shorter head-dim (θ_max=65535).
• NTK-Aware RoPE (Yi et al., 2023): scale θ by α<1 during finetuning to extend context (used in GPT-bigcode).
• Su-RoPE: learn a single global θ₀ instead of fixed 10000.
• XPos: apply two different scalings to Q and K to improve OOD length stability.
All remain parameter-free or add only a handful of scalars.
8. Why does it work well?
Linear, parameter-free, and cheap.
Encodes relative distances without extra score-bias matrices.
Encodes an unbounded function of distance (phase wraps around), so it can extrapolate to much longer sequences than seen at train time.
Leaves magnitude intact ⇒ content representation is cleanly separated from position (unlike additive mixing).
Plays nicely with multi-head attention: each frequency band lives in its own 2-D subspace.
9. Take-aways
• View RoPE as “multiplying by e^{i θp}” — a rotation per position, per frequency.
• It upgrades sinusoidal absolute embeddings into a relative, extrapolatable form.
• No learnable parameters, no speed penalty, yet tangible accuracy gains (esp. long-range tasks); that’s why it became the default in LLama, GPT-J-6B, PaLM-2, etc.