π§ Positional Embeddings: From Sinusoids to RoPE
Positional Embeddings: From Sinusoids to RoPE
Attention compares every token with every other token, and it does so with no idea where any of them sit. Shuffle the input and the outputs shuffle with it, and nothing else changes. So every transformer has to inject position somehow. The choice of how decides whether the model can read longer inputs than it was trained on, and it is one of the few places where open-weight architectures in 2026 still visibly differ.
This page follows the structure of Sebastian Raschka's Understanding Positional Embeddings in Modern LLMs (November 2026), which is the main reference here. Every number below is computed in this notebook, and each claim is checked against a second way of getting the same number.
- Why attention needs position at all, shown by shuffling a sentence
- Learned absolute positions (GPT-2)
- Fixed sinusoids (the original Transformer), and the rotation hiding inside them
- RoPE: rotate the query and key instead of adding anything
- RoPE in many dimensions, and why distant tokens score lower
- Split-half vs interleaved pairing: the same method, two memory layouts
- Beyond full RoPE: partial RoPE, NoPE, ALiBi, and stretching the context
The full forward pass these vectors feed into is worked through in Autoregressive Transformer: Encoder + Decoder.
helpers ready
1. Attention cannot see order
Take three tokens, dog bites man, give each a random embedding, and run one head of self-attention. Then run it again on man bites dog, which is the same three vectors in a different order.
If attention knew about order, the two outputs would be unrelated. In fact the second output is exactly the first one with its rows swapped. Every token attends to the same set of tokens with the same weights, wherever they sit. Formally, self-attention is permutation-equivariant: permuting the input rows permutes the output rows the same way, and nothing more.
==============================================================================
SHUFFLE THE SENTENCE, SHUFFLE THE OUTPUT - NOTHING ELSE
==============================================================================
Output row for each word, in each sentence
------------------------------------------------------------------------------
dog in 'dog bites man': [-0.6234 -0.1298 0.1956 0.1003 0.1049 -0.4179]
dog in 'man bites dog': [-0.6234 -0.1298 0.1956 0.1003 0.1049 -0.4179]
bites in 'dog bites man': [-0.1309 0.0637 0.1204 0.1433 -0.0003 -0.4998]
bites in 'man bites dog': [-0.1309 0.0637 0.1204 0.1433 -0.0003 -0.4998]
man in 'dog bites man': [-0.8407 0.3119 0.1651 -0.0152 -0.5475 -0.2644]
man in 'man bites dog': [-0.8407 0.3119 0.1651 -0.0152 -0.5475 -0.2644]
Checks
------------------------------------------------------------------------------
[MATCH] output(man bites dog) == rows of output(dog bites man), reordered
[MATCH] mean-pooled sentence vectors are identical
A classifier pooling these outputs could not tell who bit whom.
2. Learned absolute positions (GPT-2)
The simplest fix is to give every slot its own trainable vector and add it to the token embedding before the first layer:
$$h_m = E[x_m] + P[m]$$
$E$ is the token embedding table and $P$ is a second table with one row per position. GPT-2 trains $P$ along with everything else, with 1,024 rows.
Once the position rows are added, the shuffle test fails, which is what we want: dog in slot 0 and dog in slot 2 are now different vectors.
The cost is that the table ends at 1,024. Position 1,025 has no row. You cannot ask the model to read a longer input without adding rows that were never trained, so the context length is fixed when the model is built.
============================================================================== LEARNED POSITION TABLE ============================================================================== Same shuffle test, after adding position rows ------------------------------------------------------------------------------ [DIFFERENT] output(man bites dog) == reordered output(dog bites man) largest difference between the two pooled vectors: 0.4822 Size of the position table in the GPT-2 family (1,024 positions) ------------------------------------------------------------------------------ GPT-2 small d_model= 768 1024 x 768 = 786,432 parameters GPT-2 medium d_model= 1024 1024 x 1024 = 1,048,576 parameters GPT-2 large d_model= 1280 1024 x 1280 = 1,310,720 parameters GPT-2 XL d_model= 1600 1024 x 1600 = 1,638,400 parameters Every one of those rows is learned from data. Row 1,024 does not exist.
3. Fixed sinusoids, and the rotation hidden inside them
The original Transformer (Vaswani et al., 2017) uses a fixed table instead of a learned one. Feature pairs $(2i, 2i{+}1)$ get a sine and a cosine at frequency $\omega_i$:
$$P_{m,2i} = \sin(m\,\omega_i), \qquad P_{m,2i+1} = \cos(m\,\omega_i), \qquad \omega_i = 10000^{-2i/d}$$
The first pair turns fast and the last pair turns very slowly. Read the whole vector at once and it works like an odometer: a fast digit, then slower and slower ones, so every position up to a very large one gets a distinct pattern.
The property that matters most is not obvious from the formula. Each (sin, cos) pair is a point on a unit circle, and moving $k$ positions forward rotates that point by the angle $k\,\omega_i$:
$$\begin{pmatrix}\sin((m{+}k)\omega)\\ \cos((m{+}k)\omega)\end{pmatrix} = \begin{pmatrix}\cos k\omega & \sin k\omega\\ -\sin k\omega & \cos k\omega\end{pmatrix} \begin{pmatrix}\sin m\omega\\ \cos m\omega\end{pmatrix}$$
That matrix depends only on the offset $k$, not on $m$. So "three tokens later" is the same linear map everywhere in the sequence. RoPE builds directly on this.
============================================================================== SINUSOIDAL TABLE ============================================================================== Frequencies for d = 64 (radians per position), first and last few ------------------------------------------------------------------------------ [1. 0.7499 0.5623 0.4217] ... [0.0002 0.0002 0.0001] wavelength of the fastest pair: 6.28 positions wavelength of the slowest pair: 47,117 positions Moving k positions forward is a rotation that depends only on k ------------------------------------------------------------------------------ 27 (k, m, pair) combinations, worst error: 9.44e-16 [MATCH] P[m+k] pair == R(k*w) @ P[m] pair, for every combination
Watch the odometer turn. Each dial is one (sin, cos) pair of an 8-dimensional table, and the hand's angle is $m\,\omega_i$. The first hand spins a full turn roughly every six positions. The last one has barely moved after fifty.
4. RoPE: rotate the query and the key
Adding a position vector mixes where into what before attention ever runs, and the model has to learn to untangle them. Rotary Position Embedding (Su et al., 2021, the RoFormer paper) takes the rotation property above and applies it where it matters, inside the attention score.
Split the query and key into pairs. Rotate the pair of a query at position $m$ by $m\theta$, and the pair of a key at position $n$ by $n\theta$:
$$q'_m = R(m\theta)\,q, \qquad k'_n = R(n\theta)\,k, \qquad R(\alpha) = \begin{pmatrix}\cos\alpha & -\sin\alpha\\ \sin\alpha & \cos\alpha\end{pmatrix}$$
Rotations preserve length and compose by adding angles. So the score is
$$q'^{\top}_m k'_n = q^\top R(m\theta)^\top R(n\theta)\,k = q^\top R\big((n-m)\theta\big)\,k$$
Only the offset $n-m$ survives. Absolute positions cancel out of the attention score exactly. Nothing is added to the token embedding, the values are not rotated, and there are no extra parameters.
A worked 2-D example. The angle per position is $\theta = 30Β°$, the query is at position 4 and the key at position 1.
============================================================================== RoPE BY HAND IN TWO DIMENSIONS ============================================================================== Rotate the query by m*theta = 4*30 = 120 degrees ------------------------------------------------------------------------------ q0' = 0.9*cos(120) - 0.4*sin(120) = 0.9*(-0.5000) - 0.4*(+0.8660) = -0.7964 q1' = 0.9*sin(120) + 0.4*cos(120) = 0.9*(+0.8660) + 0.4*(-0.5000) = +0.5794 [MATCH] by-hand rotation == R(m*theta) @ q Rotate the key by n*theta = 1*30 = 30 degrees ------------------------------------------------------------------------------ k' = [-0.117 1.2026] Lengths do not change ------------------------------------------------------------------------------ |q| = 0.9849 |q'| = 0.9849 |k| = 1.2083 |k'| = 1.2083 The score, three ways ------------------------------------------------------------------------------ q'.k' = +0.790000 q . R((n-m)*theta) k (offset only) = +0.790000 both shifted by 10 positions = +0.790000 [MATCH] score depends only on n - m Compare: the same two vectors two positions apart instead of three ------------------------------------------------------------------------------ (m, n) = (4, 2): +1.129160 (m, n) = (9, 7): +1.129160
Here is that algebra in motion. The query (cyan) and key (pink) both step forward one position at a time and both turn by 30Β° per step. The angle between them does not change, so neither does their dot product. Then the key moves by itself, the offset changes, and the score changes with it.
5. RoPE in many dimensions, and why far-away tokens score lower
A real head has $d$ features, so it has $d/2$ pairs. Each pair rotates at its own rate, chosen exactly like the sinusoidal frequencies:
$$\theta_i = b^{-2i/d}, \qquad b = 10{,}000\ \text{(the usual base)}$$
Fast pairs tell neighbouring tokens apart. Slow pairs still distinguish tokens thousands of positions away. The relative-position property holds pair by pair, so it holds for the whole vector. The next cell checks it on random vectors with $d = 128$.
The RoFormer paper also points out a useful side effect. When the frequencies are spread like this, the score between two fixed vectors tends to decay as the distance grows. At offset 0 every pair contributes positively. Further apart, the pairs point in increasingly unrelated directions and partly cancel. The plot uses $q = k$ = all ones, which is the case the paper's bound is about.
============================================================================== RoPE WITH d = 128 ============================================================================== Score for offset n - m = 5, at many absolute positions ------------------------------------------------------------------------------ m = 0, n = 5: score = -6.7021265386 m = 1, n = 6: score = -6.7021265386 m = 37, n = 42: score = -6.7021265386 m = 500, n = 505: score = -6.7021265386 m = 4000, n = 4005: score = -6.7021265386 m = 100000, n = 100005: score = -6.7021265386 spread across positions: 1.77e-12 [MATCH] RoPE score depends only on the offset (d = 128) [MATCH] rotation preserves the norm All-ones q and k: score at selected offsets ------------------------------------------------------------------------------ offset 0: +128.000 offset 1: +124.187 offset 4: +97.172 offset 16: +79.403 offset 64: +61.040 offset 256: +41.050 offset 1024: +26.169 offset 2048: +15.268
6. Split-half vs interleaved: one method, two layouts
Which features count as "a pair" is a convention.
- Interleaved: pairs are $(0,1), (2,3), (4,5), \dots$, as in the RoFormer paper and in Meta's original Llama code, which treats each pair as a complex number.
- Split-half: feature $i$ is paired with $i + d/2$, as in the Hugging Face
rotate_halfimplementation, which is what the code above does.
They are the same transformation applied to permuted features. A model trained with one layout works with the other only if its query and key weight rows are permuted to match, which is exactly what checkpoint conversion scripts do. Get it wrong and nothing crashes; the model just quietly produces worse text.
============================================================================== INTERLEAVED == SPLIT-HALF, UP TO A FEATURE PERMUTATION ============================================================================== interleaved pairs: [(0, 1), (2, 3), (4, 5), (6, 7)] split-half pairs: [(0, 4), (1, 5), (2, 6), (3, 7)] [MATCH] rope_interleaved(x)[perm] == rope_split(x[perm]) consistent layout score: -6.702127 mismatched layout score: +1.159566 <- silently wrong
7. Beyond full RoPE
Full RoPE on every feature of every layer is still the most common choice among 2026 open-weight models, according to Raschka's survey. It is no longer the only one.
| Method | What it does | Seen in |
|---|---|---|
| Learned absolute | add a trained vector per slot | GPT-2 |
| Sinusoidal | add a fixed sin/cos vector per slot | original Transformer |
| RoPE | rotate $q$, $k$ by position, nothing added | Llama, Qwen, most 2026 models |
| Partial RoPE | rotate only some of each head's features, leave the rest position-free | e.g. MiniMax-M3 (64 of 128 dims) |
| NoPE | no positional signal; the causal mask alone implies order | some layers of SmolLM3 |
| Relative bias | learned scalar per distance bucket, added to scores | T5 |
| ALiBi | fixed penalty $-s_h\,(n-m)$ added to scores | BLOOM, MPT |
NoPE works at all because a causal mask is not symmetric: token 5 can see five earlier tokens and token 1 can see one, so the model can count. It is usually mixed with RoPE layers rather than used everywhere.
ALiBi skips vectors entirely. Head $h$ subtracts a linear penalty proportional to distance, with slopes $s_h = 2^{-8h/H}$, so some heads look locally and others far away.
============================================================================== ALiBi SLOPES AND BIAS ============================================================================== slopes for 8 heads: [0.5 0.25 0.125 0.0625 0.0312 0.0156 0.0078 0.0039] as fractions: 1/2, 1/4, 1/8, 1/16, 1/32, 1/64, 1/128, 1/256
Stretching the context: extrapolate or interpolate?
A RoPE model trained on 2,048 tokens has seen every angle that its fast pairs can take, because those wrap around many times. Its slow pairs never wrap. For pair $i = 50$ of a 128-dim head, the largest angle seen in training is about 90Β°. Run the same model at 8,192 tokens and that pair reaches angles it has never seen, all the way around the dial.
Position interpolation (Chen et al., 2023) divides every position by $L'/L$, here 4, so the longest new input maps back into the trained range. The cost is that neighbouring tokens are now four times closer in angle, so a short fine-tune is needed. Later methods such as NTK-aware scaling and YaRN scale the fast and slow pairs differently, to keep the fast pairs sharp.
============================================================================== WHICH ANGLES DOES A SLOW PAIR SEE? ============================================================================== theta_50 = 10000^(-100/128) = 7.499e-04 rad per position largest angle in training (m = 2048): 88.0 degrees extrapolated to m = 8192: 352.0 degrees <- unseen interpolated, m * 2048/8192: 88.0 degrees <- in range fastest pair wraps 326 times during training: every angle already seen
Summary
- Self-attention is permutation-equivariant. Without a position signal it computes the same thing for dog bites man and man bites dog.
- Learned absolute positions are simple and work, but the context length is fixed by the size of the table.
- Sinusoidal positions are fixed and unlimited, and hide a key property: moving $k$ positions forward is a rotation that depends only on $k$.
- RoPE applies that rotation to queries and keys instead of adding it to embeddings, so absolute position cancels and the attention score depends only on $n - m$. It is parameter-free, keeps vector lengths, and gives a gentle long-range decay.
- Interleaved and split-half RoPE are the same method; mixing them is a silent bug.
- Current models adjust RoPE rather than replace it: partial RoPE, NoPE layers, and position interpolation or YaRN to read past the trained length.
References
- Understanding Positional Embeddings in Modern LLMs
- RoFormer: Enhanced Transformer with Rotary Position Embedding
- Attention Is All You Need
- Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation
- Extending Context Window of Large Language Models via Positional Interpolation
- YaRN: Efficient Context Window Extension of Large Language Models
- The Impact of Positional Encoding on Length Generalization in Transformers
- Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer (T5)