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.
Prerequisites
Table of Contents
- Learning Objectives
- Notation
- Core Intuition
- Why Position Matters
- Sinusoidal Positional Encoding
- Learned Positional Embeddings
- Rotary Position Embedding (RoPE)
- ALiBi (Attention with Linear Biases)
- Length Generalization
- Common Pitfalls
- Summary
- Exercises
Learning Objectives
- Prove that attention without positional encoding is permutation-invariant.
- Derive sinusoidal positional encoding and explain the geometric intuition.
- Derive RoPE from the relative position kernel requirement.
- Compare absolute vs relative position methods.
- Explain how RoPE enables context length extension.
Notation
- — absolute position index
- — frequency for dimension
- — rotation matrix for RoPE
- — 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)
Why Position Matters
Theorem. Self-attention is permutation-equivariant. For any permutation matrix :
Proof. Let , similarly , .
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:
where .
Properties:
- Each dimension oscillates at a different frequency (from to ).
- Relative positions can be expressed as linear transformations: for a matrix depending only on .
- Bounded norm regardless of position.
Geometric interpretation: Position is encoded as a point on a -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:
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:
where are absolute positions but the result depends only on the difference.
Solution (2D case): Apply a rotation of angle to the query, and to the key:
Then:
General dimensions: Apply independent 2D rotations to each consecutive pair of dimensions, with frequencies (where ):
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:
where is a head-specific slope ( 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 degrade at length .
Methods for extending context:
- RoPE frequency scaling (NTK-aware): Scale base frequency to accommodate longer sequences:
- YaRN: Combines NTK scaling with attention temperature scaling.
- Position interpolation: Map positions to : use position .
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 for 2D rotation matrices.
Exercise 2. Compute the dot product for .
Exercise 3. Prove that sinusoidal positional encoding satisfies for an explicit matrix .
Exercise 4. For ALiBi with heads, compute all slope values .
Exercise 5. Explain why position interpolation (scaling to ) degrades less than extrapolation for RoPE.