Skip to content
Transformers and LLMs Core 26 min read

Positional encoding: sinusoidal, RoPE, ALiBi

Attention treats its input as a bag of tokens, so a transformer has to be told where each token is. The answer the field converged on — rotate each query and key by an angle proportional to its position (RoPE) — makes attention scores depend only on how far apart two tokens are, and it is the reason "extending the context window" is mostly a matter of adjusting a few frequencies.

10,000 ft

Self-attention is permutation-equivariant: shuffle the tokens and you shuffle the outputs, nothing more. Yet "dog bites man" and "man bites dog" must mean different things. Positional encoding is how order is put back. The choice looks like a detail but governs three things that matter a great deal in practice: whether the model can handle sequences longer than it was trained on, how cheaply the context window can be extended after training (see long context), and how attention behaves over distance. The history runs from adding fixed sinusoids to the input (2017), through learned and relative schemes, to rotary position embedding (RoPE), used by PaLM, Llama, Gemma, DeepSeek and most open models as of 2026, and ALiBi, a simple distance penalty. Some evidence even suggests decoder-only models can manage with no explicit encoding at all.

2,000 ft

Position can enter the network in one of three places, plus "nowhere":

  1. Add to the input (absolute): \(\mathbf{x}_i = \text{embed}(t_i) + \mathbf{p}_i\), with \(\mathbf{p}_i\) learned (GPT-2, BERT) or fixed sinusoids (2017 transformer).
  2. Bias the scores (relative): \(s_{ij} = \mathbf{q}_i\cdot\mathbf{k}_j/\sqrt{d} + b(i - j)\) — learned per offset bucket (T5) or a fixed linear penalty (ALiBi).
  3. Rotate queries and keys (RoPE): \(\mathbf{q}_i \to R_i\mathbf{q}_i\), \(\mathbf{k}_j \to R_j\mathbf{k}_j\), so \(\mathbf{q}_i^\top R_i^\top R_j \mathbf{k}_j = \mathbf{q}_i^\top R_{j-i}\mathbf{k}_j\) depends only on the offset.
  4. Nothing (NoPE): the causal mask alone leaks enough order for a decoder to infer position.

Where position enters the attention computation
Where position enters the attention computation. token embeddings, + position vector (learned / sinusoidal), Q, K projections, rotate q and k by position (RoPE), scores q·k/√d, + b(i−j) (T5 bias / ALiBi), softmax → weights, absolute, rotary, relative biasWhere position enters the attention computation. token embeddings, + position vector (learned / sinusoidal), Q, K projections, rotate q and k by position (RoPE), scores q·k/√d, + b(i−j) (T5 bias / ALiBi), softmax → weights, absolute, rotary, relative bias

Ground level

Why position must be injected

Without positional information, the output at a position depends on its own token and the set of other tokens, not their order. In a causal decoder the mask breaks the symmetry slightly — position \(i\) sees exactly \(i\) tokens — but that is a weak signal. Language needs much more: word order, which adjective modifies which noun, how far back a quote opened. So we need a scheme that makes "token X at position 5" distinguishable from "token X at position 50", and ideally makes the relation "3 positions before me" easy to express regardless of where in the sequence it happens.

Four requirements guide every design:

  1. Unique: different positions get distinguishable signals.
  2. Relative: the model should be able to express "the previous token" or "five tokens back" the same way at position 10 and position 10,000.
  3. Bounded and smooth: values must not blow up with position, and nearby positions should look similar.
  4. Cheap and cache-friendly: no extra cost per pair of tokens that can't be fused, and compatible with caching keys during generation.

Learned absolute embeddings

The simplest scheme: a second embedding table, one learned row per position, added to the token embedding. GPT-2 has a \(1024 \times 768\) position table; BERT has 512 rows. It satisfies requirement 1 trivially and works well within the trained length. Its fatal flaw is requirement 3: there is no row for position 1,025. The model cannot run past its training length at all, and positions near the end, seen less often during training, get less-trained rows.

Sinusoidal encodings

The 2017 transformer used a fixed function instead (§3.5). For position \(p\) and dimension pair \(i = 0, \dots, d/2 - 1\):

\[ \mathrm{PE}(p, 2i) = \sin(p\,\omega_i),\qquad \mathrm{PE}(p, 2i+1) = \cos(p\,\omega_i),\qquad \omega_i = 10000^{-2i/d}. \]

Each pair of dimensions is a clock hand turning at its own speed. The first pair turns once every \(2\pi \approx 6.3\) positions; the last, for \(d = 512\), once every \(2\pi \cdot 10000^{510/512} \approx 60{,}600\) positions. Read across the dimensions, the encoding is like a binary counter whose bits have been smoothed into sinusoids: fast dimensions distinguish neighbours, slow ones distinguish distant regions.

The authors chose sinusoids for one property: "for any fixed offset \(k\), \(PE_{pos+k}\) can be represented as a linear function of \(PE_{pos}\)" — each pair is rotated by a fixed angle, \(k\omega_i\) (proved in The maths). A layer could therefore learn to attend by relative offset. A corollary you can check: the dot product of two encodings depends only on their offset,

\[ \mathrm{PE}(p)\cdot\mathrm{PE}(q) = \sum_{i}\cos\big((p - q)\,\omega_i\big), \]

so \(\mathrm{PE}(10)\cdot\mathrm{PE}(13) = \mathrm{PE}(40)\cdot\mathrm{PE}(43)\) (both 5.5431 for \(d = 16\) in the Build it output).

They also hoped sinusoids "may allow the model to extrapolate to sequence lengths longer than the ones encountered during training" — and reported that learned embeddings "produced nearly identical results" (Table 3, row E). In practice sinusoidal models extrapolate poorly, because the encoding is added to the content: at an unseen position the input vectors themselves are in an unfamiliar region, and every layer downstream is affected.

Relative position in the scores

If what matters is the offset \(i - j\), why encode absolute positions at all? Relative schemes put the offset straight into the attention score.

  • Shaw et al. (2018) add a learned vector for each clipped offset to the keys (and values) inside attention (arXiv:1803.02155).
  • T5 simplifies this to a learned scalar per offset bucket, added to the logit: "we use 32 embeddings for all of our models with ranges that increase in size logarithmically up to an offset of 128", shared across layers, different for each head (Raffel et al., arXiv:1910.10683). Nearby offsets get their own buckets; distant ones share coarse buckets.
  • Transformer-XL decomposes the score into content and position terms with sinusoidal relative encodings, so it can attend into a cached previous segment (arXiv:1901.02860).

These generalise better than absolute schemes, but a learned bias per offset means extra work on every \(n \times n\) score matrix, and it complicates fused attention kernels.

RoPE: rotate the queries and keys

Rotary position embedding (Su et al., RoFormer, arXiv:2104.09864) combines the strengths of both: it is applied to each vector absolutely — a function of that token's own position — yet the resulting attention score depends only on the relative offset.

Start in two dimensions. Rotate the query at position \(m\) by angle \(m\theta\) and the key at position \(n\) by angle \(n\theta\). A dot product between two vectors depends only on their lengths and the angle between them, and rotating both changes that angle by \((m - n)\theta\). So

\[ (R_{m\theta}\mathbf{q})\cdot(R_{n\theta}\mathbf{k}) = \mathbf{q}^\top R_{(n-m)\theta}\,\mathbf{k}, \]

which depends on \(m\) and \(n\) only through \(n - m\). Shift both tokens by 100 positions and the score is unchanged.

q at m=2k at n=4 q at m=12k at n=14 Offset 2 in both (θ = 6.75° per position): the arc between q and k is 45° each time.
RoPE in one 2-D pair. Queries and keys are rotated by their own positions; a dot product sees only the angle between them, which depends only on the offset n − m.

To use all \(d_h\) dimensions of a head, RoPE splits the query and key into \(d_h/2\) pairs and rotates pair \(i\) at its own frequency, using the same geometric ladder as the sinusoids:

\[ \theta_i = \text{base}^{-2i/d_h},\qquad i = 0, \dots, d_h/2 - 1,\qquad \text{base} = 10{,}000 \text{ (RoFormer)}. \]

Fast pairs resolve fine local order; slow pairs carry coarse position over long ranges. Properties that made it the default:

  • Relative by construction, as above, for any \(d_h\) (the Build it check gives the same score, −8.446152, at offsets (5, 2), (105, 102) and (1005, 1002)).
  • No parameters and norm-preserving: rotations don't change vector lengths, so they don't disturb the scale of the scores.
  • Applied to Q and K only, not to values or the residual stream: content stays position-free.
  • Cache-friendly: a key is rotated once, by its own position, when it is computed; cached keys never need updating.
  • Decay with distance: for fixed vectors, the score tends to shrink as the offset grows, because the sum of cosines at many frequencies dephases. With \(\mathbf{q} = \mathbf{k} = (1, \dots, 1)\) and \(d_h = 128\) the score falls from 128 at offset 0 to 97 at 4, 61 at 64, 26 at 1,024 (real output below). RoFormer presented this as a desirable inductive bias.

That last explanation has been questioned. Studying Gemma 7B, Barbero et al. found that the model uses RoPE's highest frequencies to build precise positional attention patterns (for example previous-token heads) and tends to put content in the lowest frequencies, which barely rotate over the context and so act almost like position-free channels; they argue decay is probably not the main reason RoPE works (Round and Round We Go!, arXiv:2410.06205).

Two RoPE layouts

The paper rotates adjacent pairs \((x_0, x_1), (x_2, x_3), \dots\). Many implementations (GPT-NeoX, Hugging Face Llama) instead pair dimension \(i\) with \(i + d_h/2\) ("rotate half"). The two are equivalent up to a fixed permutation of the projection weights, but mixing conventions between a checkpoint and the code that loads it silently ruins a model. If a port produces fluent nonsense, check this first.

The base frequency and long context

The base controls the slowest rotation. With \(d_h = 128\):

base fastest pair: positions per turn slowest pair: positions per turn pairs that never complete a turn within 8K within 128K
10,000 6.28 54,410 14 0
500,000 (Llama 3) 6.28 2,559,196 29 15

(Real output of the second snippet in Build it.) A pair that completes many turns within the context is ambiguous about absolute distance — its angle repeats. Raising the base slows the low frequencies so they stay unambiguous over longer ranges. Meta raised it to 500,000 for Llama 3, noting that "this enables us to better support longer contexts", and in the final stage of pre-training extended the context from 8K to 128K tokens (Llama 3 paper).

Extending a trained model's context is mostly a matter of remapping positions or frequencies so that a longer context looks, to the model, like angles it has already seen:

  • Position Interpolation (PI) divides every position by the extension factor \(s = L'/L\), squeezing the new length into the trained range of angles. Chen et al. extended LLaMA models "to up to 32768 with minimal fine-tuning (within 1000 steps)" (arXiv:2306.15595). The cost: the fast frequencies are slowed too, so neighbouring tokens become harder to tell apart.
  • NTK-aware scaling changes the base instead, \(b' = b \cdot s^{d_h/(d_h - 2)}\), which leaves the fastest pairs almost untouched and stretches the slowest by the full factor \(s\).
  • YaRN interpolates different frequency bands by different amounts ("NTK-by-parts") and adds a small temperature to the attention logits; its authors report needing "10x less tokens and 2.5x less training steps than previous methods" (arXiv:2309.00071).

The full story — and why a model that accepts 128K tokens may not use them well — is on the long context page.

ALiBi: a linear penalty on distance

Attention with Linear Biases (Press, Smith, Lewis, arXiv:2108.12409) adds no position vectors anywhere. It subtracts a penalty proportional to distance from every score:

\[ s_{ij} = \frac{\mathbf{q}_i\cdot\mathbf{k}_j}{\sqrt{d_h}} - m_h\,(i - j),\qquad j \le i, \]

with a fixed, head-specific slope \(m_h\). For 8 heads the slopes are \(\tfrac12, \tfrac14, \dots, \tfrac1{256}\); in general a geometric sequence starting at \(2^{-8/h}\). Steep-slope heads are forced to look locally; shallow ones can see far. Because the penalty is a simple function defined for any distance, the model meets nothing unfamiliar at a longer length. The headline result: a 1.3B model trained on 1,024 tokens, evaluated on 2,048, matched the perplexity of a sinusoidal model trained on 2,048, while training about 11% faster and using about 11% less memory. BLOOM (176B) used ALiBi (arXiv:2211.05100).

The trade-off is a strong built-in recency bias: every head's view of distant tokens is penalised, so information far back must be very relevant to win. ALiBi extrapolates gracefully partly because it effectively ignores the far context; it does not make a model better at using it.

NoPE: no positional encoding at all

A causal decoder already has an asymmetry: position \(i\) attends over exactly \(i\) tokens. Haviv et al. showed that decoder-only language models with no positional encoding are competitive and "still learn positional information" (arXiv:2203.16634) — a head attending uniformly over its visible prefix, for example, produces outputs whose statistics depend on the prefix length. Kazemnejad et al. compared encodings on reasoning and arithmetic tasks and found NoPE generalised to longer lengths better than APE, T5's bias, ALiBi and RoPE (arXiv:2305.19466). NoPE is not standard on its own, but Meta describes "interleaved attention layers without positional embeddings" as "a key innovation in the Llama 4 architecture" (Meta AI, April 2025), and the result is a useful reminder that position is partly learned, not only supplied.

Comparison

Scheme Where Parameters Relative? Beyond training length Used in
Learned absolute added to input \(n_\text{max} \times d\) no impossible GPT-2, BERT
Sinusoidal added to input none expressible poor in practice 2017 transformer
T5 relative bias added to scores 32 per head yes moderate T5
RoPE rotates Q, K none yes (exact) poor without rescaling; good with PI/NTK/YaRN and a little fine-tuning PaLM, Llama, Gemma, DeepSeek
ALiBi added to scores none (fixed slopes) yes graceful, recency-biased BLOOM
NoPE nowhere none learned strong on some tasks research; interleaved with RoPE layers in Llama 4

History

Twenty years of telling a network where it is

2017 — Convolutional sequence models use learned absolute position embeddings; the transformer introduces sinusoidal encodings and reports learned ones work about as well (arXiv:1706.03762). 2018 — Shaw et al. introduce relative position representations; BERT and GPT use learned absolute tables. 2019 — Transformer-XL and T5 popularise relative schemes. 2021 — Jianlin Su develops RoPE in a series of blog posts and the RoFormer preprint; EleutherAI adopts it in GPT-NeoX and writes it up in Rotary Embeddings: A Relative Revolution; ALiBi appears the same year. 2022 — PaLM uses RoPE, as does LLaMA in 2023; NoPE results appear. 2023 — position interpolation, NTK-aware scaling (first shared online by the pseudonymous developer bloc97) and YaRN turn RoPE models into long-context models cheaply. 2024 — Llama 3 trains with base 500,000 and extends to 128K; analysis papers question why RoPE works.

First principles

Derive RoPE from one requirement. We want functions \(f_q(\mathbf{x}, m)\) and \(f_k(\mathbf{x}, n)\) that inject position into a query at position \(m\) and a key at position \(n\) such that their inner product depends only on the contents and the offset:

\[ \langle f_q(\mathbf{q}, m),\, f_k(\mathbf{k}, n)\rangle = g(\mathbf{q}, \mathbf{k}, m - n). \]

Work in 2-D and treat vectors as complex numbers, so the real inner product is \(\langle a, b\rangle = \operatorname{Re}(a\bar b)\). Try \(f(\mathbf{x}, m) = \mathbf{x}\,e^{i\phi(m)}\), a rotation by some angle \(\phi(m)\). Then

\[ \operatorname{Re}\big(q e^{i\phi(m)}\,\overline{k e^{i\phi(n)}}\big) = \operatorname{Re}\big(q\bar k\,e^{i(\phi(m) - \phi(n))}\big), \]

which depends on \(m, n\) only through \(\phi(m) - \phi(n)\). For that to be a function of \(m - n\) for all \(m, n\) we need \(\phi(m) - \phi(n) = \psi(m - n)\); setting \(n = 0\) gives \(\phi(m) = \psi(m) + \phi(0)\), and then \(\psi(a + b) = \psi(a) + \psi(b)\) — Cauchy's functional equation, whose continuous solutions are linear: \(\phi(m) = m\theta\) (taking \(\phi(0) = 0\)). So rotation by an angle linear in position is forced (RoFormer derives the general solution, with the magnitude unchanged, in §3.4). One frequency would wrap around every \(2\pi/\theta\) positions, so use many pairs at geometrically spaced frequencies — the same ladder as the sinusoids, for the same reason: to cover scales from one token to the whole context.

Why multiply rather than add? An additive encoding \(\mathbf{x} + \mathbf{p}_m\) produces scores \((\mathbf{q} + \mathbf{p}_m)\cdot(\mathbf{k} + \mathbf{p}_n)\) with four terms — content–content, content–position, position–content and position–position — of which only the last is purely relative; the cross terms entangle content with absolute position. Rotation keeps a single term whose dependence on position is exactly relative.

Why does extrapolation fail, and what fixes it? A network is only reliable on inputs like those it was trained on. For RoPE at a longer length, the fast pairs are fine — they have already cycled through every angle many times — but the slow pairs reach angles never seen in training. Interpolation (PI) and base changes (NTK, YaRN) make every pair's angles at the new length fall within the trained range, which is why they work with little or no fine-tuning. ALiBi side-steps the problem by having nothing that can be out of range; NoPE by having nothing at all.

The maths

Sinusoidal encoding. For \(p \in \{0, 1, \dots\}\), \(i \in \{0, \dots, d/2 - 1\}\), \(\omega_i = 10000^{-2i/d}\):

\[ \mathbf{PE}(p) = \big(\sin p\omega_0,\, \cos p\omega_0,\, \sin p\omega_1,\, \cos p\omega_1,\, \dots\big) \in \mathbb{R}^d . \]
Derivation: a fixed offset is a linear map (a rotation) of the sinusoidal encoding

Take one pair, \(\mathbf{u}(p) = (\sin p\omega, \cos p\omega)\). By the angle-addition formulas,

\[ \sin((p + k)\omega) = \sin p\omega\cos k\omega + \cos p\omega\sin k\omega,\qquad \cos((p + k)\omega) = \cos p\omega\cos k\omega - \sin p\omega\sin k\omega, \]

so

\[ \mathbf{u}(p + k) = \begin{pmatrix}\cos k\omega & \sin k\omega\\ -\sin k\omega & \cos k\omega\end{pmatrix}\mathbf{u}(p), \]

a rotation matrix that depends on \(k\) but not on \(p\). Stacking the pairs, \(\mathbf{PE}(p + k) = T_k\,\mathbf{PE}(p)\) with \(T_k\) block-diagonal. Then \(\mathbf{PE}(p)\cdot\mathbf{PE}(q) = \sum_i \big(\sin p\omega_i\sin q\omega_i + \cos p\omega_i\cos q\omega_i\big) = \sum_i \cos\big((p - q)\omega_i\big)\), a function of \(p - q\) alone.

RoPE. For a head of width \(d_h\) and position \(m\), define the block-diagonal rotation

\[ R_m = \operatorname{diag}\!\big(R(m\theta_0),\, R(m\theta_1),\, \dots,\, R(m\theta_{d_h/2-1})\big),\qquad R(\alpha) = \begin{pmatrix}\cos\alpha & -\sin\alpha\\ \sin\alpha & \cos\alpha\end{pmatrix},\qquad \theta_i = b^{-2i/d_h}. \]

Apply \(\tilde{\mathbf{q}}_m = R_m\mathbf{q}_m\) and \(\tilde{\mathbf{k}}_n = R_n\mathbf{k}_n\), then use \(\tilde{\mathbf{q}}_m\cdot\tilde{\mathbf{k}}_n\) as the score. Since \(R(\alpha)^\top = R(-\alpha)\) and \(R(\alpha)R(\beta) = R(\alpha + \beta)\),

\[ \tilde{\mathbf{q}}_m^\top\tilde{\mathbf{k}}_n = \mathbf{q}_m^\top R_m^\top R_n\,\mathbf{k}_n = \mathbf{q}_m^\top R_{n-m}\,\mathbf{k}_n . \]

Implementation never builds \(R_m\): for each pair \((x_{2i}, x_{2i+1})\) compute \((x_{2i}\cos m\theta_i - x_{2i+1}\sin m\theta_i,\; x_{2i}\sin m\theta_i + x_{2i+1}\cos m\theta_i)\) — \(O(d_h)\) per vector.

Long-term decay. With \(\mathbf{q} = \mathbf{k} = \mathbf{1}\), \(\tilde{\mathbf{q}}_m^\top\tilde{\mathbf{k}}_n = 2\sum_{i}\cos\big((n - m)\theta_i\big)\): the sum of \(d_h/2\) cosines at geometrically spread frequencies, which equals \(d_h\) at offset 0 and dephases as the offset grows. RoFormer bounds the general case with Abel summation (§3.4.3).

Position interpolation. Replace position \(m\) by \(m/s\), \(s = L'/L\): angles become \(m\theta_i/s\), all within the trained range for \(m < L'\).

NTK-aware base change. Replace \(b\) by \(b' = b \cdot s^{d_h/(d_h - 2)}\). The slowest frequency \(\theta_{d_h/2-1} = b^{-(d_h-2)/d_h}\) becomes \(b'^{-(d_h-2)/d_h} = \theta_{d_h/2-1}/s\) — scaled exactly like PI — while \(\theta_0 = 1\) is unchanged. (YaRN, Appendix A.2.)

ALiBi. For head \(h\) of \(H\): \(m_h = 2^{-8h/H}\), \(h = 1..H\), and \(S_{ij} \mathrel{+}= -m_h(i - j)\) for \(j \le i\). Equivalently, the attention weights are multiplied by \(e^{-m_h(i - j)}\) before renormalisation: an exponential prior on distance.

Build it

Sinusoidal encodings, RoPE and ALiBi in NumPy, each checked against the property claimed for it:

import numpy as np
np.set_printoptions(precision=3, suppress=True)
rng = np.random.default_rng(0)

def sinusoidal(n_pos, d, base=10000.0):
    pos = np.arange(n_pos)[:, None]                  # (n, 1)
    omega = base ** (-np.arange(0, d, 2) / d)        # (d/2,) frequencies, high -> low
    pe = np.zeros((n_pos, d))
    pe[:, 0::2], pe[:, 1::2] = np.sin(pos * omega), np.cos(pos * omega)
    return pe

def rope(x, pos, base=10000.0):
    """Rotate consecutive pairs (x0,x1), (x2,x3), ... of x (..., d) by angle pos * theta_i."""
    d = x.shape[-1]
    theta = base ** (-np.arange(0, d, 2) / d)
    ang = np.asarray(pos)[..., None] * theta         # (..., d/2)
    c, s = np.cos(ang), np.sin(ang)
    x1, x2 = x[..., 0::2], x[..., 1::2]
    out = np.empty_like(x)
    out[..., 0::2], out[..., 1::2] = x1 * c - x2 * s, x1 * s + x2 * c
    return out

def alibi_slopes(h):
    return 2.0 ** (-8.0 * np.arange(1, h + 1) / h)   # geometric: 2^-8/h, ..., 2^-8

# 1. Sinusoidal: the dot product of two encodings depends only on the offset
pe = sinusoidal(64, 16)
print("PE(10).PE(13) =", pe[10] @ pe[13], " PE(40).PE(43) =", pe[40] @ pe[43])

# 2. RoPE: q at position m, k at position n -> score depends only on m - n
q, k = rng.standard_normal(64), rng.standard_normal(64)
for m, n in ((5, 2), (105, 102), (1005, 1002)):
    print(f"m={m:4d} n={n:4d}  q_m.k_n = {rope(q, m) @ rope(k, n):.6f}")
print("norm preserved:", np.isclose(np.linalg.norm(rope(q, 777)), np.linalg.norm(q)))

# 3. ALiBi: per-head slopes and the bias added to the scores of head 0
print("ALiBi slopes, 8 heads:", alibi_slopes(8))
i, j = np.arange(5)[:, None], np.arange(5)[None, :]
print("head-0 bias (causal part):\n", np.where(j <= i, -alibi_slopes(8)[0] * (i - j) + 0.0, -np.inf))
PE(10).PE(13) = 5.543101061304943  PE(40).PE(43) = 5.543101061304943
m=   5 n=   2  q_m.k_n = -8.446152
m= 105 n= 102  q_m.k_n = -8.446152
m=1005 n=1002  q_m.k_n = -8.446152
norm preserved: True
ALiBi slopes, 8 heads: [0.5   0.25  0.125 0.062 0.031 0.016 0.008 0.004]
head-0 bias (causal part):
 [[ 0.  -inf -inf -inf -inf]
 [-0.5  0.  -inf -inf -inf]
 [-1.  -0.5  0.  -inf -inf]
 [-1.5 -1.  -0.5  0.  -inf]
 [-2.  -1.5 -1.  -0.5  0. ]]

RoPE frequencies, the effect of the base, and the decay with distance:

import numpy as np
d = 128                                              # head dimension -> 64 rotating pairs
for base in (10_000, 500_000):
    theta = base ** (-np.arange(0, d, 2) / d)        # radians per position, pair i
    wavelength = 2 * np.pi / theta                   # positions per full turn
    print(f"base {base:>7,}: fastest pair turns every {wavelength[0]:.2f} positions, "
          f"slowest every {wavelength[-1]:,.0f}; pairs that never complete a turn "
          f"within 8,192 tokens: {(wavelength > 8192).sum()}, within 131,072: {(wavelength > 131072).sum()}")

# Long-term decay of the score with distance, for q = k = (1, 1, ..., 1)
theta = 10_000 ** (-np.arange(0, d, 2) / d)
for dist in (0, 1, 4, 16, 64, 256, 1024, 4096):
    # for q = k = (1,1,...), q_m . k_n = 2 * sum_i cos((m - n) * theta_i)
    print(f"distance {dist:5d}: score {2 * np.cos(dist * theta).sum():8.2f}")
base  10,000: fastest pair turns every 6.28 positions, slowest every 54,410; pairs that never complete a turn within 8,192 tokens: 14, within 131,072: 0
base 500,000: fastest pair turns every 6.28 positions, slowest every 2,559,196; pairs that never complete a turn within 8,192 tokens: 29, within 131,072: 15
distance     0: score   128.00
distance     1: score   124.19
distance     4: score    97.17
distance    16: score    79.40
distance    64: score    61.04
distance   256: score    41.05
distance  1024: score    26.17
distance  4096: score    -6.77

In a real model RoPE is applied inside each attention layer, per head, right after the Q and K projections and before the scores. In PyTorch, with q, k of shape (B, h, T, d_h) and precomputed cos, sin of shape (T, d_h/2), the "rotate half" convention reads:

import torch

def apply_rope(x, cos, sin):                         # x: (B, h, T, d_h)
    x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
    cos, sin = torch.cat([cos, cos], -1), torch.cat([sin, sin], -1)
    return x * cos + torch.cat([-x2, x1], -1) * sin

Things to try

  • Verify the rotation property directly: build the \(2 \times 2\) matrix for \(k = 3\), \(\omega = 0.1\) and check sinusoidal(...)[p + 3] equals it applied to [p] for one pair.
  • Implement position interpolation by calling rope(q, m / s). For \(s = 4\), compare the score at offsets 1 and 2 with and without interpolation: how much harder do neighbours become to tell apart?
  • Implement the NTK-aware base \(b' = b\,s^{d/(d-2)}\) and print the new fastest and slowest wavelengths for \(s = 4\).
  • Add ALiBi to the attention function from the attention page and plot (or print) the weights of a uniform-content sequence for slopes \(\tfrac12\) and \(\tfrac1{256}\).
  • Replace the all-ones vectors in the decay experiment with random Gaussian \(\mathbf{q} = \mathbf{k}\) and average over 1,000 draws. Does the decay survive?

In practice

  • For a new decoder model, use RoPE (as of 2026 the near-universal choice), with a base chosen for the longest context you intend to support; large bases (500,000 to several million) are now common.
  • When porting or loading checkpoints, check the RoPE convention (interleaved vs rotate-half), the base, and any scaling configuration (rope_scaling in Hugging Face configs). A wrong base degrades quality subtly; a wrong layout destroys it.
  • To extend context of a RoPE model, use YaRN or NTK-style scaling plus a short fine-tune on long documents; plain PI works for modest factors. Evaluate on tasks that use the long context, not just perplexity.
  • Learned absolute embeddings remain fine for encoders with a fixed maximum length (classification, embeddings) — and for vision transformers, where 2-D variants of both learned and rotary schemes are used.

Check yourself

Why does a transformer need positional information at all, and why is a causal decoder a partial exception?

Self-attention is permutation-equivariant: without position, the output for a token depends only on the set of tokens, not their order. A causal mask makes position \(i\) see exactly \(i\) tokens, an asymmetry that lets a model infer some positional information (NoPE), but explicit encodings make order far easier to use.

What is the wavelength (positions per full turn) of the fastest and slowest sinusoidal dimension for d = 512?

Fastest: \(\omega_0 = 1\), wavelength \(2\pi \approx 6.28\). Slowest: \(\omega_{255} = 10000^{-510/512}\), wavelength \(2\pi \cdot 10000^{510/512} \approx 2\pi \times 9{,}647 \approx 60{,}600\).

Show that RoPE scores depend only on the offset.

\((R_m\mathbf{q})^\top(R_n\mathbf{k}) = \mathbf{q}^\top R_m^\top R_n\mathbf{k} = \mathbf{q}^\top R_{-m}R_n\mathbf{k} = \mathbf{q}^\top R_{n-m}\mathbf{k}\), using that rotation matrices satisfy \(R_\alpha^\top = R_{-\alpha}\) and \(R_\alpha R_\beta = R_{\alpha+\beta}\) (blockwise).

Why is RoPE applied to queries and keys but not to values?

Position only needs to influence where a token attends (the scores). Rotating values would mix positional phase into the content that gets written to the residual stream, and with relative rotations the result would depend on absolute position in a way the next layer would have to undo.

ALiBi with 16 heads: what are the first and last slopes?

\(m_h = 2^{-8h/16} = 2^{-h/2}\) for \(h = 1..16\): first \(2^{-0.5} \approx 0.707\), last \(2^{-8} = 1/256\).

A model trained with RoPE at 4K tokens is run at 16K with position interpolation. What is s, and what is the cost?

\(s = 16{,}384 / 4{,}096 = 4\); positions are divided by 4. All angles stay in the trained range, but the fastest frequencies now separate adjacent tokens by only a quarter of the angle they used to, so fine local order is harder to resolve; a short fine-tune lets the model adapt.

Hard: the additive sinusoidal scheme makes the score contain four terms. Which are relative, and why is that a problem?

\((\mathbf{x}_i + \mathbf{p}_i)^\top W_QW_K^\top(\mathbf{x}_j + \mathbf{p}_j)\) expands to content–content, content–position (\(\mathbf{x}_i, \mathbf{p}_j\)), position–content and position–position. Only the last can be made purely a function of \(i - j\) (and only if \(W_QW_K^\top\) respects the rotation structure); the cross terms couple content with absolute positions, so the model's behaviour can depend on where in the window a pattern occurs. RoPE's multiplicative form has no cross terms.

Hard: why do RoPE models fail beyond their training length, given that RoPE is relative?

Relative offsets beyond the training length were never seen: for low-frequency pairs, the angles \((n - m)\theta_i\) at large offsets lie outside the range encountered in training, so the score function the model learned is being evaluated out of distribution. High-frequency pairs are fine because they wrapped around many times in training. Interpolation and base changes map large offsets back into the seen range.

Go deeper

Papers

Videos and lectures

Articles and blog posts

Code

  • meta-llama/llama3 — precompute_freqs_cis and apply_rotary_emb: RoPE as complex multiplication.
  • jquesnelle/yarn — Reference implementations of PI, NTK-aware, NTK-by-parts and YaRN scaling.

Where this leads