2.7Positional encoding: sinusoids to RoPE
Attention can't tell "dog bites man" from "man bites dog" on its own. Here is how Transformers learn word order, from sine waves to rotating vectors.
Attention is order-blind
Take the two sentences “dog bites man” and “man bites dog”. Same three tokens, very different news. Now recall how self-attention works: each token’s query is compared with every other token’s key by a dot product, and the values are mixed according to those scores. Nothing in that computation mentions where a token is. If you shuffle the input tokens, the outputs get shuffled in exactly the same way and are otherwise unchanged. Mathematically, attention is permutation-equivariant: it treats its input as a set, not a sequence.
That was the price of dropping recurrence. An RNN reads tokens one at a time, so order is baked into the process. A Transformer reads them all at once, so it needs order put back in explicitly. That is the job of positional encodingPositional encodingInformation added to token representations so the model knows word order. Examples: sinusoidal, learned, RoPE..
There have been four main answers to “how do we tell the model about position?”:
- Sinusoidal encodings (original Transformer, 2017): add a fixed pattern of sine and cosine waves to each embedding.
- Learned absolute embeddings (BERT, GPT-2): learn one vector per position, like a second embedding table.
- Relative biases such as ALiBiALiBiAttention with Linear Biases: instead of adding position vectors, it subtracts a penalty proportional to the distance between query and key from each attention score, with a different slope per head.: skip vectors entirely and penalize attention scores by distance.
- Rotary embeddings, RoPERotary position embedding (RoPE)Encodes position by rotating query and key vectors by angles proportional to their position, so attention depends on relative distance. (2021 onward; Llama, Qwen, DeepSeek, Mistral and most current open models): rotate queries and keys by position.
How do you encode “what time is it” with a few numbers that change smoothly? A clock uses hands spinning at different speeds. The second hand spins fast, so it pins down fine differences but repeats every minute. The hour hand spins slowly, so it barely moves second to second but distinguishes morning from evening. Read together, the hands give a unique, smooth code for every moment of the day.
Each dimension pair of a positional encoding is a hand, and the position is the time. Low dimensions are fast hands; high dimensions are slow hands. RoPE goes one step further: it physically turns each query and key by its hand’s angle. Two arrows that were both turned by the same clock keep the same angle between them, no matter what time it is, which is why only the relative offset matters.
Sinusoidal encodings: a barcode of waves
The original Transformer gives position a vector the same size as the embedding (). Dimension pairs hold a sine and a cosine of , each pair at a different frequency. The first pair oscillates once every positions; frequencies then fall geometrically until the last pair takes tens of thousands of positions to complete one cycle. This vector is simply added to the token’s embedding before the first layer.
Why waves? Three nice properties:
- Unique and smooth. Every position gets a distinct pattern (like the clock), and neighboring positions get similar patterns.
- Bounded. Every value stays between −1 and 1, however long the sequence.
- Relative positions are easy to read. Shifting a sine wave by positions is a fixed rotation of its (sin, cos) pair, the same rotation wherever you start. So “the token 3 positions back” corresponds to a consistent linear transformation, which attention’s learned matrices can, in principle, exploit.
Hover the table for exact values; click a row (or use the slider) to make it the reference. Note how the similarity curve has the same shape wherever you put the reference: it depends on the distance between positions, not where they are.
Things to notice:
- Fast on the left, slow on the right. Dimension 0 flips sign every few rows; dimension 60 barely changes across all 100 positions. Hover to read the wavelength.
- Similarity peaks at zero distance. The dot product of a position with itself is the largest, and nearby positions are more similar than distant ones.
- The curve only depends on distance. Slide the reference position from 20 to 70: the curve slides along but keeps the same shape. The dot product of two sinusoidal encodings is a function of only. Keep that fact in mind; RoPE turns it into the whole design.
Learned absolute positions
The simplest alternative is to treat positions like vocabulary: keep a table with one learned vector per position (0, 1, 2, …, up to some maximum) and add the right row to each token’s embedding. GPT-2 does exactly this with 1,024 rows, and you’ll see it in the full Transformer walkthrough. The original Transformer paper reported that learned and sinusoidal encodings performed about the same.
The catch is the hard ceiling. A model with 1,024 learned position vectors has simply never seen position 1,025, and there is no vector to look up. Absolute encodings also make the model learn “the word at position 412” and “the word at position 413” separately, when what usually matters is “the word just before me”.
ALiBi: penalize distance directly
ALiBi (“Attention with Linear Biases”, 2021) throws position vectors out. Instead, before the softmax, it subtracts a penalty from each attention score proportional to how far apart the query and key are: . Each head uses a different fixed slope , so some heads focus locally and others see far. Because nothing is tied to absolute positions, ALiBi models were shown to handle somewhat longer inputs at test time than they were trained on. ALiBi was used in models like BLOOM and MPT, though RoPE has since become the more common choice.
RoPE: rotate queries and keys
Rotary Position Embedding (RoPE) takes the sinusoidal idea and moves it to exactly where it matters: inside the attention score. Instead of adding a position vector to the embedding, RoPE rotates each query and key vector by an angle that depends on its position.
Here is the recipe. Split the query vector into pairs of numbers, , and treat each pair as a little 2D arrow. For a token at position , rotate pair by the angle , where each pair has its own frequency (fast for early pairs, slow for later ones, just like the sinusoids). Do the same to the keys. Leave the values alone.
Now compare a query at position with a key at position . The query was turned by and the key by , so the angle between them changed by . A dot product only cares about lengths and the angle between two arrows, so the attention score depends on the content of the two tokens and on their offset , never on or by themselves.
Dashed: vectors before rotation. Ochre arc: the angle between q and k, which sets the score.
Press “Shift both +1” a few times: both arrows spin, but the angle between them, and so the score, never changes. Only m − n matters. A single plane repeats every 360°/θ positions; mixing many frequencies (blue) breaks that ambiguity.
Things to try:
- Shift both +1 several times. The arrows spin around the dial, yet the ochre angle between them and the score stay frozen. That is relative position encoding in one picture.
- Change only m. Now the offset changes and the score swings like a cosine.
- Look at the bottom chart. A single plane is periodic: at θ = 20° it repeats every 18 positions, so it can’t tell offset 0 from offset 18. The blue curve combines 32 planes with frequencies spread from fast to very slow (base 10,000). Together they peak at offset 0 and are much less ambiguous at long range, the same “many clock hands” trick as before.
Why did RoPE win? It encodes relative position (which is what language mostly needs) while being cheap: a couple of multiplications per pair, applied to queries and keys in every layer, with no extra parameters. It also doesn’t change the token vectors in the residual stream, so position information is injected precisely where tokens are compared, rather than mixed into everything.
Stretching the context: base, scaling and YaRN
RoPE’s frequencies are set by a constant called the base (10,000 in the original paper). The slowest pair completes one turn only after a very large number of positions. A model is trained up to some context length, say 4,096 tokens, and it has only ever seen rotation angles from that range. Feed it a 32,000-token document and the slow pairs reach angles it has never encountered, and quality typically falls apart.
Several tricks, collectively called RoPE scalingRoPE scaling (context extension)Techniques such as position interpolation, NTK-aware scaling and YaRN that adjust RoPE's rotation frequencies so a model trained on short contexts can handle longer ones, usually with some extra fine-tuning., adjust the frequencies so long inputs map back into familiar territory:
- Raise the base. A larger base makes every rotation slower, so long sequences use a smaller range of angles. Llama 3, for example, uses a base of 500,000 rather than 10,000.
- Position interpolation (2023) squeezes positions: position 8,000 is treated as if it were position 2,000, so all angles stay in the trained range. It works well after a short fine-tune, at some cost to fine-grained resolution.
- NTK-aware scaling (proposed in community posts in 2023) stretches the slow frequencies a lot and the fast ones barely, keeping local word order sharp.
- YaRN (2023) refines this per frequency band and adjusts the attention temperature; it is used, with variations, by several open models to extend context, typically with some additional training at long lengths.
The exact recipes differ between models and keep evolving, so treat these as families of ideas rather than one fixed algorithm. The common thread: because RoPE encodes position as angles, extending context becomes a question of how to rescale those angles. Part 4 returns to this in long context and FlashAttention.
MATH CORNER · optionalThe formulas, and RoPE's relative property worked out
Sinusoidal encoding. For position and dimension pairs :
The dot product of two encodings is
a function of only, which is what the demo’s similarity curve shows.
RoPE. For a query at position , rotate each pair by with (base , often ):
Write for rotation by . Rotations satisfy , so for one pair
which depends on and only through .
Worked example. One pair, , , per position.
| query pos | key pos | rotated | rotated | angle between | score |
|---|---|---|---|---|---|
| 2 | 1 | 60° | 30° | 30° | |
| 5 | 4 | 150° | 120° | 30° | |
| 9 | 8 | 270° | 240° | 30° | |
| 5 | 2 | 150° | 60° | 90° |
Same offset, same score, regardless of absolute position. Note also that at an offset of 13 gives the same score as an offset of 1 (since ): one frequency alone is ambiguous, which is why RoPE uses many.
In code
RoPE in a few lines of PyTorch, using the “split into pairs” convention (real implementations differ in how they pair dimensions, but the math is the same):
import torch
def rope(x, base=10000.0):
"""x: [batch, heads, seq, d_head] queries or keys. Returns rotated x."""
B, H, T, D = x.shape
i = torch.arange(D // 2, dtype=torch.float32)
theta = base ** (-2 * i / D) # one frequency per pair
pos = torch.arange(T, dtype=torch.float32)
ang = pos[:, None] * theta[None, :] # [T, D/2]: m * theta_i
cos, sin = ang.cos(), ang.sin()
x1, x2 = x[..., 0::2], x[..., 1::2] # the two halves of each pair
out = torch.empty_like(x)
out[..., 0::2] = x1 * cos - x2 * sin # 2D rotation of each pair
out[..., 1::2] = x1 * sin + x2 * cos
return out
# inside attention: q, k = rope(q), rope(k) (values are NOT rotated)
- “Positional encodings tell the model the meaning of word order.” They only provide a signal that distinguishes positions. Everything about how order matters (subjects before verbs, and so on) is learned by attention and MLP weights that read that signal.
- “RoPE adds a position vector to the embedding.” RoPE adds nothing. It rotates queries and keys inside each attention layer, and the values and residual stream are left untouched.
- “With RoPE a model works at any length.” RoPE encodes relative offsets, but models still degrade past the lengths they were trained on. Context extension needs rescaling (base changes, interpolation, YaRN-style methods) and usually some fine-tuning.
- “Sinusoidal encodings were replaced because they don’t work.” They work fine; the original paper found them comparable to learned embeddings. RoPE won because it builds in relative position at the attention score itself and extends to long contexts more gracefully.
Check your understanding
Q1.Why does a Transformer need positional information at all?
Q2.With RoPE, a query at position 10 and a key at position 7 produce score S. What score do the same two token vectors produce at positions 110 and 107?
Q3.In a sinusoidal or RoPE encoding, why use many different frequencies instead of one?
Q4.A RoPE model trained on 4k-token contexts is given a 32k-token document. Why might quality collapse, and what helps?
Q5.Which statement about ALiBi is correct?
Further reading
- paperRoFormer: Enhanced Transformer with Rotary Position Embedding — Su et al., the RoPE paper.
- paperTrain Short, Test Long: Attention with Linear Biases (ALiBi) — Press et al. on distance-based attention biases and length extrapolation.
- paperExtending Context Window of Large Language Models via Positional Interpolation — Chen et al. on squeezing positions into the trained range.
- paperYaRN: Efficient Context Window Extension of Large Language Models — Peng et al.; frequency-aware RoPE scaling.
- paperAttention Is All You Need — Section 3.5 introduces sinusoidal positional encoding.
- blogRotary Embeddings: A Relative Revolution (EleutherAI) — An accessible explanation with experiments.