What this is
How does a language model know word order?
Positional information is what an AI language model adds to each word to say where in the sentence it sits, because attention on its own treats the input as an unordered bag. Shuffle "dog bites man" into "man bites dog" and attention with no positions returns the same vectors, only reordered. There are three ways to add position back: a fixed code for each position, a learned table, or a rotation by an angle that grows with position (RoPE), which most current language models use. The scheme a language model uses decides how long a prompt it can read.
Why it matters: You need it the day length matters: a spec sheet claims 128K tokens and you wonder how far to trust it, or quality is fine on short prompts and drops sharply past some longer one, with nothing in the logs.
At a glance
Key takeaways
- Attention with no position information is blind to word order: shuffle the words and its outputs are shuffled the same way, so "dog bites man" pools to the same vector as "man bites dog".
- The original transformer adds a fixed code of sines and cosines to each word. GPT-2 and BERT learn a table of position vectors instead, and it has no row past its last position.
- Most current language models use RoPE, which turns each query and key by an angle that grows with position, so a score depends only on how far apart two words are. Because position lives in angles, a RoPE model can be stretched to longer prompts after training.
How it works, from scratch
Attention scores each pair of words by comparing their vectors, and the comparison comes out the same wherever the two words sit. So the order of the words has to be put in from outside: added to each word's vector, or built into the way attention compares them.
Opening
The problem: attention reads a bag, not a sentence
Think of the words as Scrabble tiles poured into a bag. The bag for "dog bites man" and the bag for "man bites dog" hold the same tiles, and anyone handed only the bag cannot tell a news story from a routine dog attack. Attention with no position information is handed only the bag.
Give each word an embedding of two numbers: dog = (1, 0), bites = (0, 1), man = (1, 1). The simplest way to turn a sentence into one vector is to average its words:
| sentence | sum of vectors | average |
|---|---|---|
| dog bites man | (1,0)+(0,1)+(1,1) = (2, 2) | (0.67, 0.67) |
| man bites dog | (1,1)+(0,1)+(1,0) = (2, 2) | (0.67, 0.67) |
The averages match because addition ignores order. Attention is an average too, a weighted one, and its weights come from dot products between words, which ignore order in the same way.
Figure 1 · Diagram
flowchart LR
A["'dog bites man'"] --> E1[Embed each token]
B["'man bites dog'"] --> E2[Embed each token]
E1 --> S1["Set {dog, bites, man}"]
E2 --> S2["Set {man, bites, dog}"]
S1 --> ATT[Attention with no positions]
S2 --> ATT
ATT --> SAME[Same vectors, only reordered:<br/>the meaning difference is lost]
A permutation is a reshuffle of an ordered list. Written as a matrix (a grid of numbers), a permutation matrix is all zeros except one 1 in each row, and multiplying by it reorders rows. Attention without positions is permutation-equivariant: shuffle its input and its output is shuffled the same way.
The formula and its symbols
Symbols
| Symbol | Meaning here | In the example |
|---|---|---|
| the sentence's token vectors, one row per word | rows dog (1,0), bites (0,1), man (1,1): a 3 × 2 grid | |
| a permutation matrix: reorders the rows of whatever it multiplies | swap rows 1 and 3 | |
| the same rows in the new order | man (1,1), bites (0,1), dog (1,0) | |
| one attention layer with no position information (here with = identity, so q = k = v = the word vector) | 3 × 2 in, 3 × 2 out | |
| both sides are exactly the same grid of numbers |
In words: "running attention on the shuffled sentence gives the same answer as running it on the original sentence and shuffling afterwards."
With the numbers: in "dog bites man", dog's query (1,0) scores the three keys (1,0), (0,1), (1,1) as 1, 0, 1; divided by √2 that is 0.707, 0, 0.707. Softmax gives weights 0.401, 0.198, 0.401, so dog's output is 0.401·(1,0) + 0.198·(0,1) + 0.401·(1,1) = (0.802, 0.599). In "man bites dog" dog sits in row 3, but it scores the same three keys in a different order, gets the same weights, and outputs the same (0.802, 0.599).
In Python
import math
# q = k = v = the word vector, no positions
def Attn(X):
out = []
for q in X:
scores = [sum(a * b for a, b in zip(q, k)) / math.sqrt(2) for k in X]
exps = [math.exp(s) for s in scores]
weights = [e / sum(exps) for e in exps]
out.append(tuple(round(sum(w * v[c] for w, v in zip(weights, X)), 3) for c in range(2)))
return out
# dog, bites, man
X = [(1, 0), (0, 1), (1, 1)]
# P swaps rows 1 and 3: man, bites, dog
PX = [X[2], X[1], X[0]]
Attn(X) # → [(0.802, 0.599), (0.599, 0.802), (0.752, 0.752)]
# the same rows, shuffled the same way
Attn(PX) # → [(0.752, 0.752), (0.599, 0.802), (0.802, 0.599)]
New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.
A larger layer, with 16 random numbers per word and random, untrained weights, behaves the same way:
Figure 2 · Chart
Without positions the two sentences are identical (similarity 1.0); sinusoidal codes and RoPE pull it just below 1, and a causal mask alone drops it to 0.52
In code: order_similarity computes the bars, with word_vector giving each word its random numbers. View source
Order carries much of what a sentence means: who did what to whom, what a "not" applies to, what a line of code does. So position has to be injected, and the oldest way is to add a code for each position to the word's vector.
Chapter 1
Sinusoidal codes (the original 2017 transformer)
A clock's second hand moves fast and tells nearby moments apart; its hour hand moves slowly and tells morning from evening. Read together, the hands give every moment of the day its own reading. Sinusoidal codes give each position a set of hands like these, each turning at its own speed, and add the reading to the word's embedding.
Each hand is stored as two numbers. Picture the tip of a hand on a circle of radius 1. The angle it has turned is measured in radians (a full turn is 2π ≈ 6.28 radians). The cosine of the angle is how far right the tip is, and the sine is how far up; both lie between −1 and +1, and both repeat every full turn. With 4 numbers per code there are two hands. The fast one turns 1 radian per position, the slow one 1/100 of a radian:
| position | sin(pos·1) | cos(pos·1) | sin(pos/100) | cos(pos/100) |
|---|---|---|---|---|
| 0 | 0.000 | 1.000 | 0.000 | 1.000 |
| 1 | 0.841 | 0.540 | 0.010 | 1.000 |
| 2 | 0.909 | −0.416 | 0.020 | 1.000 |
From position 1 to position 2 the fast pair changes a lot and the slow pair hardly at all. The slow pair is there to separate positions hundreds apart.
Figure 3 · Diagram
flowchart LR
T["token id"] --> E["embedding lookup<br/>(what the word means)"]
P["position 0,1,2..."] --> S["sin/cos at many frequencies<br/>(where the word is)"]
E --> ADD(("+"))
S --> ADD
ADD --> B["transformer blocks"]
In general, a code of d numbers has d/2 hands, and each turns more slowly than the one before:
The formula and its symbols
Symbols
| Symbol | Meaning here | In the example |
|---|---|---|
| the token's position, counting from 0 | 1 | |
| how many numbers each position code has | 4 | |
| which (sin, cos) pair, counting from 0 up to | 0 and 1 | |
| , | the two columns that pair fills: even column gets sine, odd gets cosine | pair 1 fills columns 2 and 3 |
| pair 's speed in radians per position (its frequency) | , | |
| 10,000 raised to a fraction; makes each pair slower than the last | ||
| , | how far up / right a point is after turning by that many radians | |
| the number in row , column of the code table |
In words: "for position pos, each pair of columns stores where a hand turning at that pair's speed points after pos steps: sine in the first column, cosine in the second."
With the numbers: d = 4, pos = 1. Pair 0 turns 1 radian: sin 1 = 0.841, cos 1 = 0.540. Pair 1 turns 1/100 radian: sin 0.01 = 0.010, cos 0.01 = 1.000. So position 1's code is (0.841, 0.540, 0.010, 1.000), the second row of the table above.
In Python
import math
d, pos = 4, 1
PE = []
# one (sin, cos) pair per i
for i in range(d // 2):
# ω_i: pair i's speed
omega_i = 1 / 10000 ** (2 * i / d)
# columns 2i and 2i+1
PE += [math.sin(pos * omega_i), math.cos(pos * omega_i)]
[f"{v:.3f}" for v in PE] # → ['0.841', '0.540', '0.010', '1.000']
Moving k positions on turns every hand by the same angle, k·ω_i, wherever it starts. So the dot product of two position codes depends only on how far apart the positions are.
In code: sinusoidal_encoding(n, d) builds the whole table, one row per position.
Figure 4 · Chart
Left columns flip colour every few positions and right columns change slowly, so every row is a unique fingerprint and neighbours look alike
The codes need no training and exist for every position. Because their similarity depends only on distance, a model can learn "look 3 tokens back" once and use it everywhere. The cost is that position is mixed into the word's vector itself.
Chapter 2
Learned absolute positions (GPT-2, BERT)
GPT-2 and BERT keep the addition but learn the position vectors instead of computing them. The model holds a table with one row per position, like numbered seats in a theatre, and the number of seats is fixed when the model is built. GPT-2's table has 1,024 rows of 768 numbers: 786,432 parameters, learned like any other weight. Position 5 reads row 5. Position 1,024, the 1,025th token, has no row.
Figure 5 · Diagram
flowchart LR
T["token id 318"] --> TE["token table<br/>(vocab × d)"]
P["position 5"] --> PE["position table<br/>(max_len × d)"]
TE --> ADD(("+"))
PE --> ADD
ADD --> B["transformer blocks"]
P2["position ≥ max_len"] -.-> X["no row: cannot be encoded"]
Each word's input is a sum of two rows:
The formula and its symbols
Symbols
| Symbol | Meaning here | In the example (GPT-2) |
|---|---|---|
| the token's row of the token table (what the word means) | 768 numbers | |
| row of the position table, learned during training (where it is) | 768 numbers; from 0 to 1,023 | |
| add the two lists number by number | ||
| the vector the first transformer block receives | 768 numbers |
In words: "the input vector is the word's meaning plus its seat number's learned vector."
With the numbers: with 2 dimensions, if = (0.5, −0.2) and = (0.1, 0.3), then = (0.6, 0.1). does not exist.
In Python
E_dog = [0.5, -0.2]
# a position table with rows 0 to 3
P = [[0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.1, 0.3]]
# x_3 = E_dog + P_3
[round(e + p, 2) for e, p in zip(E_dog, P[3])] # → [0.6, 0.1]
# no row 1024: it cannot be encoded
len(P) > 1024 # → False
In code: primer.ml.transformer.TinyGPT uses a table like this one. View source
A learned table is simple and works well up to its last row. Past it there is nothing to look up, and the table cannot grow after training.
Chapter 3
Rotary position embeddings, RoPE (Llama, Mistral, Qwen)
Both schemes so far add a code to the word's vector, one code per position. RoPE adds nothing to the word. It turns the word's query and key, the two vectors attention compares to score a pair of words, like clock hands, by an angle that grows with the word's position. Two people pointing at a clock face, one at 1 o'clock and one at 4, hold their arms 90° apart. Move them on to 8 and 11 o'clock and the angle is still 90°. In the same way, when a turned query meets a turned key, only the angle between them affects the score, and that angle depends on how far apart the two words are, not on where they sit.
Take a query and a key of two numbers each, q = k = (1, 0), so there is one pair, turning 1 radian per position. Put the query at position 3 and the key at position 7:
- q turns by 3 rad: (cos 3, sin 3) = (−0.990, 0.141)
- k turns by 7 rad: (cos 7, sin 7) = (0.754, 0.657)
- score = −0.990·0.754 + 0.141·0.657 = −0.654 = cos(4)
Move both 100 positions on, to 103 and 107, and the score is still cos(107 − 103) = cos 4 = −0.654. Only the distance between them counts.
Figure 6 · Diagram
flowchart LR X[Token vector at position m] --> Q[q = x W_q] X --> K[k = x W_k] X --> V[v = x W_v] Q --> RQ["Rotate each pair of q<br/>by m·θ_i"] K --> RK["Rotate each pair of k<br/>by m·θ_i"] RQ --> S["Score = q'·k'<br/>depends only on distance"] RK --> S S --> SM[Softmax] --> W[Weighted sum of V<br/>V is NOT rotated] V --> W
A rotation turns a point around the centre by an angle without changing its distance from the centre. For one pair it is a 2 × 2 grid times a column of two numbers, a matrix-vector multiply: each output number is one row of the grid multiplied entry by entry with the input and added up.
The formula and its symbols
Symbols
| Symbol | Meaning here | In the example |
|---|---|---|
| pair of a query or key vector, before rotating | (1, 0) | |
| the same pair after rotating | (−0.990, 0.141) | |
| the token's position | 3 | |
| which pair, from 0 to | 0 (the only pair when d = 2) | |
| pair 's turning speed in radians per position; means | ||
| the total angle turned | 3 radians | |
| the 2 × 2 grid | the rotation: row 1 gives the new first number, row 2 the new second |
In words: "new first number = cos(angle) × old first − sin(angle) × old second; new second number = sin(angle) × old first + cos(angle) × old second, where the angle is position times the pair's speed."
With the numbers: x = (1, 0) at m = 3, θ = 1: x′ = (cos 3 · 1 − sin 3 · 0, sin 3 · 1 + cos 3 · 0) = (−0.990, 0.141).
In Python
import math
def rotate(x, m, theta_i=1.0):
# the angle m θ_i
a = m * theta_i
# row 1 of the grid
return (math.cos(a) * x[0] - math.sin(a) * x[1],
# row 2 of the grid
math.sin(a) * x[0] + math.cos(a) * x[1])
[f"{v:.3f}" for v in rotate((1, 0), m=3)] # → ['-0.990', '0.141']
d, i = 2, 0
# θ_0 = 10000^(-2i/d)
10000 ** (-2 * i / d) # → 1.0
The score is a dot product (multiply matching numbers and add them up; it is large when the vectors point the same way), and turning both vectors by the same angle does not change it. So turning q by angle a and k by angle b gives the same score as leaving q alone and turning k by b − a:
The formula and its symbols
Symbols
| Symbol | Meaning here | In the example |
|---|---|---|
| , | a query and a key vector, before rotating | (1, 0) and (1, 0) |
| , | the query's and the key's positions | 3 and 7 |
| "rotate every pair by its speed times " | turn by 3 radians | |
| the rotation for the distance only | turn by 4 radians | |
| the dot product of and (same as ) |
In words: "the score between a query at m and a key at n equals the score you'd get by leaving the query alone and turning the key by the gap n − m."
With the numbers: left side (−0.990, 0.141) · (0.754, 0.657) = −0.654; right side (1, 0) · (cos 4, sin 4) = cos 4 = −0.654. Same number, and the same again at positions 103 and 107.
In Python
import math
# turn a pair by an angle (θ = 1, so the angle is the position)
def R(angle, x):
return (math.cos(angle) * x[0] - math.sin(angle) * x[1],
math.sin(angle) * x[0] + math.cos(angle) * x[1])
def dot(a, b): return sum(a_i * b_i for a_i, b_i in zip(a, b))
q = k = (1, 0)
# ⟨R_m q, R_n k⟩ with m = 3, n = 7
round(dot(R(3, q), R(7, k)), 3) # → -0.654
# ⟨q, R_(n-m) k⟩: only the distance
round(dot(q, R(7 - 3, k)), 3) # → -0.654
# 100 positions later, the same score
round(dot(R(103, q), R(107, k)), 3) # → -0.654
The same holds for vectors of 64 numbers, 32 pairs each turning at its own speed θ_i, starting anywhere in the text:
Figure 7 · Chart
The score curves for starting positions 0, 100 and 1,000 lie exactly on top of each other: only the distance matters
The pairs turn at speeds that fall from the first pair to the last, as the sinusoidal hands do:
Figure 8 · Chart
Pair 0 wraps a full turn about every 6 tokens while the last pairs barely turn across the whole range
In code: rope_frequencies gives each pair's speed θ_i, and apply_rope turns a vector or a whole sequence. View source
Language works in relative distances ("the word two back"), and RoPE builds them into every score. Turning a vector never changes its length, so the word's content is left as it was. And because position now lives in angles, the angles can be rescaled after training.
Chapter 4
Extending context after training
A RoPE model has only seen the angles produced by positions up to its training length. Past that length its slow pairs turn to angles it never met, and attention degrades. A ruler marked from 0 to 4,000 cannot measure something 32,000 long either. You can shrink the object 8× so it fits the ruler (position interpolation), or redraw the long-distance marks and keep the fine millimetre marks (NTK-aware scaling).
Say a model trained on 4,096 tokens has to read 32,768. Interpolation multiplies every position by 4096/32768 = 1/8, so position 32,000 is treated as 4,000: an angle the model has seen. Neighbours are now 1/8 of a position apart, which a short fine-tune teaches it to resolve.
Figure 9 · Diagram
flowchart LR
P["positions 0 ... 32k"] --> C{method}
C -->|interpolation| PI["pos × 4k/32k<br/>all hands slowed 8×"]
C -->|NTK-aware| NTK["raise the RoPE base<br/>slow hands slowed, fast hands kept"]
PI --> R["RoPE with angles inside<br/>the trained range"]
NTK --> R
R --> F["short fine-tune on long text"]
Position interpolation is one multiplication:
The formula and its symbols
Symbols
| Symbol | Meaning here | In the example |
|---|---|---|
| the real position in the long input | 32,000 | |
| the longest context seen in training | 4,096 | |
| the context we now want | 32,768 | |
| the position RoPE is actually given | 4,000 |
In words: "shrink every position by the ratio of old length to new length."
With the numbers: 32,000 × 4,096 / 32,768 = 32,000 / 8 = 4,000.
In Python
pos, L_train, L_new = 32_000, 4_096, 32_768
# pos' = pos · L_train / L_new
pos * L_train / L_new # → 4000.0
NTK-aware scaling leaves the positions alone and raises the base, the 10,000 in θ_i, instead:
The formula and its symbols
Symbols
| Symbol | Meaning here | In the example |
|---|---|---|
| the 10,000 inside | 10,000 | |
| how many times longer the new context is | 8 | |
| the head width | 128 | |
| raised to a power just above 1 | ||
| the new, larger base | ≈ 82,685 |
In words: "multiply the base by slightly more than the stretch factor."
With the numbers: the fastest pair keeps radian per position. The slowest pair goes from to : exactly 8× slower.
In Python
base, s, d = 10_000, 8, 128
# s^(d/(d-2)): just above 8
round(s ** (d / (d - 2)), 2) # → 8.27
# base' = base · s^(d/(d-2))
base_new = base * s ** (d / (d - 2))
round(base_new) # → 82685
# θ_i for the last pair, 2i = 126
slowest = lambda b: b ** (-126 / 128)
f"{slowest(base):.2e}", f"{slowest(base_new):.2e}" # → ('1.15e-04', '1.44e-05')
# exactly 8× slower
round(slowest(base) / slowest(base_new), 6) # → 8.0
In code: interpolate_positions and ntk_scaled_base. View source
YaRN refines NTK-aware scaling by treating each band of frequencies differently, and many long-context models use it. ALiBi takes another route: it adds no position vectors at all and subtracts a penalty proportional to distance from each attention score.
Figure 10 · Chart
Raw positions leave the trained angle band right after 4k and reach 8 times its top by 32k; interpolation and NTK scaling stay inside it
This is how a model trained on a few thousand tokens is stretched to 100k or more without pretraining it again from scratch.
Chapter 5
The causal mask leaks some order
Each scheme so far puts position in on purpose. A decoder, the kind of model that writes text one word at a time, also gets some order without one. Its causal mask lets each word see only itself and the words before it, so the word at position i sees i + 1 words. Even with no position encoding at all ("NoPE"), the model can partly infer where each word sits from how many words it sees. In bidirectional attention, where every word sees every other (as in BERT), there is no such signal, and attention is blind to order.
In code: encode_sentence with causal=True applies primer.ml.attention.causal_mask and gives the bar chart's "causal mask only" bar. View source
Test yourself
6 questions
Answer each one out loud or on paper before you open it.
Question 1Why does a transformer need positional information at all?Think it through, then reveal
Attention compares tokens by content only, so it's permutation-equivariant: shuffling the input just shuffles the output. Without positions, word order is invisible.
Question 2How does RoPE encode position, and what property makes it attractive?Think it through, then reveal
It rotates each pair of dimensions in q and k by an angle proportional to position. The q·k score then depends only on the relative distance, and rotation preserves vector length.
Question 3Compute a RoPE score by hand: 2 dimensions, θ = 1, q = k = (1, 0), query at 3, key at 7.Think it through, then reveal
cos(7 − 3) = cos 4 ≈ −0.654, and the same at positions 103 and 107.
Question 4Why do sinusoidal codes use many frequencies?Think it through, then reveal
Fast frequencies distinguish neighbours; slow ones distinguish distant positions. Together every position gets a unique, smoothly varying code, and a shift by k is the same rotation everywhere.
Question 5What goes wrong beyond the trained context length, and how do you fix it?Think it through, then reveal
The model meets position angles or indices it never saw, and attention degrades. Position interpolation, NTK-aware scaling or YaRN rescale positions or frequencies into the trained range, usually followed by a short fine-tune.
Question 6Learned absolute position embeddings: pro and con?Think it through, then reveal
They are simple and effective within the trained length, but they cannot represent any position beyond the table size.
Primary sources
The papers behind this lesson
Introduced the transformer and, in section 3.5, the sinusoidal position codes built here.
Read on rumblr →The paperIntroduced RoPE: rotate queries and keys so attention scores depend only on relative distance.
Read on rumblr →The paperShowed that scaling positions down plus a short fine-tune extends RoPE models to much longer contexts.
The paperRefined RoPE context extension by treating fast and slow frequencies differently.
The paperReplaced position vectors with a distance penalty on attention scores that extrapolates to longer inputs.
The paperResearcher's shelf
Further reading
- Vaswani et al., Attention Is All You Need (sinusoidal codes, section 3.5): https://arxiv.org/abs/1706.03762
- Su et al., RoFormer: Enhanced Transformer with Rotary Position Embedding (2021): https://arxiv.org/abs/2104.09864
- EleutherAI, Rotary Embeddings: A Relative Revolution: https://blog.eleuther.ai/rotary-embeddings/
- Chen et al., Extending Context Window of Large Language Models via Positional Interpolation (2023): https://arxiv.org/abs/2306.15595
- Peng et al., YaRN: Efficient Context Window Extension of Large Language Models (2023): https://arxiv.org/abs/2309.00071
- Press et al., Train Short, Test Long: Attention with Linear Biases (ALiBi) (2021): https://arxiv.org/abs/2108.12409
- Kazemnejad et al., The Impact of Positional Encoding on Length Generalization in Transformers (NoPE, 2023): https://arxiv.org/abs/2305.19466
About this lesson. This is the illustrated edition of a lesson from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it.