Positional Encodings: Sinusoidal, ALiBi & Rotary Embeddings (RoPE)
Why Self-Attention is blind to word order without positional signals, how sinusoidal clocks work, and how RoPE rotates Q & K in 2D pairs so attention depends purely on relative distance (m − n) — enabling 128K+ context via YaRN!
Rotary Positional Embeddings (RoPE) encode token positions by rotating Query and Key vectors in 2D subspaces so their dot product depends cleanly on relative distance (m − n).
Self-Attention alone is order-blind ('dog bites man' looks identical to 'man bites dog'); RoPE injects relative position cleanly and extrapolates to long contexts.
RoPE (Rotary Positional Embeddings) is the universal positional engine behind LLaMA, Gemma, Mistral, Qwen, and DeepSeek — and the secret behind 128K–1M long-context extension!
Knowing WHERE RoPE is applied (strictly to Q and K, NEVER to V, and BEFORE saving K to the KV-Cache!) is a classic implementation detail that makes or breaks custom Transformer code.
Understanding RoPE's multi-frequency base θ_base (10,000 → 500,000 in LLaMA 3) explains how labs stretch a 4K model to 128K context with minimal fine-tuning!
Top modern LLM interview question: 'Why does Self-Attention need positional encodings, how does RoPE inject relative position into Q·K without adding parameters, and why isn't RoPE applied to V?'
In a Transformer using Rotary Positional Embeddings (RoPE), which tensors get rotated by the position-dependent rotation matrix R_m?
- Prove why pure Self-Attention is permutation-equivariant and cannot distinguish 'Dog bites man' from 'Man bites dog'
- Explain absolute Sinusoidal & learned positional embeddings and why they fail to extrapolate beyond training length
- Derive RoPE's 2D rotation identity ⟨R_m q, R_n k⟩ = qᵀ R_{n−m} k showing pure relative-position dependence
- Explain how RoPE base scaling (NTK / YaRN) extends 4K-trained LLMs to 128K+ context windows
Imagine two friends standing on a giant spinning Ferris wheel (RoPE). Token n gets on at 12:00 and rotates to angle n·θ. Four steps later, Token m gets on and rotates to m·θ. Even as the entire wheel spins around 100 times, the angle between the two friends is ALWAYS (m − n)·θ! RoPE gives every 2D slice of Q and K its own Ferris wheel spinning at a different speed — fast wheels measure nearby words, slow wheels measure distant chapters!
1. Permutation Invariance & Absolute Sinusoidal Clocks
Because Self-Attention computes pairwise dot products between all tokens simultaneously, shuffling the input words simply shuffles the exact same outputs — without positional signals, 'Dog bites man' and 'Man bites dog' look identical!
Absolute Positional Encodings (2017–2020)
- Sinusoidal (Original Transformer): Adds fixed sine/cosine waves directly to token embeddings .
- Learned Absolute (GPT-2 / BERT): Learns a lookup table
nn.Embedding(max_len, D)— hard-capped atmax_len(e.g., 512 or 1,024 tokens; cannot extrapolate by even 1 token!).
2. Sinusoidal Multi-Frequency Clocks vs. ALiBi Linear Bias
Before RoPE took over, ALiBi (Press et al., 2022) showed you could simply subtract a fixed linear distance penalty -s_h · |m − n| from attention logits — zero positional embeddings needed! Then RoPE combined multi-frequency expressiveness with pure relative geometry.
Why Multi-Frequency Dimensions Matter
Just like a clock needs both a second hand (fine local precision) and an hour hand (long-range tracking), encoding position across geometric frequencies lets nearby tokens distinguish 1-word vs. 2-word gaps while distant paragraphs stay distinguishable across 128,000 tokens!
3. RoPE Math: Rotating 2D Pairs & Long-Context Scaling (YaRN / NTK)
Slide BOTH m and n forward by +10 in the tester below to prove that RoPE's relative angle (m − n)·θ stays 100% invariant!
Exact 2D RoPE Rotation Formula (Su et al., 2021)
For each 2D pair at position with frequency : Because rotation matrices satisfy , the dot product between rotated Query and Key is: Pure relative position ! And because rotating a vector preserves its L2 norm (), RoPE never destabilizes attention variance!
⟨R_m q, R_n k⟩ = qᵀ R_{n−m} k
Query at position m rotated counterclockwise by m·θ_i per 2D pair.
'animal' and 'it' sit at positions (1, 7) or (1001, 1007), their relative offset is −6, so RoPE rotates them to the exact same relative angle!Worked Example: Rotating a 2D Vector by 90° With RoPE
Let 2D query slice q = [1, 0] and key slice k = [1, 0], with θ = π/4 (45°/step), at positions m = 2 (90°) and n = 1 (45°).
, .
RoPE Relative-Distance Invariance Tester
Try shifting BOTH m and n by +10 — notice the relative angle 57° and dot product stay 100% identical!
Why does RoPE NEVER modify the Value tensor V?
Why did LLaMA 3 raise RoPE's base frequency from 10,000 (LLaMA 2) up to 500,000?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Using the 1-line rotate_half trick: q_rot = (q * cos) + (rotate_half(q) * sin) — pure element-wise multiply-add (O(d_k) instead of O(d_k²) matrix multiply)!
m and n spin!RoPE (Rotary Positional Embedding) 2D Complex-Plane Studio
Watch Query (pos m) and Key (pos n = m − 4) spin together around the 2D circle — their relative angle (m − n)·θ stays 100% constant at every position!
Q and K in 2D pairs at geometric frequencies (0 extra params) so ⟨R_m q, R_n k⟩ depends purely on relative distance (m − n) and scales cleanly to 128K+ context!LLaMA 3 / Gemma 2 / Qwen 2.5 / DeepSeek
Universal relative positional encoding with base = 500,000–1,000,000 for 128K+ context.
YaRN Long-Context Extension
Frequency-aware RoPE scaling extends 4K/8K pretrained checkpoints to 128K with <0.1% extra training tokens.
2D RoPE in Vision & Video (Flux / Qwen-VL)
Splits head dims into X-axis and Y-axis rotations to encode native 2D image/video coordinates!
import torch
# Fast Production RoPE Implementation (LLaMA / Gemma rotate_half trick!)
def rotate_half(x: torch.Tensor) -> torch.Tensor:
# Splits last dim in half: [-x2, x1] -> equivalent to 2D 90-degree rotation!
x1, x2 = x.chunk(2, dim=-1)
return torch.cat((-x2, x1), dim=-1)
def apply_rope(q: torch.Tensor, k: torch.Tensor, base: float = 10000.0):
# q, k: (B, H, T, d_k)
_, _, T, d_k = q.shape
inv_freq = 1.0 / (base ** (torch.arange(0, d_k, 2, device=q.device).float() / d_k))
pos = torch.arange(T, device=q.device).float()
angles = torch.outer(pos, inv_freq) # (T, d_k/2)
emb = torch.cat([angles, angles], dim=-1) # (T, d_k)
cos, sin = emb.cos()[None, None], emb.sin()[None, None]
q_rot = (q * cos) + (rotate_half(q) * sin)
k_rot = (k * cos) + (rotate_half(k) * sin)
return q_rot, k_rot
V as well as Q and K.Q and K!⟨R_m q, R_n k⟩ depend ONLY on relative token distance (m − n) in RoPE?base (e.g., from 10,000 to 500,000) help long-context LLMs?