Why position must be injected at all
Attention is permutation-invariant by construction. If you shuffle the tokens of a sentence and apply the same attention operation, each output is the corresponding shuffle of the original outputs - the model cannot tell "dog bites man" from "man bites dog". Every transformer therefore needs some signal that distinguishes position, and the way it is injected has real consequences for how well a model generalises beyond the lengths it was trained on.
The original transformer added fixed sinusoidal vectors to the embeddings: a set of sine and cosine waves at different frequencies, summed into each token vector. GPT-1 and GPT-2 replaced those with a learned embedding table, one vector per position up to a maximum length - simple, effective, but hard-capped: position 1,025 in a model trained to 1,024 has no vector at all.
Both approaches share a flaw. Position is added to the token vector before the first layer, then mixed with content through every subsequent computation. The model has to learn to disentangle "what this token is" from "where it sits", and that entanglement is what makes length extrapolation difficult.
The rotation trick
RoPE, introduced by Su et al. in 2021, takes a different route: it encodes position by rotating the query and key vectors, not by adding anything to them. Split a head's dimension into pairs (x0, x1), (x2, x3), and so on. For a token at position m, rotate pair i by angle m*theta_i, where theta_i = base^(-2i/d) and base is typically 10,000.
Rotation preserves vector length and preserves the angle between vectors. The crucial property is what happens to a dot product: if query q at position m is rotated by R(m) and key k at position n by R(n), then (R(m)q)*(R(n)k) = q^TR(n-m)k. The absolute positions cancel; only the difference survives. Attention scores depend on relative distance, exactly what a language model wants, and it emerges from the geometry rather than from learned weights.
In two dimensions this is easy to see. Rotating by alpha and beta and taking a dot product gives |q||k|cos(alpha - beta + phi), a function of the angle difference alone. RoPE applies that idea independently to 64 pairs in a 128-dimensional head, each pair rotating at its own frequency.
Frequencies and what they mean
With d_head = 128 and base 10,000, the 64 pairs span frequencies from theta0 = 1 (wavelength 2pi ~ 6.3 tokens) down to theta63 ~ 1.04e-4 (wavelength around 60,000 tokens). Low-index pairs spin fast and encode fine local order; high-index pairs turn slowly and encode coarse, long-range position.
That spread is the design. Fast dimensions let the model distinguish "the word immediately before" from "two words before"; slow dimensions let it represent "roughly 8,000 tokens ago". A model trained at 4K tokens never sees the slow dimensions complete even a fraction of a rotation, which is precisely why naive extrapolation to 128K fails: those dimensions are being evaluated far outside the range where they carry learned meaning.
Raising the base stretches every wavelength. Llama 3 uses 500,000 instead of 10,000, which multiplies the longest wavelength by about 50 and lets slow dimensions keep turning gradually across a 128K context instead of saturating. Some long-context models push the base to 1,000,000 or beyond for the same reason.
Implementation details that matter
- Rotate queries and keys only. Values carry content, not position; rotating them corrupts the output.
- Apply before the attention score computation, after the query and key projections.
- Compute cosines and sines in fp32 even when the model runs in bf16 - at position 100,000, bf16 angles lose enough precision to degrade long-context quality.
- Cache the cosine and sine tables per position to avoid recomputation on every layer; the table is tiny compared with the weights.
- Two layout conventions exist: rotate adjacent pairs (interleaved) or split the head dimension in half and rotate across the halves. Checkpoints are only compatible with the convention they were trained under - getting this wrong silently destroys the model.
- RoPE is applied per head after reshaping, so the same frequency table serves every head and every layer.
What the rotation looks like in code
Precompute the inverse frequencies once: freqs = 1.0 / (base ** (arange(0, d_head, 2) / d_head)). For a token at position m, the angle for pair i is m x freqs[i]. Cache cos(m x freqs) and sin(m x freqs) up to your maximum length, in fp32.
Then, for each pair (even, odd) in a head vector: out_even = even x cos - odd x sin, and out_odd = even x sin + odd x cos. That is a two-dimensional rotation applied 64 times for a 128-wide head. The half-split layout does the same thing with the first half of the vector as the "even" component and the second half as the "odd" component, which is friendlier to vectorised kernels - and incompatible with the interleaved layout unless you permute the weights first.
Two implementation notes save hours of debugging. Apply this to queries and keys after the projection and before the score computation, never to values. And keep the trigonometry in fp32: at position 100,000 the angle for the fastest pair is around 100,000 radians, and bf16's 8-bit mantissa cannot represent that with enough precision to keep neighbouring positions distinct.
Why it became the default
RoPE adds zero parameters, which matters when you are counting every billion. It requires no retraining of an embedding table when context grows, because there is no table. It degrades gracefully: attention scores between distant tokens naturally oscillate and decay, giving a soft locality bias without an explicit penalty term.
It also composes well. Because position is a rotation applied to q and k, you can rescale positions, change the base, or interpolate between frequencies without touching the model's weights - the entire family of context-extension methods depends on this. And it is compatible with efficient attention kernels, since the rotation can be fused into the projection at almost no cost.
The alternatives each give something up. ALiBi adds a fixed linear penalty proportional to distance; it extrapolates reasonably but cannot represent precise long-range order and has largely fallen out of favour. Learned absolute embeddings cannot extrapolate at all. NoPE, which omits position entirely and lets causal attention infer order from the mask, is an interesting research direction but not yet a production default.
Extending context with RoPE
Position interpolation (Chen et al., 2023) is the simplest method: if a model was trained at 4K and you want 16K, divide every position by four. The model then sees the same range of angles it was trained on, compressed into a longer sequence. It works with a short fine-tune, but compressing everything uniformly makes nearby tokens harder to distinguish.
NTK-aware scaling instead increases the base, stretching only the high-frequency dimensions in a way that preserves local resolution while extending the slow ones. YaRN combines per-dimension scaling with a temperature adjustment on the attention logits, and reports reaching 128K from a 4K base with roughly 400 steps of fine-tuning. Each method is a different answer to the same question: how do you keep fast dimensions precise while making slow dimensions reach further?
None of this creates information. A model fine-tuned to 128K still degrades on tasks that require combining facts spread across the whole window, and retrieval accuracy at 100K is materially worse than at 10K for most open models. Extension buys the ability to accept the tokens, not the ability to reason over them equally well.
Choosing a base and a scaling method
If you are training from scratch at a fixed context length, base 10,000 is fine and is what most 2K-8K models used. If you intend to serve at 32K or beyond, set a larger base from the start - 500,000 is the current common choice - and train at the target length for at least part of the run. Training at 4K and extending later always costs quality somewhere.
If you are extending an existing checkpoint, pick the method that matches your budget. Position interpolation is a one-line change and needs the least fine-tuning, but softens local resolution. NTK-aware scaling preserves local detail better and needs a little more tuning. YaRN is the most effective at aggressive ratios and needs a few hundred steps and a temperature adjustment. All three need evaluation at the target length, not just a successful load.
Record the base, the scaling factor and the fine-tuning length alongside the checkpoint. A model directory that says "128K context" without those three numbers is not reproducible, and the most common long-context bug in self-hosted deployments is a config file whose rope_theta does not match the weights.
Measuring long-context quality honestly
Needle-in-a-haystack tests - place a fact at various depths, ask for it - are necessary but weak, because they measure single-fact retrieval. A model can score near 100% on needles and still fail to summarise a 50-page contract or track a variable defined 30K tokens earlier. RULER and similar suites add multi-fact aggregation, variable tracking and ordering tasks, and scores on them fall off far more steeply.
The other reliable finding is positional: accuracy is highest when the relevant content is at the beginning or the end of the context and lowest in the middle. This is a property of attention and training data distribution, not of RoPE alone, and it means prompt structure is a real optimisation - put instructions at the end, and avoid burying the critical document at position 60% of a long prompt.
For anyone deploying long context, the honest test is your own task at your own lengths, with the same retrieval, chunking and prompt structure you will ship. Published context numbers describe the input socket, not the model's attention span.
How RoPE interacts with the rest of the stack
Keys are rotated before they are cached. That has a direct consequence for prefix caching: a cached key is only valid at the absolute position where it was computed, so a shared system prompt reused at a different offset must either be re-rotated or stored unrotated and rotated at read time. Serving engines handle this in different ways, and it is one reason prefix-cache hits can be slower than expected when the prefix is not aligned.
RoPE also composes with grouped-query attention without modification, because rotation is applied per head after projection and does not care how many heads share a key-value group. It composes with sliding-window attention too, but the combination changes behaviour: a window bounds which positions are visible while RoPE still encodes exact distance, so the model loses the ability to distinguish two occurrences of the same pattern that fall outside the window.
Finally, position and batching interact. Continuous batching packs sequences that start at different offsets; every sequence needs its own position counter, and a bug there produces output that looks plausible but subtly wrong - repeated phrases, dropped instructions, or answers that reference the wrong part of the prompt. When long-context output degrades after a serving upgrade, check the position bookkeeping before blaming the model.
Where RoPE causes trouble
- Base mismatch: loading a checkpoint with the wrong rope_theta produces fluent-looking but positionally confused output.
- Layout mismatch: interleaved versus half-split rotation silently corrupts attention when porting weights between frameworks.
- Precision loss: computing angles in bf16 breaks down past a few tens of thousands of tokens.
- Over-extrapolation: pushing far beyond the fine-tuned length without scaling yields repetition and drift.
- Fine-tuning at long length with too few long documents: the model learns to accept the window but not to use it.
- Assuming a larger base is always better - it changes the frequency profile the model was trained with and needs matching fine-tuning.
The practical summary
RoPE is a small, elegant idea with large downstream consequences: encode position as rotation, and relative distance falls out of the dot product for free. It costs no parameters, needs no position embedding table, and gives the model a smooth, continuous notion of distance that behaves sensibly beyond the training range - provided you scale it deliberately.
When you evaluate a long-context model, check three numbers before anything else: the base used for RoPE, the context length it was actually trained or fine-tuned at, and the scaling method applied. Those three explain most of the difference between a model that advertises 128K and one that works at 128K.