Positional Encoding & RoPE

Why transformers need positional information, derivation of sinusoidal encoding, learned embeddings, Rotary Position Embedding (RoPE), ALiBi, and how position representations enable length generalization.

Intermediate

Table of Contents

  1. Learning Objectives
  2. Notation
  3. Core Intuition
  4. Why Position Matters
  5. Sinusoidal Positional Encoding
  6. Learned Positional Embeddings
  7. Rotary Position Embedding (RoPE)
  8. ALiBi (Attention with Linear Biases)
  9. Length Generalization
  10. Common Pitfalls
  11. Summary
  12. Exercises

Learning Objectives

  1. Prove that attention without positional encoding is permutation-invariant.
  2. Derive sinusoidal positional encoding and explain the geometric intuition.
  3. Derive RoPE from the relative position kernel requirement.
  4. Compare absolute vs relative position methods.
  5. Explain how RoPE enables context length extension.

Notation

  • pos\text{pos} — absolute position index
  • ωk=1/100002k/d\omega_k = 1/10000^{2k/d} — frequency for dimension kk
  • Rθ\mathbf{R}_\theta — rotation matrix for RoPE
  • mm — slope parameter in ALiBi

Core Intuition

Self-attention treats its input as a set — it is permutation-equivariant by construction. This means without positional information, "The cat sat on the mat" and "mat the on sat cat The" produce identical attention patterns. Positional encoding breaks this symmetry, telling the model where each token is.

Rotary Position Embeddings (RoPE)

Q (pos 0)K (pos 4)θ = m·ωRelative distance4Q·K dot product0.000Decay ≈ cos(θ)0.000distance →
Distance
4
Query vectorKey vector
Explore: RoPE rotates Q and K by position-dependent angles. The dot product depends only on relative distance — attention naturally decays for distant tokens.

Why Position Matters

Theorem. Self-attention is permutation-equivariant. For any permutation matrix P\mathbf{P}:

Attention(PX)=PAttention(X).(1)\text{Attention}(\mathbf{PX}) = \mathbf{P} \cdot \text{Attention}(\mathbf{X}). \tag{1}

Proof. Let Q=PXWQ=PQ\mathbf{Q}' = \mathbf{PXW}^Q = \mathbf{PQ}, similarly K=PK\mathbf{K}' = \mathbf{PK}, V=PV\mathbf{V}' = \mathbf{PV}.

softmax(QKT/dk)V=softmax(PQKTPT/dk)PV=Psoftmax(QKT/dk)V.  \text{softmax}(\mathbf{Q}'\mathbf{K}'^T/\sqrt{d_k})\mathbf{V}' = \text{softmax}(\mathbf{PQK}^T\mathbf{P}^T/\sqrt{d_k})\mathbf{PV} = \mathbf{P}\text{softmax}(\mathbf{QK}^T/\sqrt{d_k})\mathbf{V}. \; \blacksquare

Thus, without positional encoding, word order has no effect on the computation.


Sinusoidal Positional Encoding

Original Transformer (2017): Add fixed sinusoidal vectors to token embeddings:

PE(pos,2k)=sin(posωk),PE(pos,2k+1)=cos(posωk),(2)\text{PE}(\text{pos}, 2k) = \sin(\text{pos} \cdot \omega_k), \quad \text{PE}(\text{pos}, 2k+1) = \cos(\text{pos} \cdot \omega_k), \tag{2}

where ωk=1/100002k/d\omega_k = 1/10000^{2k/d}.

Properties:

  • Each dimension oscillates at a different frequency (from 2π2\pi to 2π100002\pi \cdot 10000).
  • Relative positions can be expressed as linear transformations: PE(pos+k)=MkPE(pos)\text{PE}(\text{pos}+k) = \mathbf{M}_k \cdot \text{PE}(\text{pos}) for a matrix Mk\mathbf{M}_k depending only on kk.
  • Bounded norm regardless of position.

Geometric interpretation: Position pp is encoded as a point on a d/2d/2-dimensional torus, with each pair of dimensions tracing a circle at a different angular velocity.


Learned Positional Embeddings

Replace fixed sinusoids with a learnable lookup table:

xpos=etoken+ppos,pposRd (learned).(3)\mathbf{x}_{\text{pos}} = \mathbf{e}_{\text{token}} + \mathbf{p}_{\text{pos}}, \quad \mathbf{p}_{\text{pos}} \in \mathbb{R}^d \text{ (learned)}. \tag{3}

Advantage: Can learn task-specific positional patterns. Disadvantage: Cannot generalize to positions unseen during training.

Used in: GPT-2, BERT.


Rotary Position Embedding (RoPE)

Key insight: Encode position into the dot-product directly, making the attention score depend only on relative position.

Requirement: Find a position encoding such that:

f(q,m),f(k,n)=g(q,k,mn),(4)\langle f(\mathbf{q}, m), f(\mathbf{k}, n) \rangle = g(\mathbf{q}, \mathbf{k}, m - n), \tag{4}

where m,nm, n are absolute positions but the result depends only on the difference.

Solution (2D case): Apply a rotation of angle θ=mω\theta = m \cdot \omega to the query, and θ=nω\theta = n \cdot \omega to the key:

f(x,p)=(cos(pω)sin(pω)sin(pω)cos(pω))(x1x2)=Rpωx.(5)f(\mathbf{x}, p) = \begin{pmatrix}\cos(p\omega) & -\sin(p\omega) \\ \sin(p\omega) & \cos(p\omega)\end{pmatrix}\begin{pmatrix}x_1 \\ x_2\end{pmatrix} = \mathbf{R}_{p\omega}\mathbf{x}. \tag{5}

Then:

f(q,m),f(k,n)=qTRmωTRnωk=qTR(nm)ωk.(6)\langle f(\mathbf{q}, m), f(\mathbf{k}, n) \rangle = \mathbf{q}^T\mathbf{R}_{m\omega}^T\mathbf{R}_{n\omega}\mathbf{k} = \mathbf{q}^T\mathbf{R}_{(n-m)\omega}\mathbf{k}. \tag{6}

General dd dimensions: Apply independent 2D rotations to each consecutive pair of dimensions, with frequencies ωk=θ2k/d\omega_k = \theta^{-2k/d} (where θ=10000\theta = 10000):

RΘ,p=diag(Rpω0,Rpω1,,Rpωd/21).(7)\mathbf{R}_{\Theta, p} = \text{diag}(\mathbf{R}_{p\omega_0}, \mathbf{R}_{p\omega_1}, \ldots, \mathbf{R}_{p\omega_{d/2-1}}). \tag{7}

Properties:

  • Relative position encoding via absolute rotations.
  • No additional parameters.
  • Decays naturally with distance (due to oscillation).
  • Compatible with KV-cache (position applied at projection time).

Used in: LLaMA, Mistral, GPT-NeoX, most modern LLMs.


ALiBi (Attention with Linear Biases)

Approach: No positional embedding at all. Instead, add a linear bias to attention scores:

score(i,j)=qiTkjdkmij,(8)\text{score}(i, j) = \frac{\mathbf{q}_i^T\mathbf{k}_j}{\sqrt{d_k}} - m \cdot |i - j|, \tag{8}

where mm is a head-specific slope (mh=28h/Hm_h = 2^{-8h/H} for geometric spacing).

Effect: Penalizes distant tokens linearly. Closer tokens always have higher baseline scores.

Advantage: Excellent length generalization — trains on short sequences, works on longer ones.

Used in: BLOOM, MPT.


Length Generalization

Problem: Models trained on length TtrainT_{\text{train}} degrade at length Ttest>TtrainT_{\text{test}} > T_{\text{train}}.

Methods for extending context:

  • RoPE frequency scaling (NTK-aware): Scale base frequency θ\theta to accommodate longer sequences:
θ=θ(TtestTtrain)d/(d2).(9)\theta' = \theta \cdot \left(\frac{T_{\text{test}}}{T_{\text{train}}}\right)^{d/(d-2)}. \tag{9}
  • YaRN: Combines NTK scaling with attention temperature scaling.
  • Position interpolation: Map positions [0,Ttest][0, T_{\text{test}}] to [0,Ttrain][0, T_{\text{train}}]: use position pTtrain/Ttestp \cdot T_{\text{train}}/T_{\text{test}}.

Common Pitfalls

Pitfall 1. Adding positional encoding to both Q and K and V. Standard practice adds position to the input (affecting all), but RoPE only rotates Q and K (not V). Applying to V would make the value content position-dependent, which is undesirable.

Pitfall 2. Assuming learned positional embeddings generalize. They strictly cannot: position 4097 has no embedding if training used max length 4096.

Pitfall 3. Extending RoPE context without fine-tuning. Raw extrapolation fails; some fine-tuning on longer data is needed after frequency adjustment.


Summary

  • Without positional encoding, attention is permutation-invariant.
  • Sinusoidal: Fixed frequencies, limited to training length.
  • Learned: Flexible but non-generalizable.
  • RoPE: Rotary encoding that injects relative position into dot products; dominant approach.
  • ALiBi: Linear bias penalty; excellent generalization.
  • Context extension: NTK scaling, YaRN, position interpolation.

Exercises

Exercise 1. Verify that RαTRβ=Rβα\mathbf{R}_\alpha^T\mathbf{R}_\beta = \mathbf{R}_{\beta-\alpha} for 2D rotation matrices.

Exercise 2. Compute the dot product RoPE(q,5),RoPE(k,3)\langle \text{RoPE}(\mathbf{q}, 5), \text{RoPE}(\mathbf{k}, 3)\rangle for q=[1,0],k=[0,1],ω=π/4\mathbf{q} = [1, 0], \mathbf{k} = [0, 1], \omega = \pi/4.

Exercise 3. Prove that sinusoidal positional encoding satisfies PE(p+k)=MkPE(p)\text{PE}(p+k) = M_k \cdot \text{PE}(p) for an explicit matrix MkM_k.

Exercise 4. For ALiBi with H=8H=8 heads, compute all slope values mhm_h.

Exercise 5. Explain why position interpolation (scaling pp to pTtrain/Ttestp \cdot T_{\text{train}}/T_{\text{test}}) degrades less than extrapolation for RoPE.