Chapter 3 · Positional Encoding and Long Context¶
3.1 Why does a Transformer need positional encoding, and what are the limitations of absolute positional encodings? ★★¶
One-sentence answer
Because self-attention scores depend only on the content of the query and key, shuffling the input merely moves the outputs along with it (permutation equivariance), so the model by itself cannot tell "dog bites man" from "man bites dog". The original Transformer uses fixed sinusoidal encodings and BERT and GPT-2 use learned position vectors, both added to the input embeddings; their limitations are that relative distance is available only indirectly, content and position get mixed in the scores, and they generalize poorly beyond the training length.
I will address three aspects: why position information is needed, how the two absolute encodings work, and their limitations.
(1) Attention is permutation-equivariant, so position information must be injected explicitly.
In attention, the score of the query at position \(m\) against the key at position \(n\) is \(q_m^\top k_n\), which depends only on the content of the two tokens, not on where they sit in the sequence; the weighted sum of values is likewise order-independent, and the FFN and normalization layers process each token independently. So if the input tokens are shuffled, each token's output stays the same and simply moves with it; this property is called permutation equivariance. The meaning of language, however, depends heavily on order: "dog bites man" and "man bites dog" use the same words with opposite meanings. We therefore need some way to tell the model "this is position number such-and-such", which is the job of positional encoding (the basic computation of attention is covered in Chapter 1).
(2) Both classic absolute encodings add a position vector to the input embeddings.
- Sinusoidal encoding (Vaswani et al. 2017): a set of sine and cosine functions at different frequencies produces a fixed vector for each position, which is added to the token embedding. High-frequency dimensions change quickly with position and tell neighboring positions apart; low-frequency dimensions change slowly and tell distant positions apart, like the second hand and the hour hand of a clock. Thanks to the angle-addition formulas, the encoding of position \(pos+k\) can be written as a linear transformation of the encoding of position \(pos\) that depends only on \(k\), and the authors hoped the model could use this to learn relative position. It has no parameters and can in principle produce an encoding for any position.
- Learned encoding (BERT, GPT-2): a table of position embeddings is learned directly; position \(pos\) maps to row \(pos\) of the table, which is trained along with all other parameters and likewise added to the token embedding. It is more flexible and works about as well as sinusoidal encoding within the training length, but the table size is fixed before training (512 for BERT, 1024 for GPT-2).
(3) Limitations: relative distance is available only indirectly, content and position are mixed in the scores, and they generalize poorly to longer sequences.
Once \(x_m+p_m\) and \(x_n+p_n\) enter attention, the score expands into four terms: content-content, two content-position cross terms, and position-position (the formula is in "Going deeper"). What really matters in language is usually content and relative distance, but the model can only infer distance indirectly from two absolute positions; the cross terms link "a given word" with "a given absolute position", between which there is usually no meaningful connection, so they act more like noise the model has to learn to ignore. Moreover, after the \(W_Q\) and \(W_K\) projections, the sinusoidal property of "depending only on \(k\)" no longer holds exactly. The more serious problem is length generalization: learned encodings simply have no vector for positions beyond the table; sinusoidal encodings can compute encodings for new positions, but the model has never seen what they look like combined with content, so quality drops noticeably as soon as the input exceeds the training length. Later methods therefore turned to injecting relative position directly into the attention scores, and the most successful of them is RoPE (see 3.2).
In summary: the need for positional encoding comes from the permutation equivariance of attention; absolute encodings are simple, but they express relative distance only indirectly and generalize poorly in length, so they have been replaced by relative methods such as RoPE.
Going deeper: the sinusoidal formula and the four-term expansion of the score
(1) The sinusoidal encoding formula.
Here \(pos\) is the position, \(j\) indexes the dimension pairs (\(j = 0, \dots, d/2-1\)), \(d\) is the model dimension, \(x_{pos}\) is the token embedding, and \(h_{pos}\) is the input fed to the network. Each pair of dimensions uses one frequency \(1/10000^{2j/d}\): the smaller \(j\), the higher the frequency. Sine and cosine come in pairs because \(\sin(\omega(pos+k))\) and \(\cos(\omega(pos+k))\) can both be written as linear combinations of \(\sin(\omega\, pos)\) and \(\cos(\omega\, pos)\) with coefficients that depend only on the offset \(k\); that is, \(p_{pos+k}\) equals a rotation matrix depending only on \(k\) times \(p_{pos}\). RoPE applies exactly this idea of "rotation" directly to q and k.
(2) The score expansion for additive positional encodings.
Here \(W_Q\) and \(W_K\) are the query and key projection matrices. Only the last term depends purely on position; the middle two are cross terms between content and absolute position.
(3) Comparing the two absolute encodings.
| Sinusoidal encoding | Learned encoding | |
|---|---|---|
| Parameters | None | One vector per position |
| Quality within the training length | Good | About the same as sinusoidal, sometimes slightly better |
| Beyond the training length | Encodings can be computed, but quality drops noticeably | No vector exists, so it cannot be handled |
| Example models | Original Transformer | BERT, GPT-2 |
Follow-up questions
Follow-up 1: Why can BERT handle at most 512 tokens?
Because its positional encoding is a learned table with only 512 rows. Positions beyond 512 have no vector in the table, so the model cannot provide position information for them and the input must be truncated. Even within the table, later positions appear less often in the training data, so their embeddings are not trained as well.
Follow-up 2: Why does sinusoidal encoding use many frequencies?
To distinguish both near and far positions at once. With only high frequencies, neighboring positions are well separated, but at larger distances the angles repeat and far positions cannot be distinguished; with only low frequencies, far positions can be distinguished, but neighboring positions get nearly identical encodings. Combining many frequencies in a geometric series is like reading the second, minute and hour hands together: every position gets a unique encoding, and both near and far positions can be resolved.
Follow-up 3: Why can a decoder-only model without positional encoding still work?
Because the causal mask itself carries implicit position information. In causal attention, position \(i\) sees exactly \(i\) tokens, and the model can use this to infer where it is; for example, the output statistics of a head that attends uniformly over all previous tokens change with position. NoPE (Kazemnejad et al. 2023), which uses no positional encoding, can therefore train usable models, and in small-scale experiments it even showed fairly good length generalization; for large-scale LLMs, however, the mainstream choice is still RoPE, NoPE is rarely adopted throughout, and some models drop positional encoding only in a subset of layers (such as Llama 4).
Common mistakes
- Do not say that attention is permutation-invariant: The precise term is permutation-equivariant; shuffling the input moves the outputs along with it rather than leaving them unchanged.
- Do not say that sinusoidal encoding naturally extrapolates to any length: The formula can compute an encoding for any position, but quality drops noticeably beyond the training length.
- Do not say that the FFN or normalization layers provide order information: They process each token independently and are equally unaware of order.
3.2 How does RoPE work, and why does it represent relative position? ★★★¶
One-sentence answer
RoPE splits the dimensions of the query and key into pairs, treats each pair as a 2-D plane, and rotates it by an angle equal to "position × that pair's frequency"; since the dot product of two rotated vectors depends only on the difference of their rotation angles, the score between the query at position \(m\) and the key at position \(n\) depends only on the relative distance \(n-m\). It implements relative positional encoding through an absolute-position transformation, has no parameters, is applied in every layer, works naturally with the KV cache and FlashAttention, and makes it easy to extend the context by adjusting frequencies, which is why it is the standard choice for today's LLMs.
I will address four aspects: how RoPE rotates, why the dot product depends only on relative position, how the frequencies are chosen and what long-range decay means, and why it became the standard.
(1) RoPE treats every two dimensions of q and k as a plane and rotates it by an angle of "position × frequency".
RoPE (Su et al. 2021) starts by looking for a transformation of q and k such that the dot product after the transformation naturally depends only on relative position, and the answer is rotation. Concretely, the \(d\) dimensions of the head vector, after the \(W_Q\) and \(W_K\) projections, are split into \(d/2\) pairs; pair \(j\) rotates at frequency \(\theta_j\), the query at position \(m\) is rotated by \(m\theta_j\), and the key at position \(n\) by \(n\theta_j\). In the formula, \(R(\phi)\) is the matrix that rotates a 2-D vector counterclockwise by angle \(\phi\), \(R_m\) is the block-diagonal matrix made of the rotations of all pairs, \(d\) is the head dimension, and \(\tilde q_m\) and \(\tilde k_n\) are the rotated vectors, which attention uses for scoring. Three details are worth noting: only q and k are rotated, not v, because position only needs to affect "who attends to whom", while the value is the content being passed along; the rotation is applied again in every attention layer, so position information does not fade in deep layers; and the implementation does not build the matrix at all, using precomputed cos/sin tables in element-wise operations, so the extra cost is tiny.
(2) The transpose of a rotation is the reverse rotation, and rotations in the same plane add their angles, so the absolute positions cancel in the dot product and only the relative distance remains.
This derivation uses two properties of rotation matrices: a rotation matrix is orthogonal, and its transpose is the reverse rotation, \(R(\phi)^\top = R(-\phi)\); and consecutive rotations in the same plane simply add their angles, \(R(a)R(b) = R(a+b)\). Hence \(R_m^\top R_n = R((n-m)\theta)\) holds for every pair of dimensions, and the final result depends only on the content of q and k and the relative distance \(n-m\); the absolute positions \(m\) and \(n\) themselves disappear. This has two important consequences. Position is "multiplied in" through rotation rather than added, so the content-position cross terms of sinusoidal encoding do not exist, and since rotation does not change a vector's length, it does not distort the strength of the content itself. At the same time, each token only needs to be rotated once by its own absolute position, without knowing whom it will later be dotted with, yet the dot product automatically depends only on relative distance, so rotated keys can be stored directly in the KV cache and reused by later queries. Precisely speaking, RoPE applies an absolute-position transformation to each token, but inside the attention score it behaves as a relative positional encoding.
(3) The frequencies form a geometric series, so different dimensions handle distances at different scales, which also produces long-range decay.
RoPE keeps the geometric series of frequencies from sinusoidal encoding, where \(b\) is the base (originally 10000) and \(\lambda_j\) is the wavelength of pair \(j\), i.e. how many tokens the position must advance for that pair to complete exactly one turn. High-frequency dimensions (small \(j\)) rotate fast, so neighboring tokens already differ by a clear angle, which suits telling nearby order apart, but over longer distances they wrap around many times and the angles repeat; low-frequency dimensions (large \(j\)) rotate slowly, so their angle changes noticeably only over long distances, and they supply coarse long-range position information. Moreover, Su et al. (2021) showed that with this choice of frequencies, if the content of q and k is held fixed, an upper bound on the score decays as relative distance grows, which is called long-term decay: the score is a sum of \(d/2\) terms, each oscillating with distance at a different frequency; at short distances the terms are nearly in phase and add up, while at long distances their phases scatter and they cancel out. This gives the model a mild prior that "nearby tokens usually matter more", but it is only an upper bound in an idealized case, accompanied by oscillation, not a hard constraint, and the model can still attend far away by adjusting the content of q and k. The larger the base, the longer the wavelengths and the farther the low-frequency dimensions reach, so long-context models usually increase the base (for example, Llama 3 uses 500,000).
(4) RoPE became the standard because it combines relative position, zero overhead, compatibility with efficient implementations, and easy context extension.
- Relative position enters the score directly: the dot product itself encodes distance, with no extra bias term and no cross terms from addition.
- Zero parameters, and the score matrix is untouched: RoPE only modifies q and k, and the attention computation itself is unchanged, so efficient kernels such as FlashAttention can be used as is, and rotated keys can be cached directly; T5 bias and ALiBi, by contrast, add a bias element by element to the score matrix (see 3.3).
- Easy context extension: position information is entirely determined by "angle = position × frequency", so by rescaling positions or changing frequencies, a modest amount of continued training can extend the context from 4K to 128K or beyond (see 3.5), which learned encodings cannot do.
On top of these advantages, once PaLM and Llama adopted RoPE, almost every mainstream open model followed, and training and inference frameworks were heavily optimized around it, further consolidating its position.
In summary: the core of RoPE is multiplying position into q and k through rotation so that the dot product depends only on relative distance; it balances expressiveness, computational efficiency and extensibility, which is why it became the standard.
Comparing sinusoidal encoding and RoPE:
| Sinusoidal encoding | RoPE | |
|---|---|---|
| How position is injected | Added to the input embeddings | Rotates q and k in every layer |
| Where it acts | Only at the input | Attention in every layer |
| Dependence of the score on position | Absolute positions plus content-position cross terms | Relative distance only |
| Frequencies | Geometric series, base 10000 | The same geometric series, adjustable base |
| Parameters | None | None |
Going deeper: the complex-number view, concrete wavelengths, and common variants
(1) The complex-number view.
Treat pair \(j\) as a complex number \(q^{(j)}\); rotating by \(m\theta_j\) is multiplication by \(e^{\mathrm{i}m\theta_j}\). The 2-D dot product of two such numbers is:
Here \(\mathrm{Re}\) takes the real part and the overline denotes the complex conjugate. The result again depends only on \(m-n\).
(2) Concrete wavelengths.
With \(b = 10000\) and \(d = 128\), the shortest wavelength is about \(2\pi \approx 6\) tokens, and the longest is about \(2\pi \cdot 10000^{126/128} \approx 54{,}000\) tokens. This means that within a training length of 4K, a sizable share of the low-frequency dimensions never complete a single turn, which is the root of extrapolation failure (see 3.4).
(3) Implementation.
In practice it is usually written as \(\tilde q = q \odot \cos(m\theta) + \mathrm{rotate\_half}(q) \odot \sin(m\theta)\), where \(\odot\) is element-wise multiplication and \(\mathrm{rotate\_half}\) swaps the two halves of the vector and negates one of them. Implementations such as Llama's pair dimension \(i\) with dimension \(i+d/2\) rather than with the adjacent dimension; the two differ only by a fixed permutation of dimensions and are equivalent.
(4) Common variants.
| Variant | What it does | Examples |
|---|---|---|
| Larger base | Lowers all frequencies to reach farther distances | Llama 3 uses 500,000; Qwen3 uses 1,000,000 in its long-context stage |
| Different bases per layer type | Small base in local window layers, large base in global layers | Gemma 3: 10,000 for local layers, 1,000,000 for global layers |
| Partial rotation | Applies RoPE to only some dimensions, leaving the rest position-free | GPT-NeoX, GPT-J |
| Interleaving with NoPE layers | Some global layers use no positional encoding | Llama 4 |
| Multi-axis positions | Splits dimensions among time, height and width | M-RoPE in Qwen2-VL |
Follow-up questions
Follow-up 1: Why does RoPE rotate only q and k, not v?
Because position only needs to affect "who attends to whom", i.e. the scores. Attention scores are determined by the dot product of q and k, so rotating q and k is enough to make the scores depend on relative position; the value is the content being passed along by the weighting, and rotating it would mix a position-dependent transformation into the output, corrupting the content representation without helping to represent relative position.
Follow-up 2: Is RoPE an absolute or a relative positional encoding?
It applies an absolute-position transformation to each token, but behaves as a relative positional encoding in the scores. Each token is rotated only by its own absolute position, so in implementation it is absolute; the dot product depends only on \(n-m\), so in effect it is relative. Note that when the low-frequency dimensions do not complete a full turn within the training length, angle and position correspond one to one, so the model can in fact read absolute position from them, which is one source of the extrapolation problem (see 3.4).
Follow-up 3: What does RoPE's base do, and why do long-context models increase it?
The base controls how fast all frequencies rotate overall; the larger the base, the slower the rotation and the farther the distances that can be distinguished. With a larger base, every pair except the highest-frequency one (\(\theta_0 = 1\), independent of the base) gets a lower frequency and a longer wavelength, so distant positions are less likely to produce repeated angles and the long-term decay is slower, which suits long contexts better. The cost is slightly lower resolution at short distances in the middle- and low-frequency dimensions; moreover, the base must match the one used in training, since changing it arbitrarily at inference breaks the position patterns the model has learned, so increasing the base usually goes together with continued training (see 3.5).
Common mistakes
- Do not say that RoPE adds a position vector to the input: It rotates q and k in the attention of every layer, multiplicatively.
- Do not say that RoPE also rotates the value: Only q and k are rotated.
- Do not describe long-term decay as a hard penalty like ALiBi's: It is only the decay of an upper bound on the score in an idealized case, and the model can still attend far away.
- Do not say that RoPE, being relative, naturally extrapolates to any length: Beyond the training length, the low-frequency dimensions meet unseen angles and quality collapses (see 3.4).
- Do not say that RoPE has learnable parameters: Its frequencies are fixed, and it has no parameters at all.
3.3 How do ALiBi and the T5 relative position bias work? ★¶
One-sentence answer
Neither adds a position vector to the input; instead, both add a scalar bias that depends only on relative distance directly to the attention scores: T5 learns, for each head, a set of biases indexed by distance buckets (fine nearby, merged logarithmically far away); ALiBi learns no parameters and directly subtracts a penalty proportional to distance, with a different slope for each head. ALiBi's perplexity stays stable when extrapolating, but in essence it pins attention to nearby tokens and struggles to really use distant information, so it was eventually replaced by RoPE with interpolation methods.
I will address three aspects: how the T5 relative position bias works, how ALiBi works, and why neither became mainstream.
(1) T5 relative position bias: each head adds a learned scalar to the score according to the bucket of the relative distance.
T5 (Raffel et al. 2019) learns a set of scalar biases \(b_h\) for each head \(h\); when the query at position \(m\) scores the key at position \(n\), it looks up which bucket the relative distance \(n-m\) falls into and adds that bucket's bias. In the formula, \(a_{mn}\) is the score before softmax and \(d_k\) is the key dimension. The buckets are fine nearby and coarse far away: small distances each get their own bucket, larger distances are merged at logarithmic intervals, and all distances beyond 128 share one bucket; T5 uses 32 buckets in total and shares these biases across all layers. The reason for this division is that exact distances nearby matter a great deal for syntax and local structure, while far away it is enough to know roughly "how far". It has very few parameters and is a pure relative encoding; but the bias is just a scalar, so position can only raise or lower attention overall and cannot interact with content in finer ways, and since far distances all land in the same bucket, the model cannot tell 200 from 2000.
(2) ALiBi: learns no parameters and directly subtracts a penalty proportional to distance from the score.
In ALiBi (Press et al. 2021), \(m-n\) is the distance between query and key, and \(\lambda_h\) is a fixed slope for head \(h\), chosen as a geometric series (\(1/2, 1/4, \dots, 1/256\) for 8 heads). Heads with steep slopes are penalized heavily and attend only very close by; heads with gentle slopes can look farther. ALiBi's selling point is extrapolation: the paper reports that a 1.3B model trained at length 1024 reaches, at length 2048, the perplexity of a sinusoidal model trained at length 2048. BLOOM and MPT both adopted ALiBi.
(3) Neither became mainstream: ALiBi's extrapolation comes from a hard-coded recency bias, and scalar biases have limited expressiveness.
ALiBi extrapolates because the linear penalty pushes the scores of distant tokens very low, so their attention weights are nearly zero and the model mainly uses nearby context, like a "soft sliding window". That is why perplexity does not blow up beyond the training length, but it does not mean the model really uses distant information, such as accurately retrieving a fact that appeared 50,000 tokens earlier; and this recency bias is hard-coded, so the model cannot learn its way around it. The problem with T5 bias is the limited expressiveness of a scalar bias, plus the coarse merging of far distances. In addition, both add a bias element by element to the \(n\times n\) score matrix, which early on required specific support in attention kernels, while RoPE only modifies q and k. Meanwhile, RoPE combined with interpolation methods performed better on tasks that truly require long-range retrieval, and so it became the mainstream choice.
In summary: T5 bias and ALiBi represent the idea of "adding a distance bias directly to the scores"; ALiBi is simple and its perplexity extrapolates stably, but its hard-coded recency bias makes it hard to use distant information, so it was eventually replaced by RoPE.
Going deeper: an overall comparison of positional encodings
(1) Comparing five positional encodings.
| Sinusoidal | Learned absolute | T5 bias | ALiBi | RoPE | |
|---|---|---|---|---|---|
| Type of position | Absolute | Absolute | Relative | Relative | Absolute transform, relative in the score |
| How it is injected | Added to input embeddings | Added to input embeddings | Scalar bias added to the scores | Linear distance penalty subtracted from the scores | Rotates q and k in every layer |
| Extra parameters | None | One vector per position | One scalar per bucket per head | None | None |
| Beyond the training length | Poor | Cannot be handled | Generalizes somewhat | Stable perplexity, but distant information is barely used | Poor as is; strong with PI, NTK or YaRN |
| Kernel requirements | None | None | Must support a score bias | Must support a score bias | None |
| Example models | Original Transformer | BERT, GPT-2 | T5 | BLOOM, MPT | Llama, Qwen, DeepSeek |
(2) How ALiBi's slopes are chosen.
For \(H\) heads, the slope of head \(h\) is \(2^{-8h/H}\) (\(h = 1, \dots, H\)). For \(H = 8\) this gives \(2^{-1}, 2^{-2}, \dots, 2^{-8}\). Different heads thus cover ranges from very close to fairly far. (Kernels such as FlashAttention now support ALiBi, so kernel support is no longer the main obstacle; the real limitation is its recency bias.)
(3) Where the idea came from.
The idea of "injecting relative position into the attention scores" goes back to Shaw et al. (2018), who learned a vector for each relative distance and added it to the key during scoring; T5 simplified this to one scalar per bucket, and ALiBi went further and removed all parameters.
Follow-up questions
Follow-up 1: Why are T5's buckets fine nearby and merged logarithmically far away?
Because the model needs much more precision for nearby distances than for distant ones. A difference of one or two words often determines a syntactic relation and must be distinguished exactly, whereas for content hundreds of tokens away the model only needs to know it is "far", and whether it is 300 or 400 hardly matters. Logarithmic merging keeps precision nearby, covers a large range with very few buckets, and lets far distances share parameters, which also gives some generalization to longer, unseen distances.
Follow-up 2: If ALiBi's perplexity does not blow up on long sequences, does that show it uses long context well?
No. Perplexity is dominated by tokens that depend only on local context, and ALiBi concentrates attention nearby, so its perplexity stays stable; but it often fails at tasks that require retrieving information precisely from far away. Long-context ability must be judged with downstream evaluations such as retrieval tasks (see 3.6).
Follow-up 3: What do ALiBi and sliding-window attention have in common?
Both make the model focus mainly on nearby tokens; ALiBi is a "soft" window and sliding-window attention a "hard" one. ALiBi uses a linear penalty to push distant weights smoothly toward zero, with each head's effective range set by its slope; a sliding window simply masks out scores outside the window. The difference is that sliding windows are usually paired with global layers to keep long-range retrieval (see Chapter 2), whereas every ALiBi layer carries the recency bias.
Common mistakes
- Do not equate ALiBi's perplexity extrapolation with strong long-context ability: It relies mainly on nearby context and struggles to use distant information precisely.
- Do not say that ALiBi's slopes are learned: The slopes are fixed in advance as a geometric series; ALiBi has no parameters.
- Do not say that T5's biases are learned separately in each layer: Each head has its own biases, but the set is shared across all layers.
3.4 Why does a model fail beyond its training length, and what is the difference between extrapolation and interpolation? ★★¶
One-sentence answer
Although RoPE is relative in theory, its low-frequency dimensions do not complete even one turn within the training length, so beyond it they produce rotation angles never seen in training; combined with unseen relative distances and attention dilution in longer sequences, the scores become unpredictable and perplexity shoots up. Extrapolation keeps counting positions upward and makes the model cope with unseen angles; interpolation compresses the longer range of positions back into the range seen in training, at the cost of lower resolution between neighboring positions, and usually needs a little continued training to adapt.
I will address three aspects: the causes of failure, the difference between extrapolation and interpolation, and what this means in practice.
(1) Failure has three causes: unseen rotation angles, unseen relative distances, and attention dilution.
- Low-frequency dimensions meet unseen angles: with training length \(L\), pair \(j\) only ever sees rotation angles in \([0, L\theta_j)\). High-frequency dimensions turn many times during training and see every angle; but low-frequency dimensions with wavelength \(\lambda_j > L\) never complete even one turn and see only one arc of the circle. For these dimensions, angle and position correspond one to one, so they are effectively encoding absolute position. Once the input exceeds \(L\), these dimensions produce angles never seen in training, the corresponding scores land in ranges the model does not know, and the errors grow layer by layer. This is the main reason RoPE, relative in theory, still fails to extrapolate in practice.
- Unseen relative distances: even setting angles aside, the model has never handled relative distances beyond \(L\) in training, so the patterns it learned for "how much to attend at what distance" do not cover them.
- Attention dilution: the longer the sequence, the more keys softmax must spread its weight over, so the distribution becomes flatter and its entropy grows; the model's learned ability to "focus on a few key tokens" at the training length is weakened, and the truly relevant tokens receive less weight.
(2) Extrapolation handles the longer positions directly, while interpolation compresses them back into the training range.
There are two ways to handle longer inputs. Direct extrapolation keeps counting positions upward and requires the model to handle unseen angles, and the analysis above shows that this does not work for RoPE. Position interpolation goes the other way: it compresses the longer range of positions proportionally back into the range seen in training; for example, when extending from 4K to 16K, position 16000 is rotated as if it were position 4000, so every angle falls into an interval the model knows. The cost of interpolation is that the angle difference between neighboring positions shrinks and local resolution drops, so a little continued training on long text is usually needed to adapt. Intuitively, extrapolation asks the model to "answer questions it has never seen", while interpolation only asks it to "look more finely within the range it has seen", which is much easier to adapt to; this is the starting point of every method in 3.5.
(3) Practical implications: perplexity not blowing up does not mean the model can really use a long context, and some architectures sidestep out-of-range positions altogether.
ALiBi and sliding-window models show that a model can keep perplexity low by relying only on nearby context while being completely unable to retrieve distant information, so long-context ability must be judged with downstream evaluations such as retrieval tasks (see 3.6). On the other hand, some architectures avoid out-of-range positions at the root: in a sliding-window layer, relative distance never exceeds the window size (see Chapter 2), and some models use no positional encoding at all in their global layers (such as Llama 4). For mainstream RoPE models, however, the standard practice is still to interpolate and then continue training on long text.
In summary: failure beyond the training length is rooted in out-of-distribution problems such as out-of-range angles in the low-frequency dimensions; interpolation turns this into a loss of resolution, which is much easier to adapt to than extrapolation.
Going deeper: a worked example, and why interpolation is easier
(1) Example: how many dimension pairs of Llama 2 go out of range.
Here \(m\) is the position and \(L\) the training length. Llama 2 has a training length of 4096, a base of 10000 and a head dimension of 128. Solving \(\lambda_j = 2\pi \cdot 10000^{2j/128} > 4096\) gives \(j \ge 46\), so the last 18 of the 64 pairs (\(j = 46, \dots, 63\)) do not complete a turn within 4K. These are exactly the dimensions that break first when extrapolating.
(2) The error bound of interpolation is much smaller than that of extrapolation.
Chen et al. (2023) analyzed theoretical upper bounds on the error of attention scores in the two cases: when extrapolating, unseen angles can push the scores arbitrarily far off; when interpolating, new positions fall between two seen positions and the scores vary smoothly, so the error bound is much smaller (by their estimate, at least about 600 times smaller). This is why interpolation needs only a little fine-tuning to adapt.
(3) Compensating for attention dilution.
To counter the flattening of attention on long sequences, a common approach is to scale up the attention logits slightly so the distribution becomes sharp again. YaRN's temperature (see 3.5) and the attention temperature scaling that Llama 4 applies at inference both aim to compensate for this.
Follow-up questions
Follow-up 1: Which RoPE dimensions are most likely to break when extrapolating?
The low-frequency ones. High-frequency dimensions turn many times within the training length and have seen every angle, so extrapolation brings them no new angles; low-frequency dimensions have wavelengths longer than the training length, have seen only an arc during training, and immediately meet new angles beyond it. The methods in 3.5 therefore focus on the low-frequency dimensions while leaving the high-frequency ones as untouched as possible.
Follow-up 2: Without any training, by how much can the context be extended directly?
By a limited factor, usually with some loss. NTK-aware scaling, Dynamic NTK and YaRN can all extend the context to several times the training length without fine-tuning; for example, Qwen3 uses YaRN at inference to extend its usable length from 32K by a further factor of about 4. The larger the factor, however, the more quality degrades, and extending reliably by a large factor still requires continued training on long text.
Follow-up 3: Why not simply pretrain on long sequences from scratch?
Because it is too expensive, and most data is short anyway. Attention compute grows quadratically with sequence length, so training at 128K from scratch is extremely costly; and since most documents are short, forcing them into long sequences does not teach the model to use long-range dependencies. The standard practice is therefore to complete the bulk of pretraining on short sequences and extend the context during mid-training (see Chapter 4 of the "LLM Training Pipeline" direction).
Common mistakes
- Do not say that RoPE, being a relative encoding, naturally extrapolates: Beyond the training length, the low-frequency dimensions meet angles they have never seen.
- Do not say that the high-frequency dimensions are the main cause of extrapolation failure: The high-frequency dimensions have seen every angle; the problem lies in the low-frequency ones.
- Do not say that interpolation needs no training and is lossless: Interpolation reduces local resolution and usually needs a little continued training to adapt.
- Do not use perplexity as the sole criterion for whether a model can use a long context: A model can keep perplexity low using only nearby context.
3.5 How do PI, NTK-aware scaling and YaRN extend the context? ★★¶
One-sentence answer
RoPE's rotation angle equals "position × frequency", so extending the context comes down to two operations: rescale positions or change frequencies. PI compresses all positions uniformly by a factor of \(s\), which is simple but loses local resolution in the high-frequency dimensions; NTK-aware scaling increases the base so the high-frequency dimensions barely change while the low-frequency ones are close to fully interpolated; YaRN treats each dimension according to how many turns it makes within the training length and adds an attention temperature to offset attention dilution, making it the best-performing and most widely used method today. These methods are usually combined with a small amount of continued training on long text.
I will address three aspects: how PI, NTK-aware scaling and YaRN each work. Training data and stage schedules for long context are covered in Chapter 4 of the "LLM Training Pipeline" direction. Below, let the original training length be \(L\), the target length \(L'\), and the extension factor \(s = L'/L\).
(1) PI: divide every position by \(s\) so the angles return to the training range, but compress all dimensions alike.
Position Interpolation (Chen et al. 2023) is the most direct: divide every position by \(s\), which is equivalent to dividing every frequency by \(s\). For example, when extending from 2K to 8K (\(s = 4\)), position 8000 is rotated as if it were position 2000, and every angle is squeezed back into the range seen in training. The paper extended LLaMA from 2K to 32K with no more than 1000 fine-tuning steps. However, PI compresses all dimensions uniformly, including the high-frequency ones that tell nearby order apart: the angle difference between neighboring tokens in pair \(j\) shrinks from \(\theta_j\) to \(\theta_j/s\), like squeezing 4 tokens into the space that used to hold 1, so local resolution drops. The larger \(s\) is, therefore, the greater the loss and the more the method depends on fine-tuning to adapt.
(2) NTK-aware scaling: change only the base, so the high-frequency dimensions barely move and the compression falls mainly on the low-frequency ones.
NTK-aware scaling (bloc97 2023, first proposed in the open-source community) targets exactly PI's loss of high-frequency information, and its intuition comes from an observation in NTK theory: if the input lacks high-frequency components, the network struggles to learn fine details. It simply replaces the base \(b\) with \(b'\), where \(d\) is the head dimension and \(\theta'_j\) is the new frequency. Checking the two ends: at \(j = 0\) (highest frequency) the factor is \(s^0 = 1\), completely unchanged; at \(j = d/2-1\) (lowest frequency) the factor is \(s^{-1}\), exactly PI's full interpolation; the dimensions in between transition smoothly, with lower frequencies compressed more. Its advantage is that even without fine-tuning it does noticeably better than PI (Dynamic NTK also sets \(s\) dynamically from the current length, so short inputs are completely unaffected). Its weakness is that the middle dimensions are not fully squeezed back into the training range, and some still extrapolate, so the nominal \(s\) is not the true usable extension factor; the YaRN paper also reports that after fine-tuning on long text, NTK-aware scaling actually does worse than PI. Raising the base and then continuing training (called ABF, adjusted base frequency, as in Code Llama and Llama 2 Long) follows the same idea.
(3) YaRN: per-dimension interpolation plus an attention temperature.
YaRN (Peng et al. 2023) makes the earlier ideas more precise and has two parts:
- Per-dimension treatment (NTK-by-parts): \(r_j\) is the number of turns pair \(j\) makes within the training length \(L\), and \(\lambda_j\) is its wavelength. Low-frequency dimensions that do not complete a turn (\(r_j < \alpha\)) are fully interpolated as in PI, so no unfamiliar angles appear; high-frequency dimensions that turn many times (\(r_j > \beta\)) are left untouched, preserving local resolution; dimensions in between transition linearly. For the Llama family, the recommended values are \(\alpha = 1\) and \(\beta = 32\).
- Attention temperature: the attention logits are divided by a temperature \(t\) satisfying the formula above, an empirical fit the authors obtained on Llama. It targets the attention dilution described in 3.4: as sequences get longer, softmax flattens, and scaling the logits up a little refocuses attention. In practice it only requires multiplying the cos/sin tables by a constant, with no change to the attention kernel.
In summary: the three methods evolve from "compress all dimensions together" to "compress only the dimensions that need it", and then compensate for attention dilution on long sequences.
Comparing the three methods:
| PI | NTK-aware | YaRN | |
|---|---|---|---|
| What it changes | Divides all positions by \(s\) | Increases the RoPE base | Per-dimension interpolation plus attention temperature |
| High-frequency dimensions | Compressed by \(s\) | Almost unchanged | Unchanged |
| Low-frequency dimensions | Compressed by \(s\) | Compressed by up to \(s\) | Compressed by \(s\) |
| Without fine-tuning | Poor | Reasonable (especially Dynamic NTK) | Good |
| After fine-tuning | Works (2K to 32K in the paper) | Worse than PI | Best, with few tokens needed |
| Main weakness | Loses local resolution | Middle dimensions partly extrapolate; the nominal factor overstates the real one | Two extra hyperparameters, \(\alpha\) and \(\beta\) |
Going deeper: where the NTK-aware formula comes from, and what specific models do
(1) Deriving the NTK-aware base.
The goal is to compress the lowest-frequency pair (\(j = d/2-1\)) by exactly a factor of \(s\) while leaving the highest frequency (\(j = 0\)) unchanged. The lowest frequency is \(b^{-(d-2)/d}\); setting its value under the new base to \(1/s\) of the original gives:
Since \(\theta_0 = b^0 = 1\) does not depend on the base, the highest frequency stays unchanged automatically, and the dimensions in between transition smoothly in an exponential fashion.
(2) What specific models do.
| Model | Approach | Key points |
|---|---|---|
| Code Llama (Rozière et al. 2023) | Larger base, then fine-tuning | Base raised from 10,000 to 1,000,000, trained on 16K sequences |
| Llama 2 Long (Xiong et al. 2023) | ABF | Base raised to 500,000, then continued training |
| Llama 3.1 (Dubey et al. 2024) | Frequency-dependent scaling | Original length 8192 and factor 8: dimensions with wavelengths shorter than 2048 are unchanged, those longer than 8192 have their frequency divided by 8, with a smooth transition in between; essentially NTK-by-parts without the temperature |
| DeepSeek-V3 (DeepSeek-AI 2024) | YaRN | Two stages, from 4K to 32K and then to 128K |
| Qwen3 (Yang et al. 2025) | Larger base, plus YaRN at inference | Base raised from 10,000 to 1,000,000 in the long-context stage; YaRN at inference extends the usable length by a further factor of about 4 |
(3) Reported efficiency.
YaRN reports that, compared with previous methods, it needs about 1/10 of the tokens and about 1/2.5 of the training steps to extend Llama 2 to 128K. (In addition, LongRoPE (Ding et al. 2024) uses search to determine a separate scaling factor for each dimension, extending the context further to about 2 million tokens.)
Follow-up questions
Follow-up 1: Given a model trained with a 4K context, how would you extend it to 128K?
Choose YaRN or a larger base for the positional encoding, continue training on long text in stages, and finally verify with long-context evaluations. For the positional encoding, the extension factor is \(s = 32\), and one can use YaRN or raise the base to several hundred thousand or more (ABF); one can also extend in two steps as DeepSeek-V3 did, first to 32K and then to 128K. For training, use long documents that genuinely contain long-range dependencies, mix in a substantial share of high-quality short data, and continue training with a small learning rate (details in Chapter 4 of the "LLM Training Pipeline" direction). For evaluation, use retrieval-style benchmarks such as RULER and real long-document tasks, and check that short-context ability has not regressed (see 3.6).
Follow-up 2: Why does YaRN add a temperature?
To compensate for attention dilution on long sequences. As sequences get longer, softmax must spread its weight over more keys, the distribution becomes flatter, and the model struggles to focus on the key tokens. Dividing the logits by a temperature \(t\) below 1 is equivalent to scaling them up, which sharpens the distribution again. The larger \(s\) is, the more scaling is needed, so the temperature is adjusted with \(\ln s\).
Follow-up 3: Why does NTK-aware scaling's nominal extension factor differ from the factor that is really usable?
Because the middle-frequency dimensions are only partly compressed, and some of them still extrapolate. NTK-aware scaling only guarantees that the lowest-frequency dimension is compressed by a factor of \(s\); the middle dimensions are compressed by less than \(s\), and some of them still rotate into angles never seen in training at the new length. In practice, therefore, \(s\) often has to be set larger than the target factor to truly cover the target length. YaRN's per-dimension treatment exists precisely to solve this problem.
Common mistakes
- Do not say that PI is friendly to the high-frequency dimensions: PI compresses all dimensions uniformly, and the loss of local resolution in the high-frequency dimensions is the most pronounced.
- Do not say that NTK-aware scaling is always better than PI after fine-tuning: The YaRN paper reports that after fine-tuning, NTK-aware scaling actually does worse than PI.
- Do not say that YaRN's temperature requires modifying the attention kernel: It only requires multiplying the cos/sin tables by a constant.
- Do not say that changing only the positional encoding, without any training, can reliably extend the context by a large factor: Training-free extension is limited, and continued training on long text is usually still needed.
3.6 How is long-context ability evaluated, and what is "lost in the middle"? ★¶
One-sentence answer
Perplexity is dominated by tokens that depend only on local context and cannot show whether the model uses distant information, so long-context evaluations must be designed as tasks that "cannot be answered without distant information": needle-in-a-haystack is the most intuitive but too easy, while RULER adds multi-needle retrieval, multi-hop tracing and aggregation, revealing the gap between claimed and effective length. "Lost in the middle" means that a model uses information at the beginning and end of the input best and information in the middle worst, so accuracy follows a U shape across positions.
I will address three aspects: why perplexity is not enough, common evaluation methods, and lost in the middle.
(1) Perplexity is not enough: most tokens can be predicted well from nearby context alone.
Computing perplexity on long documents is the simplest evaluation, but its signal is weak. Most tokens can be predicted well from just the few hundred tokens nearby, and the tokens that truly need distant information are only a small fraction, so improvements on them barely show up in average perplexity. ALiBi also shows that a model can keep perplexity low while looking only at nearby content (see 3.3); Gao et al. (2024) even found that as the share of long data increases, perplexity keeps improving while long-context downstream tasks get worse (see Chapter 4 of the "LLM Training Pipeline" direction). Long-context evaluations must therefore be designed as tasks that cannot be answered correctly without distant information.
(2) Common evaluations are moving from simple retrieval toward tasks that require reasoning and integration.
- Needle-in-a-haystack (Kamradt 2023): insert one key sentence at some depth in a large body of unrelated text, then ask a question about it; varying both the context length and the insertion depth produces a heatmap that shows at a glance at which lengths and positions the model misses the information. It is simple and intuitive, but the "needle" and the question usually share obvious literal overlap, and the needle sticks out from its surroundings, so a single lookup is enough to answer, and strong models almost all score perfectly.
- RULER (Hsieh et al. 2024): a synthetic benchmark with configurable length and difficulty, containing 13 tasks in four categories: retrieval (multiple needles, multiple values, added distractors), multi-hop tracing (for example, following a chain like
X2 = X1, X3 = X2to track a variable's value), aggregation (for example, finding the most frequent words in a long text) and question answering. Its main finding is that almost every model scores near-perfectly on vanilla needle-in-a-haystack, but on RULER performance drops sharply as length increases. This led to the notion of "effective context length": the length a model can use reliably is often far shorter than the length it claims to support. - Real-task evaluations: for example, LongBench (Bai et al. 2023) and HELMET (Yen et al. 2024) cover long-document QA, summarization, generation with citations, multi-document RAG and many-shot in-context learning, which are closer to actual use. HELMET found that synthetic tasks like needle-in-a-haystack do not reliably predict downstream performance.
(3) Lost in the middle: the model uses information in the middle positions worst, and accuracy follows a U shape.
Liu et al. (2023) placed the document containing the answer at different positions in the input for multi-document QA and key-value retrieval tasks, and found that accuracy follows a U shape across positions: highest when the answer is at the beginning or end, and clearly lower when it is in the middle. This shows that the model does not use the whole context evenly. Several causes may contribute together: in training data, human-written text tends to put important information at the beginning (titles, abstracts) or the end (conclusions), and instructions usually come last, so the model learns to pay more attention to both ends; causal attention and RoPE's long-term decay naturally bias the model toward the most recent tokens, while the first tokens are seen by every later position and also tend to receive a lot of attention (related to the attention-sink phenomenon); and long-context training data contains too few examples that truly require extracting information from the middle. Practical mitigations include putting the most important information and the instructions at the beginning or the end, and deliberately placing key information at random positions in training data so the model learns to use the whole context evenly. As long-context training has improved, the U shape has flattened considerably in newer models, but it has not disappeared.
In summary: the key to long-context evaluation is using tasks that cannot be completed without distant information, and focusing on effective rather than claimed length; lost in the middle reminds us that information "fitting in the context" does not mean it is "used evenly and well".
Going deeper: concrete numbers and newer evaluations
(1) A few key numbers.
- Lost in the middle: in the 20-document setting, with the answer in the middle, GPT-3.5-Turbo's accuracy was even lower than its closed-book accuracy with no documents at all (56.1%) (Liu et al. 2023).
- RULER: all the models evaluated claimed contexts of 32K or more, yet only about half still performed satisfactorily at 32K (Hsieh et al. 2024).
- NoLiMa: Modarressi et al. (2025) built "needles" with almost no literal overlap with the question, so models must infer semantic associations to find the answer. At a length of 32K, most of the evaluated models fell below half of their short-context performance; GPT-4o dropped from a near-perfect 99.3% to 69.7%.
(2) Comparing common evaluations.
| Benchmark | What it tests | Property |
|---|---|---|
| Needle-in-a-haystack | Retrieval of a single piece of information | Intuitive, but saturated for strong models |
| RULER | Retrieval, multi-hop tracing, aggregation, QA | Synthetic, with controllable length and difficulty |
| NoLiMa | Retrieval without literal overlap | Requires inferring semantic associations |
| LongBench, LongBench v2 | Real long-document tasks | Closer to actual use |
| HELMET | Seven categories of downstream tasks | Found that synthetic retrieval does not reliably predict downstream performance |
(3) Two further points for evaluation.
- Evaluate after SFT: base models are often poor at following the instructions of long-context tasks, so their results underestimate their long-context ability.
- Check short-context ability as well: extending the context can hurt short-context performance, so both must be evaluated.
Follow-up questions
Follow-up 1: If you had to evaluate a model that claims a 128K context, what would you do?
Evaluate in layers, from simple to hard, with a focus on finding the effective length. Start with needle-in-a-haystack as a basic check that information can be retrieved at every length and depth; then run RULER at multiple lengths from 8K to 128K to find the effective length at which performance starts to drop clearly; then assess reasoning and integration with tasks without literal overlap, such as NoLiMa, and with real tasks from HELMET or LongBench; also vary the position of the key information to check for lost in the middle; and finally confirm that short-context benchmarks have not regressed.
Follow-up 2: With long context, do we still need RAG?
Yes; the two are complementary. Long context suits processing a few relevant long documents in one go, but its cost grows with length, and it suffers from limited effective length and lost in the middle; RAG first filters relevant content out of massive, frequently updated knowledge bases, at lower cost and with easier updates. In practice the two are often combined (see Chapter 2 of the "RAG" direction).
Follow-up 3: Why can a model that scores perfectly on needle-in-a-haystack still perform poorly on real long-document tasks?
Because needle-in-a-haystack tests only the simplest kind of literal retrieval. Its "needle" shares obvious literal overlap with the question and sticks out from the surrounding text, so a single lookup suffices; real tasks require understanding meaning, integrating information from several places, and reasoning. The results of RULER and NoLiMa both show that once literal overlap is removed, or multi-hop reasoning and aggregation are required, many models' performance drops sharply with length.
Common mistakes
- Do not use perplexity to show that a model uses long context well: Perplexity is dominated by local context and is insensitive to the use of distant information.
- Do not equate a perfect needle-in-a-haystack score with strong long-context ability: It tests only simple literal retrieval and is saturated for strong models.
- Do not say that lost in the middle happens because the middle information falls outside the context window: The information is entirely within the window; the problem is that the model uses different positions unevenly.
- Do not treat the claimed context length as the effective length: The length a model can use reliably is often far shorter than the claimed length.