Chapter 6 of 40 · ~26 min read & lab+85 XP
Chapter 6 · Generative AI

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!

What Is It?

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).

Why Is It Required?

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.

Everyday Analogy: Turning clock hands forward by a fixed angle for each word position so the angle gap between two words directly reveals how far apart they sit.
Why ML Engineers & Data Scientists Actually Need This

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!

ML / AI Engineer

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.

Data Scientist

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!

Interview & Debug Edge

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?'

Step 0 · Test Your Gut Before Any Math!

In a Transformer using Rotary Positional Embeddings (RoPE), which tensors get rotated by the position-dependent rotation matrix R_m?

What You Will Master in This Chapter
  • 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
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 4
m, nSay aloud:“query & key positions”
Plain-English Meaning
0-indexed integer token positions in the sequence
Everyday Example
Relative distance = m − n
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

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

Everyday Story First (Zero Math Yet!)

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!

Why Attention Needs Position: Pure Self-Attention Treats Text as a Bag of Words!"Dog bites man"Same Q, K, V dot products!="Man bites dog"Identical output without pos!Unlike RNNs (which loop t=1..T), Transformers process all tokens in parallel → must inject position explicitly!
Pure Self-Attention is a set operation: without positional encodings, 'Dog bites man' and 'Man bites dog' produce the exact same attention outputs per word!

Absolute Positional Encodings (2017–2020)

  • Sinusoidal (Original Transformer): Adds fixed sine/cosine waves PE(m,2i)=sin⁡(m/100002i/D)PE(m, 2i) = \sin(m / 10000^{2i/D}) directly to token embeddings XX.
  • Learned Absolute (GPT-2 / BERT): Learns a lookup table nn.Embedding(max_len, D) — hard-capped at max_len (e.g., 512 or 1,024 tokens; cannot extrapolate by even 1 token!).

2. Sinusoidal Multi-Frequency Clocks vs. ALiBi Linear Bias

Everyday Story First (Zero Math Yet!)

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.

Sinusoidal Positional Encoding: Multi-Frequency Binary-Like Clock Handsdim 0dim 8dim 64Fast dims track local neighbor offsets; slow dims track paragraph-level distance!
Sinusoidal positional encodings assign each dimension pair a different wavelength — like a multi-hand clock (seconds, minutes, hours) uniquely stamping every position.

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 dk/2d_k / 2 geometric frequencies θi=base−2i/dk\theta_i = \text{base}^{-2i/d_k} 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)

Everyday Story First (Zero Math Yet!)

Slide BOTH m and n forward by +10 in the tester below to prove that RoPE's relative angle (m − n)·θ stays 100% invariant!

RoPE (Rotary Embeddings): Rotate Q by m·θ & K by n·θ → Angle Depends ONLY on (m − n)!R_n kR_m qΔθ = (m − n)θWhy Frontier LLMs All Use RoPE⟨R_m q, R_n k⟩ = qᵀ R_{n−m} k• Pure relative position baked into Q·K!• 100% compatible with KV-Cache & YaRN!
Rotary Positional Embeddings (RoPE) rotate each 2D pair of Query and Key by angle m·θ_i so their dot product ⟨R_m q, R_n k⟩ depends purely on relative distance (m − n)!

Exact 2D RoPE Rotation Formula (Su et al., 2021)

For each 2D pair (x0,x1)(x_0, x_1) at position mm with frequency θi\theta_i: [x0′x1′]=[cos⁡(mθi)−sin⁡(mθi)sin⁡(mθi)cos⁡(mθi)][x0x1]\begin{bmatrix} x_0' \\ x_1' \end{bmatrix} = \begin{bmatrix} \cos(m\theta_i) & -\sin(m\theta_i) \\ \sin(m\theta_i) & \cos(m\theta_i) \end{bmatrix} \begin{bmatrix} x_0 \\ x_1 \end{bmatrix} Because rotation matrices satisfy Rm⊤Rn=Rn−mR_m^\top R_n = R_{n - m}, the dot product between rotated Query and Key is: ⟨Rmq,  Rnk⟩=q⊤Rm⊤Rnk=q⊤Rn−mk\langle R_m q, \; R_n k \rangle = q^\top R_m^\top R_n k = q^\top R_{n - m} k Pure relative position (m−n)(m - n)! And because rotating a vector preserves its L2 norm (∥Rmq∥2=∥q∥2\|R_m q\|_2 = \|q\|_2), RoPE never destabilizes attention variance!

Formula Anatomy · Click Any Colored Piece to Decode It
Anatomy of the RoPE Relative-Position Identity

⟨R_m q, R_n k⟩ = qᵀ R_{n−m} k

Rotated Query

Query at position m rotated counterclockwise by m·θ_i per 2D pair.

In our example: Preserves ‖q‖₂
Put it together with real numbers: Whether '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!
Walk Through With Me · Interactive Worked Example

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°).

11. Rotate q by 90° and k by 45°Step 1 / 2

R2q=[0,1]R_2 q = [0, 1], R1k=[0.707,0.707]R_1 k = [0.707, 0.707].

Teacher's Note: Both vectors stay unit length!
Animated Mini-Lab • 1.5

RoPE Relative-Distance Invariance Tester

Δpos = m − n = 4 → Δangle = 57°

Try shifting BOTH m and n by +10 — notice the relative angle 57° and dot product stay 100% identical!

Pause & Check · Quick Intuition Pulse

Why does RoPE NEVER modify the Value tensor V?

Try It YourselfStandard

Why did LLaMA 3 raise RoPE's base frequency from 10,000 (LLaMA 2) up to 500,000?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

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)!

Interactive Visual Lab
Lab Challenge: Switch between High, Mid, and Low frequencies in the RoPE Complex-Plane Studio below and verify that ΔAngle stays constant as both m and n spin!
Interactive Animation • 1.5 Deep Lab

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!

Query R_m q (angle = 0°)Key R_n k (angle = 0°)ΔAngle = 0.0° (CONSTANT!)cos(ΔAngle) = 1.000 at every pos m!
0%
pos m=0, n=0 (Δ=4)
Intuition Takeaway: Self-Attention is blind to word order on its own; RoPE rotates 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!
Where This Powers Real ML, Deep Learning & Generative AI

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!

Production NumPy & PyTorch Code Patterns
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
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Applying RoPE to V as well as Q and K.
Best Practice: Rotate ONLY Q and K!
Trap #2: Thinking RoPE adds trainable parameters.
Best Practice: RoPE uses fixed trigonometric frequencies — 0 trainable parameters!
Chapter Mastery Check (+85 XP)
Score: 0 / 5
1Why does ⟨R_m q, R_n k⟩ depend ONLY on relative token distance (m − n) in RoPE?
2Which tensors receive RoPE rotation inside a Transformer Attention layer?
3How many trainable parameters does standard RoPE add to a Transformer?
4What happens if you remove ALL positional encodings from a Transformer?
5How does raising RoPE's base (e.g., from 10,000 to 500,000) help long-context LLMs?

Apply What You Learned — Solve Matching Coding Problems