Lesson 10.3 · 3 of 7 · 7 min read · Reviewed 24 Nov 2026
Positional encodings: sinusoidal and RoPE
By the end, you can
- Explain why attention needs position information at all.
- Compare sinusoidal, learned and rotary (RoPE) position schemes.
- Show that RoPE makes attention scores depend on the distance between tokens.
Look again at the attentionAttention: The mechanism that lets each token weigh every other token in the context when building its representation. recipe in lesson 10.1. Nothing in it mentions where a tokenToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id. sits. Scores come from dot products of queries and keys, and a dot product doesn’t care about order. “Dog bites man” and “man bites dog” would give every token the same set of scores. Order has to be put in on purpose. That is the job of a positional encoding.
Option 1: sinusoidal encodings
The original transformerTransformer: The neural network architecture behind modern LLMs, built from stacked attention and feed-forward layers. added a fixed pattern to each token’s embeddingEmbedding: A list of numbers (a vector) that represents the meaning of a piece of text, so similar meanings land close together. before the first layer. For position pos and dimension pair i of a width d:
PE(pos, 2i) = sin(pos / 10000^(2i/d))
PE(pos, 2i+1) = cos(pos / 10000^(2i/d))
Each pair of dimensions is a wave with its own speed. Early dimensions change quickly from one position to the next, later ones very slowly, a little like the hands of a clock. Together they give every position a distinct fingerprint, with no parameters to learn.
Option 2: learned absolute positions
BERT and GPT-2 instead learn one vector per position, up to a maximum such as 512 or 1,024, and add it to the embedding. Simple and effective, but the model has no vector at all for position 1,025.
Option 3: rotary position embedding (RoPE)
RoPE doesn’t add anything to the embedding. Inside each attention layer, it rotates the query and the key. Their numbers are split into pairs, and each pair is treated as an arrow on a plane. A token at position m has each pair turned by an angle m x theta, with a different theta for each pair, fast for some and slow for others.
The useful property: when you take the dot product of a query rotated by m and a key rotated by n, the result depends only on the difference m - n. Absolute position cancels out. Attention naturally sees “this key is 5 tokens back”.
A worked example
One pair, theta = 0.5 radians per position, query [1, 0], key [1, 0]. The score is the cosine of the angle between them after rotation.
| Query at | Key at | Offset | Angle between | Score |
|---|---|---|---|---|
| 5 | 3 | 2 | 1.0 rad | 0.54 |
| 12 | 10 | 2 | 1.0 rad | 0.54 |
| 7 | 7 | 0 | 0 | 1.00 |
| 7 | 3 | 4 | 2.0 rad | -0.42 |
Positions 5 and 3 score the same as 12 and 10. Real models use dozens of pairs with different speeds, so the combined score varies smoothly with distance instead of repeating.
How they compare
| Scheme | Where it acts | Relative distance | Seen in |
|---|---|---|---|
| Sinusoidal | Added to embeddings | Only indirectly | Original transformer |
| Learned absolute | Added to embeddings | No | BERT, GPT-2 |
| RoPE | Rotates q and k in every layer | Yes, built in | Llama, Mistral, Qwen and many open models |
Other schemes exist, such as ALiBi, which adds a penalty to scores that grows with distance.
Why builders hear about this
Context length claims depend on position handling. A model trained on 8,000-token sequences has never seen a rotation angle beyond that range. Techniques such as position interpolation and YaRN rescale RoPE angles so a model can be extended to longer contexts with some extra training. When you pick an open-weight modelOpen-weight model: A model whose trained weights are published so you can download, run and fine-tune it yourself., check the context length it was trained or tuned for, not just the largest number the config file allows.
Common mistakes
- Assuming attention knows word order by itself. It doesn’t; the encoding supplies it.
- ThinkingExtended thinking: A mode in which the model reasons step by step in thinking blocks before giving its final answer. RoPE adds a vector to the embedding. It rotates queries and keys inside attention.
- Trusting any context length in a config. Quality can fall well before the hard limit.
Key points
- Attention on its own ignores order: shuffle the tokens and each one gets the same weights, just in a different order.
- The original transformer added fixed sine and cosine waves of different speeds to each token's embedding.
- RoPE rotates each query and key by an angle set by its position, so their dot product depends only on how far apart they are.
- Models handle positions they were trained on best; longer contexts need models trained or adapted for them.
Rotate queries and keys with RoPE
Implement rotary position embedding and show that attention scores depend only on the distance between tokens.
You will have: A rope function and a table of scores for pairs of positions with equal and different offsets.
Steps
- Read thetas: one rotation speed per pair of dimensions, fast to slow.
- Fill in the rotation of each pair inside rope.
- Run it and compare the scores for (5, 3), (12, 10) and (105, 103).
- Check that rotating a vector leaves its length unchanged.
- Try a pair with a different offset and see the score change.
Done when
- Pairs with offset 2 all print the same score.
- The script prints that the same offset gives the same score.
- Rotation keeps length prints True.
Open in the Playground No API key needed.
Starter code (Python)
import math
# RoPE: split a vector into pairs and rotate pair i by angle pos * theta_i.
def thetas(dim, base=10000.0):
return [base ** (-2 * i / dim) for i in range(dim // 2)]
def rope(vec, pos, base=10000.0):
out = []
for i, th in enumerate(thetas(len(vec), base)):
x, y = vec[2 * i], vec[2 * i + 1]
a = pos * th
# TODO: rotate the pair (x, y) by angle a:
# x' = x cos a - y sin a, y' = x sin a + y cos a
out += [x, y]
return out
def score(q, k, m, n):
return sum(a * b for a, b in zip(rope(q, m), rope(k, n)))
q = [0.3, -1.2, 0.8, 0.5, -0.4, 0.9, 1.1, -0.2]
k = [1.0, 0.4, -0.6, 0.7, 0.2, -1.1, 0.5, 0.3]
print("query pos key pos offset score")
for m, n in [(5, 3), (12, 10), (105, 103), (7, 7), (7, 3)]:
print(f"{m:>9} {n:>8} {m - n:>7} {score(q, k, m, n):>7.3f}")
same = abs(score(q, k, 5, 3) - score(q, k, 105, 103)) < 1e-9
print("same offset, same score:", same)
print("rotation keeps length:", round(math.dist([0] * 8, rope(q, 50)), 6) == round(math.dist([0] * 8, q), 6))
Show a solution
import math
# RoPE: split a vector into pairs and rotate pair i by angle pos * theta_i.
def thetas(dim, base=10000.0):
return [base ** (-2 * i / dim) for i in range(dim // 2)]
def rope(vec, pos, base=10000.0):
out = []
for i, th in enumerate(thetas(len(vec), base)):
x, y = vec[2 * i], vec[2 * i + 1]
a = pos * th
out += [x * math.cos(a) - y * math.sin(a), x * math.sin(a) + y * math.cos(a)]
return out
def score(q, k, m, n):
return sum(a * b for a, b in zip(rope(q, m), rope(k, n)))
q = [0.3, -1.2, 0.8, 0.5, -0.4, 0.9, 1.1, -0.2]
k = [1.0, 0.4, -0.6, 0.7, 0.2, -1.1, 0.5, 0.3]
print("query pos key pos offset score")
for m, n in [(5, 3), (12, 10), (105, 103), (7, 7), (7, 3)]:
print(f"{m:>9} {n:>8} {m - n:>7} {score(q, k, m, n):>7.3f}")
same = abs(score(q, k, 5, 3) - score(q, k, 105, 103)) < 1e-9
print("same offset, same score:", same)
print("rotation keeps length:", round(math.dist([0] * 8, rope(q, 50)), 6) == round(math.dist([0] * 8, q), 6))