Positional Encoding

Positional Encoding

The core mathematical engine of the Transformer is self-attention. While self-attention allows every token to directly interact with every other token in a single parallel operation, it possesses a fundamental mathematical property: permutation equivariance.

Let be an input sequence of token embeddings, and let be an arbitrary permutation matrix that shuffles the rows of . Applying self-attention to the permuted sequence yields:

Permuting the inputs simply permutes the outputs identically. The operation itself contains zero structural awareness of sequence order. To a pure transformer without positional coordinates, the sentences:

  • The dog bit the mailman.
  • The mailman bit the dog.

produce identical sets of contextual representations. Because language, syntax, logic, and causality depend strictly on word order, models must explicitly break this permutation symmetry by injecting positional coordinates into the vector representations.


Why Transformers Need Positional Information

To teach a neural network where words appear in time, two primary philosophies exist:

Encoding FamilyMathematical FormulationGeometric Mechanism
Absolute Additive
(Sinusoidal, 2017)
Adds a deterministic trigonometric vector directly to the token embedding at the input layer. Mixes semantic content and absolute index in the same vector space.
Multiplicative Rotary (RoPE)
(Su et al. 2021)
Rotates Query and Key 2D feature pairs in the complex plane inside every attention layer so attention dot products depend strictly on relative distance while preserving Euclidean norm .

Sinusoidal Positional Encoding

The original Transformer encoded sequence position by adding deterministic trigonometric waves of geometrically decreasing frequencies directly to token embeddings:

where is the token position index (), is the dimension pair index (), and is the model embedding dimension.

Geometric Intuition

Think of sinusoidal encoding like a multi-hand clock or a binary counter:

  • Dimension (High-Frequency Hand): Has a wavelength of tokens (). It oscillates rapidly, allowing the model to distinguish between immediately adjacent words (cat sat vs sat cat).
  • Intermediate Dimensions (Mid-Frequency Hand): Have wavelengths spanning hundreds of tokens, capturing phrase and clause boundaries.
  • Highest Dimensions (Low-Frequency Hand): Have wavelengths spanning tens of thousands of tokens (), tracking high-level thematic position across long documents.

Because every position produces a unique fingerprint across the frequency spectrum, the model can infer both absolute location and relative distance through trigonometric linear combinations ().


Rotary Position Embedding (RoPE)

While sinusoidal encodings add vectors (), modern frontier LLMs (LLaMA 3, Mistral, Gemma, Qwen) use Rotary Position Embeddings (RoPE).

Instead of adding static vectors to word embeddings, RoPE treats pairs of features inside the Query and Key vectors as 2D complex numbers and rotates them by an angle proportional to the token’s position.

1. Rotating Query and Key Vectors

For a 2D feature pair at token position , RoPE applies the 2D rotation matrix :

In the complex plane , if we write the 2D vector as a complex number , multiplying by is mathematically equivalent to multiplying by a complex phase factor:

2. Relative Position Invariance

Suppose token emits Query and token emits Key . When the self-attention layer computes their dot product:

Because rotation matrices are orthogonal () and rotations compose additively ():

The Core Mathematical Invariance:
The inner product depends strictly on the relative displacement , completely independent of absolute token coordinates.
Whether two words appear at positions or positions , their relative angle is , producing an identical attention score!


Interactive RoPE Simulator

Use the interactive simulator below to rotate Query and Key on the complex unit circle. Notice that shifting both positions simultaneously preserves the relative angle and produces the exact same dot product:

Rotary Position Embedding (RoPE) Relative Invariance Simulator

Shift both tokens forward in a sentence () to see how the relative angle and dot product stay 100% constant.

1.0
3.0
30°
ReImqmkn
Query Angle () 30.0°
Token at position rotates counterclockwise by .
Key Angle () 90.0°
Token at position rotates counterclockwise by .
Relative Angle 60.0° (n−m = 2.0)
Dot Product : +0.500
Relative Distance Principle: Because ⟨R(mθ)q, R(nθ)k⟩ = ⟨q, R((n−m)θ)k⟩, shifting both tokens by the same offset preserves the relative wedge angle and dot product. Δpos = 2.0
Shift Offset Δ:

Extending Context Windows: RoPE Scaling & YaRN

When an LLM trained with RoPE on an -token context window is asked to evaluate tokens, the rotation angles enter unobserved geometric territory, causing attention entropy to destabilize.

Modern techniques extend context windows without retraining from scratch:

  1. Linear Position Interpolation (PI): Scales down position indices . This maps all positions back into the observed range, but compresses high-frequency dimensions too tightly, impairing local grammatical distinctions.
  2. Base Frequency Scaling (Llama 3): Increasing the base frequency from to (or ) slows the rotation rate across all dimensions, preserving fine-grained positional resolution across tokens.
  3. YaRN (Yet another RoPE extensioN): Applies non-uniform frequency scaling. It leaves high frequencies unscaled (preserving local syntax), linearly interpolates low frequencies (expanding long-range context), and applies an entropy temperature correction to prevent attention dilution.

Comparing Positional Encodings

ParadigmExemplar ModelsMathematical MechanismExtrapolation to Unseen Lengths
Learned AbsoluteGPT-2, BERTLearned embedding matrix Zero — Hard error if sequence length exceeds
Sinusoidal AbsoluteVaswani (2017)Fixed harmonic sine/cosine waves added to token vectorsPoor — Attention weights degrade outside training length
Relative Bias (ALiBi)MPT, BLOOMSubtracts distance penalty directly from attention logits ()Excellent — Trains on 2k, tests on 8k+ without fine-tuning
Rotary (RoPE)LLaMA 3, Mistral, GemmaMultiplies Q and K by block-diagonal 2D complex rotation matricesVery High — Scales seamlessly to 128k–1M tokens with YaRN

Key Papers & References