What Is Positional Encoding? RoPE and Word Order in LLMs
By LatestLLM Editorial · Published · Facts verified · 10 min read
Also called: position embedding, RoPE, rotary position embedding, sinusoidal encoding, word order in transformers
Before this: Attention, Embedding
In one line
Positional encoding is the signal that tells a transformer where each token sits in the text, because attention alone cannot tell “dog bites man” from “man bites dog”.
Positional encoding, simply and technically
In plain English
A language model reads all the words of a prompt at the same time, not one after another. That is fast, but it creates a problem: the part of the model that compares words, attention, has no built-in sense of order. Handed “dog”, “bites” and “man” in any order, it would treat them identically. Positional encoding is the extra signal that tells the model which word came first, which came second and how far apart any two words are.
Order is not a detail. “The dog bit the man” and “The man bit the dog” use the same words and mean opposite things. Every chatbot relies on some form of positional encoding to keep sentences, lists, code and conversations in the right order, and the method a model uses also decides how long a text it can handle.
Think of it like this: Positional encoding is like page numbers on a shuffled stack of pages. The words on each page stay the same, but the numbers let anyone put the pages back in order and see how far apart two pages are. Modern models do something cleverer than stamping a number on each page: they tilt every page by an angle that depends on its position, so two pages can tell how far apart they are just by comparing their tilts. The page-number picture breaks down there, because the model never sees a number at all.
Everyday example: Same words, different order
Two short sentences use exactly the same words.
Input:
The dog bit the man.
The man bit the dog.
Output:
Same six words, opposite meanings. Only their order differs.
What it shows: Without any positional signal, attention would see the same set of words twice and could not tell the biter from the bitten. With positions, “dog” in first place and “man” in last place produce a different pattern from “man” first and “dog” last, so the two sentences end up with different meanings inside the model.
Technically
Self-attention is permutation-equivariant: shuffling the input rows shuffles the output rows in the same way, so nothing in it depends on where a token is. Position has to be injected. The original transformer added fixed sinusoids to the embeddings, PE(pos, 2i) = sin(pos / 10000^(2i/d_model)) and a cosine for the odd dimensions, and found that learned position vectors gave nearly identical results. GPT-2 learns a table of 1,024 × 768 = 786,432 values, one vector per position, which is why its context window ends at 1,024 tokens.
Most current models use rotary position embedding (RoPE, Su et al. 2021). Nothing is added to the embeddings. Instead each query and key is rotated, one pair of dimensions at a time, by an angle pos × θ_i with θ_i = base^(−2i/d). The dot product between a query rotated to position m and a key rotated to position n then depends only on m − n. The base is a config value: 10,000 in the original design, 150,000 in gpt-oss, and 1,000,000 on Gemma 4's global layers (its local layers use 10,000). DeepSeek-V3 rotates only 64 of every 192 query and key numbers.
Technical example: RoPE depends only on distance
A toy query and key are rotated to three pairs of positions that are all 3 tokens apart, using the RoPE formula with base 10,000 and a head width of 4.
Code (python):
import math
def rope(v, pos, base=10000):
d, out = len(v), []
for i in range(d // 2):
a = pos * base ** (-2 * i / d)
x, y = v[2 * i], v[2 * i + 1]
out += [x * math.cos(a) - y * math.sin(a), x * math.sin(a) + y * math.cos(a)]
return out
dot = lambda a, b: sum(x * y for x, y in zip(a, b))
q = [1.0, 0.5, -0.3, 0.8]
k = [0.2, -1.0, 0.7, 0.4]
print("no rotation:", round(dot(q, k), 6))
for m, n in [(5, 2), (105, 102), (5005, 5002)]:
print(f"query at {m}, key at {n}:", round(dot(rope(q, m), rope(k, n)), 6))
print("query at 8, key at 2 (distance 6):", round(dot(rope(q, 8), rope(k, 2)), 6))
Output:
no rotation: -0.19
query at 5, key at 2: 0.231319
query at 105, key at 102: 0.231319
query at 5005, key at 5002: 0.231319
query at 8, key at 2 (distance 6): 0.088332
What it shows: The three scores for distance 3 are identical to six decimals even though the absolute positions differ by thousands, and a distance of 6 gives a different score. This is the relative-position property that makes RoPE attractive: attention sees how far apart two tokens are, not where the text happens to start.
Why order needs its own signal
In plain English: A sentence is more than its words: it is the words in a particular order. People get order for free because they read left to right. A transformer looks at all the tokens in parallel, so order has to be handed to it explicitly, or it would only know which words are present and not where they are.
Think of it like this: Without position it is like being told the ingredients of a recipe but not the order of the steps.
Technically:
Attention computes a weighted sum over keys and values. If the rows of the input are permuted, the queries, keys and values are permuted the same way and the sum is unchanged apart from the output order, so the layer is blind to position. The causal mask used by decoder models restricts which tokens can be seen but does not say how far away they are.
A positional scheme must make attention scores depend on position without hurting what the embeddings already carry. There are two routes: change the input vectors before attention (absolute encodings), or change how queries and keys are compared (relative encodings such as RoPE and ALiBi).
What is permutation-equivariant?
A function that gives the same answer, shuffled the same way, when its input is shuffled. Attention without positions behaves this way.
Absolute positions: sinusoids and learned tables
In plain English: The simplest idea is to give every position its own list of numbers and add it to the token's meaning. Position 1 always gets the same list, position 2 another. Early models made these lists with a fixed mathematical pattern, later ones simply let training discover them.
Technically:
Vaswani et al. (2017) used sine and cosine waves of geometrically spaced wavelengths, from 2π up to 10,000 × 2π, so each position has a unique fingerprint and any fixed offset corresponds to a linear transformation. They noted that learned embeddings performed nearly identically and chose sinusoids because they might extrapolate to longer sequences.
GPT-2 and BERT learn a table with one row per position. GPT-2's table has 1,024 rows of 768 values, 786,432 parameters, so a position beyond 1,024 has no row at all. Absolute schemes also make the model learn that “three tokens apart” looks different at positions 5 and 5,000, which relative schemes avoid.
Everyday example: A hotel numbering scheme
A hotel gives every room a number from 1 to 1,024 and no more.
What it shows: Guests can be sent to any of the 1,024 rooms but the hotel has nowhere to put guest 1,025. A learned position table works the same way: past its last row, the model has no position to give a token.
Rotary embeddings: position as a turn
In plain English: Rotary embeddings skip the numbering. Each token's query and key are turned by an amount that grows with the token's position, like the hands of many clocks that all tick at different speeds. When two tokens meet in attention, what matters is how far apart their hands are, and that depends only on the distance between the tokens.
Technically:
The head's d dimensions are grouped into d/2 pairs, each treated as a point in a plane and rotated by pos × θ_i. The frequencies θ_i = base^(−2i/d) fall geometrically: with a 64-wide head and base 10,000, pair 0 turns 1 radian per token while pair 31 turns about 0.000133 radians per token, a full turn every 47,117 tokens. With base 150,000 that slowest wavelength grows to about 649,000 tokens, and with base 1,000,000 to about 4.08 million.
Fast pairs distinguish neighbours; slow pairs separate distant tokens. RoPE needs no extra parameters and is applied to queries and keys only, never to values. DeepSeek-V3 applies it to a 64-dimension part of each head and leaves the other 128 free of position, and Gemma 4 rotates only a quarter of the frequency pairs on its global layers (p-RoPE).
Go deeper: details for practitioners
- The score q·k after rotation equals a sum over pairs of |q_i||k_i| cos(φ_i + (m − n)θ_i), where φ_i is the angle between the pair's two vectors, so the position enters only through (m − n)θ_i.
What is a frequency pair?
Two neighbouring dimensions of a query or key, treated as a point on a plane that RoPE rotates at one fixed speed.
What is the base?
The number that sets the spread of rotation speeds. A larger base slows the slow pairs further.
Stretching a model to longer texts
In plain English: A model trained on short texts tends to get confused by longer ones, because the turns it meets are beyond anything it saw in training. Engineers therefore adjust the position scheme afterwards so the same model can read far more text, and then train it briefly on long examples.
Technically:
YaRN (Peng et al. 2023) rescales RoPE frequencies, leaving fast pairs alone, stretching the slowest, and blending in between, and needs about 10 times fewer tokens and 2.5 times fewer steps than earlier extension methods. gpt-oss was extended from 4,096 to 131,072 positions with YaRN at factor 32; DeepSeek-V3 from 4,096 to 163,840 at factor 40, though its model card states 128K as the length it was tested at.
ALiBi (Press et al. 2021) takes a different route: it adds no position vectors and instead subtracts a penalty proportional to distance from each attention score, which lets models trained on short sequences extrapolate to longer ones. Gemma 4 combines a 10,000 base on local layers with a 1,000,000 base and rotation on only a quarter of the frequency pairs on global layers, to keep long-range comparison stable.
What is YaRN?
A method that rescales RoPE's rotation speeds so a model can handle contexts many times longer than it was originally trained on.
Common misconceptions
Myth: The model reads text left to right, so it knows the order automatically.
Reality: A transformer processes all positions in parallel. Order is only known because a positional encoding adds it to the computation.
Myth: Position numbers are simply added to the words as plain integers.
Reality: Models use vectors: fixed sinusoids, learned tables, or rotations of queries and keys. A raw integer such as 4,096 would swamp the embedding's own values.
Myth: A bigger context window only needs more memory.
Reality: The position scheme must also work at the longer length. That is why models need an extension method such as YaRN and extra training on long text.
Where you'll see this
- gpt-oss architecture: gpt-oss uses RoPE with a base of 150,000 and stretches it with YaRN from 4,096 to 131,072 tokens.
- Gemma 4 architecture: Gemma 4 uses standard RoPE on local layers and p-RoPE (a quarter of the frequency pairs, base 1,000,000) on global layers.
- DeepSeek-V3 architecture: DeepSeek-V3 rotates a 64-dimension decoupled key and extends context with YaRN at factor 40.
Key takeaways
- Attention by itself ignores order, so every transformer needs a positional signal to tell “dog bites man” from “man bites dog”.
- The original transformer added sinusoids and GPT-2 added learned vectors; most modern models instead rotate queries and keys with RoPE, so attention depends on the distance between tokens.
- RoPE's base sets how slowly the slowest dial turns: larger bases such as 150,000 or 1,000,000 suit longer contexts.
- A model's context length is tied to its position scheme, and methods such as YaRN stretch a trained model to longer texts without training from scratch.
Frequently asked questions
What is positional encoding in a transformer?
It is the information that tells a transformer where each token sits in the sequence, added or applied before or inside attention because attention alone ignores order.
What is RoPE?
Rotary position embedding rotates each query and key by an angle proportional to the token's position, so the attention score between two tokens depends on how far apart they are.
Why do some models have a base of 150,000 or 1,000,000?
A larger RoPE base slows the slowest rotations, so far-apart tokens stay distinguishable over longer contexts. gpt-oss uses 150,000 and Gemma 4's global layers use 1,000,000.
Can a model read text longer than it was trained on?
Only with help. Without adjustment, quality usually drops past the training length; methods such as YaRN rescale the rotations and a short round of long-context training restores it.
Do positional encodings add parameters?
Learned tables do: GPT-2's has 786,432. Sinusoids and RoPE are computed from a formula and add none.
Sources
Facts last verified November 23, 2026.
- Vaswani et al.: Attention Is All You Need (arXiv)
- Su et al.: RoFormer, Enhanced Transformer with Rotary Position Embedding (arXiv)
- Peng et al.: YaRN, Efficient Context Window Extension of Large Language Models (arXiv)
- Press et al.: Train Short, Test Long, ALiBi (arXiv)
- GPT-2 small config.json (Hugging Face)