Skip to content
LearnAI
PART 2 · HOW LANGUAGE MODELS WORK/ Inside the Transformer

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.

⏱ 16 minIntermediate

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?”:

  1. Sinusoidal encodings (original Transformer, 2017): add a fixed pattern of sine and cosine waves to each embedding.
  2. Learned absolute embeddings (BERT, GPT-2): learn one vector per position, like a second embedding table.
  3. 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.
  4. 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.
ANALOGY· The hands of a clock

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 pp a vector the same size as the embedding (dmodeld_\text{model}). Dimension pairs hold a sine and a cosine of pp, each pair at a different frequency. The first pair oscillates once every 2π≈6.32\pi \approx 6.3 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 kk 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.
INTERACTIVESinusoidal positional encoding
Encoding table: rows = positions 0–99, columns = dimensions 0–63
dim 0 (fast)dim 63 (slow)
position, dim40, 6 (sin)frequency ω0.4217 rad/stepwavelength14.9 positionsvalue-0.917
Similarity of position 40 to every other position (dot product ÷ 32)
10.50-0.5025507599other position
sim(ref, ref ± 1)0.966sim(ref, ref ± 10)0.658

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.

Left: the encoding table for 100 positions × 64 dimensions (blue positive, orange negative). Hover for exact values and frequencies. Right: the dot product between one reference position and every other position. Move the reference and watch the curve keep its shape.

Things to notice:

  1. 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.
  2. 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.
  3. 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 p−qp - q 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: score−m⋅(i−j)\text{score} - m \cdot (i - j). Each head uses a different fixed slope mm, 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, (q0,q1),(q2,q3),…(q_0, q_1), (q_2, q_3), \ldots, and treat each pair as a little 2D arrow. For a token at position mm, rotate pair ii by the angle mθim\theta_i, where each pair has its own frequency θi\theta_i (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 mm with a key at position nn. The query was turned by mθm\theta and the key by nθn\theta, so the angle between them changed by (m−n)θ(m - n)\theta. 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 m−nm - n, never on mm or nn by themselves.

INTERACTIVERoPE rotation dial
qk

Dashed: vectors before rotation. Ochre arc: the angle between q and k, which sets the score.

q rotated by m·θ
100°
k rotated by n·θ
40°
relative offset m − n
3
score q·k
0.770
Score as a function of the offset m − n only
10-1-40-2002040offset m − n
this plane (normalized), dot = current offsetsum over 32 planes, d = 64, base 10,000

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.

One 2D plane of a query (orange) and key (blue). Move the positions m and n, or press 'Shift both' to move them together. The score q·k only changes when the offset m − n changes. Below: the score as a function of offset for this plane, and for all 32 planes of a 64-dim head combined.

Things to try:

  1. 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.
  2. Change only m. Now the offset changes and the score swings like a cosine.
  3. 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 pp and dimension pairs i=0,…,d/2−1i = 0, \ldots, d/2 - 1:

PE(p,2i)=sin⁡(p ωi),PE(p,2i+1)=cos⁡(p ωi),ωi=10000−2i/d.PE(p, 2i) = \sin(p\,\omega_i), \qquad PE(p, 2i+1) = \cos(p\,\omega_i), \qquad \omega_i = 10000^{-2i/d}.

The dot product of two encodings is

PE(p)⋅PE(q)=∑i[sin⁡pωisin⁡qωi+cos⁡pωicos⁡qωi]=∑icos⁡((p−q) ωi),PE(p)\cdot 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−qp - q only, which is what the demo’s similarity curve shows.

RoPE. For a query qq at position mm, rotate each pair (q2i,q2i+1)(q_{2i}, q_{2i+1}) by mθim\theta_i with θi=b−2i/d\theta_i = b^{-2i/d} (base bb, often 10410^4):

(q2i′q2i+1′)=(cos⁡mθi−sin⁡mθisin⁡mθicos⁡mθi)(q2iq2i+1).\begin{pmatrix} q'_{2i} \\ q'_{2i+1} \end{pmatrix} = \begin{pmatrix} \cos m\theta_i & -\sin m\theta_i \\ \sin m\theta_i & \cos m\theta_i \end{pmatrix} \begin{pmatrix} q_{2i} \\ q_{2i+1} \end{pmatrix}.

Write R(α)R(\alpha) for rotation by α\alpha. Rotations satisfy R(a)⊤R(b)=R(b−a)R(a)^\top R(b) = R(b - a), so for one pair

(R(mθ)q)⊤(R(nθ)k)=q⊤R((n−m)θ) k,\big(R(m\theta) q\big)^\top \big(R(n\theta) k\big) = q^\top R\big((n - m)\theta\big)\, k ,

which depends on mm and nn only through m−nm - n.

Worked example. One pair, q=(1,0)q = (1, 0), k=(1,0)k = (1, 0), θ=30°\theta = 30° per position.

query pos mmkey pos nnqq rotatedkk rotatedangle betweenscore q′⋅k′q' \cdot k'
2160°30°30°cos⁡30°=0.866\cos 30° = 0.866
54150°120°30°0.8660.866
98270°240°30°0.8660.866
52150°60°90°cos⁡90°=0\cos 90° = 0

Same offset, same score, regardless of absolute position. Note also that at θ=30°\theta = 30° an offset of 13 gives the same score as an offset of 1 (since 13×30°=390°≡30°13 \times 30° = 390° \equiv 30°): 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)
COMMON MISCONCEPTIONS
  • “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

0/5 answered
  1. Q1.Why does a Transformer need positional information at all?

  2. 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?

  3. Q3.In a sinusoidal or RoPE encoding, why use many different frequencies instead of one?

  4. Q4.A RoPE model trained on 4k-token contexts is given a 32k-token document. Why might quality collapse, and what helps?

  5. Q5.Which statement about ALiBi is correct?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.