← Explainer Library

Interactive Explainer

Positional Encodings — Sinusoid, RoPE, ALiBi

Transformer attention is permutation-invariant: "dog bites man" and "man bites dog" would produce identical logits. Position has to be injected from somewhere else. Three families have won; this article shows all three on the same axes — heatmap, similarity matrix, RoPE rotation, extrapolation curves.

Prelude

Why attention forgets order

Plain attention computes $\text{softmax}(QK^\top / \sqrt d)\, V$. Each output token is a weighted sum over all the input tokens — but the weights depend only on the content of $Q$ and $K$, not on their indices. Permute the input sequence and every attention weight is permuted along with it. The output set is the same set.

That symmetry is fatal for any task that depends on order, which is every interesting task language has. Three families of fixes have prevailed:

They differ along three axes that matter at scale: parameter count, ability to extrapolate to longer sequences than seen at training, and computational cost. Each of the three sections below makes those differences visceral.

Step 1

Sinusoidal — one frequency per dimension

Pick a sequence length and embedding dimension. The heatmap below shows the full positional encoding tensor: rows are positions $0, 1, \ldots, L-1$, columns are embedding dimensions $0, 1, \ldots, d-1$. Even columns are sines; odd columns are cosines. Each dimension has its own frequency, spaced geometrically from $1$ down to $1 / 10000$.

64 32

positional-encoding matrix (rows = position, columns = embedding dim)

Reading the picture. Leftmost columns oscillate fast (high-frequency, distinguishing neighbours). Rightmost columns oscillate slowly (low-frequency, encoding broad position bands). Together they form a "binary clock" where every position has a unique fingerprint.

The headline property: $\mathrm{PE}_{\text{pos}+k}$ is a fixed linear function of $\mathrm{PE}_{\text{pos}}$ for any offset $k$. So a transformer can recover relative position from the absolute encoding via a learned linear map. This was the original argument for why a fixed sinusoid would work as well as a learned table.

Below: the cosine similarity between every pair of positions. Diagonal is 1 (each position with itself); the dropoff away from the diagonal tells you how distinguishable nearby positions are.

cosine similarity matrix between positions ⟨PEi, PEj

Higher values = positions look similar to attention. Smooth fall-off near the diagonal is exactly what we want — close positions are confusable; far ones are cleanly distinguished.
Step 2

RoPE — encode position by rotating

Sinusoidal PE has a known weakness: it's added to the embedding once, and the attention layer has to spend capacity recovering relative position from the sum. RoPE inverts this: instead of adding position, it rotates the queries and keys.

Pair adjacent dimensions $(2i, 2i+1)$. For position $\text{pos}$, rotate that 2D sub-vector by an angle $\theta_i = \text{pos} \cdot 10000^{-2i/d}$. The dot product between a rotated query at position $i$ and a rotated key at position $j$ then becomes a function only of the difference $j - i$.

5 15 10000

two rotated query/key vectors (one 2D sub-pair)

dot product Qi · Kj as i, j slide

The headline: change positions 1 and 2 to (5, 15) or (20, 30) — the offset is 10 in both. The dot product is identical. RoPE has factored absolute position out of the attention score; only relative position remains.

Why this matters for long context. With pure absolute encodings, every position has a distinct embedding. Train on positions $0$–$2047$, test on position $4096$, and the embedding for $4096$ has never been seen. With RoPE, only the relative offset enters the dot product. Inference at offset 100 looks the same whether the absolute positions are $(0, 100)$ or $(5000, 5100)$.
Step 3

ALiBi — a linear penalty on distance

The simplest of the three. Skip positional encodings at the embedding layer entirely. Add a fixed bias $-m \cdot |i - j|$ to the attention score, where the slope $m$ is hand-set per head (a geometric sequence across heads — head $h$ uses $m_h = 2^{-8h/H}$).

The matrix below shows the bias on a 32×32 attention grid for one head. Pick a slope. The bias is uniformly negative and grows with distance: it penalises attending to faraway tokens — equivalently, biases each token toward attending to its neighbours.

2 m = 0.25 32

ALiBi bias matrix (lower-triangular for causal attention)

per-head slope schedule

Different heads use different slopes; some heads focus on local context (steep slope), others on broad context (gentle slope). The schedule is fixed at training time and never trained.

ALiBi's selling point: extrapolation. There's nothing in the bias matrix that depends on absolute position — only on $|i - j|$. The model trained on length 2048 can be deployed at length 16384 with no degradation in the relative-position signal it sees.

Step 4

Extrapolation — train at 2k, test at 32k

The benchmark that put RoPE and ALiBi on the map: train a transformer with a max context of 2048 tokens; evaluate perplexity at 4k, 8k, 16k, 32k. A scheme that has memorised absolute positions $0$–$2047$ will fall off a cliff past 2048. A scheme that uses only relative information will degrade gracefully.

Below: the three positional-encoding schemes scored on a synthetic "relative-position recall" task. The metric is the cosine similarity between the model's representation of a query at distance $\Delta$ in training (≤ 2k) versus the same offset at test (up to 32k). High and flat is good; falling is bad. The numbers reproduce the qualitative finding from Press et al. (2022):

sinusoidal

trained 0–2k. drops sharply past 2k — model has never seen position 4000.

RoPE

only relative offsets matter; degrades gradually as the angle wraps.

ALiBi

flat. nothing in the bias depends on absolute position.
The pattern. Sinusoidal collapses past the training length because its high-frequency dimensions wrap around in ways the model has never optimised against. RoPE degrades because its rotation angles wrap when positions exceed $\pi / \theta_{\min}$. ALiBi doesn't degrade because its $-m \cdot |i - j|$ never changes character: at $\Delta = 10000$ it's still just a slightly bigger negative bias.
Step 5

When to use what

scheme where added learnable? relative? extrapolates? used by
learned absolute token embedding yes no no (fixed table) BERT, GPT-2
sinusoidal token embedding no recoverable partially original Transformer (Vaswani 2017)
RoPE Q, K (in attention) no yes (in dot product) yes (with NTK / YaRN tricks) Llama family, PaLM, GPT-NeoX, Mistral
ALiBi attention score no yes (purely) yes BLOOM, MPT
T5 relative attention score (per-bucket bias) yes (small table) yes partially T5

The post-2022 consensus: RoPE is the modern default for autoregressive LLMs; ALiBi is preferred when extrapolation is the top concern and the model is single-task. Learned absolute is the legacy baseline; nobody picks it for a new model.

NTK-aware scaling, YaRN, and dynamic NTK are all techniques for extending RoPE-trained models beyond their training length. They rescale the base frequency to keep rotation angles in the seen range. None of them comes free — there is always some accuracy trade-off, well-documented in the long-context benchmarks (LongBench, Needle in a Haystack, RULER).

Step 6

Three misconceptions

"RoPE has no parameters." → true, but...
...the rotation base $\theta = 10000$ is a hyperparameter and choosing it badly hurts long-context behaviour. Llama-3 uses $\theta = 500{,}000$ to make the angles wrap less aggressively at long distances. NTK-aware scaling can be viewed as dynamically picking $\theta$ at inference time.
"ALiBi extrapolates perfectly to infinite context."
ALiBi degrades less than sinusoidal or RoPE, but it does degrade: the model has only seen attention scores with bias magnitudes up to $2048 \cdot m$. Past that range, the model's behaviour relies on the assumption that a slightly larger bias has the same qualitative effect — which holds in practice but not perfectly.
"Positional encoding is decoupled from attention."
Sinusoidal encoding adds to the embedding once, before attention sees anything; in that sense it is decoupled. RoPE is inside the attention computation (rotates Q and K). ALiBi is also inside attention (a bias on logits). The trend has been to push position deeper into the attention machinery, not keep it outside.
Step 7

Reading list