Day 3:Week 7, Day 3: Positional Encodings — Sinusoidal vs Rotary Position Embeddings
Battle-tested daily lesson note • 100% runnable code, interview Q&A, test suite & interactive quiz
Week 7, Day 3: Positional Encodings — Sinusoidal vs Rotary Position Embeddings (RoPE)
1. Why Unmodified Self-Attention is a "Bag of Words"
Look closely at .
If you swap the order of tokens in a sentence ("dog bites man" vs "man bites dog"), the rows of simply permute in the exact same way (Permutation Equivariance). Without positional information, a Transformer cannot tell whether a word appeared at position 1 or position 1,000!
2. Generation 1: Additive Sinusoidal Positional Encodings (2017)
The original 2017 Transformer added a fixed vector directly to the input token embeddings :
Limitation of Additive Encodings:
- Positional information is only injected at Layer
0and gets diluted after passing through dozens of linear projections. - It encodes absolute position , whereas attention dot products fundamentally care about the relative distance between Query token and Key token .
3. Generation 2 (Modern Standard): Rotary Position Embeddings (RoPE)
Used in Llama-3, Qwen, Mistral, Gemma, PaLM, DeepSeek (Su et al., "RoFormer", 2021). Instead of adding a vector to embeddings at Layer 0, RoPE rotates Query and Key inside every attention layer by an angle proportional to their position index and !
The $2 \times 2$ Rotation Matrix Derivation
Group each head's dimensions into two-dimensional pairs . Rotate the 2D vector at token position by angle :
Why RoPE is Mathematically Brilliant: Relative Distance Invariance!
When we compute the attention dot product between rotated Query at position and rotated Key at position :
Because the transpose of a rotation by followed by a rotation by is simply a rotation by , the dot product depends ONLY on the relative token distance !
Whether two words are at positions (2, 5) or (1002, 1005) (both distance 3 apart), their RoPE attention dot product is 100% identical!
In Simple English: Why Transformers Need Word Order (RoPE Clock Hands)
Self-Attention looks at all words at the exact same time — so without position numbers, "Dog bites man" and "Man bites dog" would look identical!
- Old Fix (Sinusoidal): Stamp a unique barcode wave onto each slot (#1, #2, #3...). Downside: works poorly if tested on longer texts than training.
- Modern Fix (
RoPE— Rotary Position Embeddings): Think of each pair of numbers in a word's vector as a clock hand! Word at position 1 turns the hand by $1\theta; word at position 5 turns it by \5\theta. When you take the dot product between word 1 and word 5, the angle depends ONLY on their **gap (\5 - 1 = 4$ words apart)** — letting Llama, Qwen, and Claude generalize naturally across long contexts!