Skip to content

Chapter 2 · Positional Encoding and Long Context


2.1 Why Position Information Is Needed ★

Chapter 1 (Section 1.2) explained that attention scores depend only on the content of the query and key, not on where they sit in the sequence. If you shuffle the input, each token's output simply moves along with it while its content stays exactly the same; this is permutation equivariance. But the meaning of language depends heavily on order: "dog bites man" and "man bites dog" use the same three words with opposite meanings. So we need some way to tell the model "this is position number such-and-such", and that is the job of positional encoding.

What makes a positional encoding good? Four requirements are useful:

  1. Every position is distinguishable. Encodings of different positions must not be confused, or the model can't tell what came first.
  2. Relative distance is easy to express. What really matters in language is usually relative: "an adjective modifies the noun right next to it", "a pronoun refers to a name a few sentences back". The same phrase means the same thing at position 10 or position 1000. So an ideal encoding lets the model directly sense "how far apart two tokens are", without memorizing absolute coordinates.
  3. It generalizes to longer sequences. The lengths seen in training are always limited, while inference often needs longer contexts.
  4. It is cheap and compatible with efficient implementations. Positional encoding shouldn't slow attention down, and ideally it works seamlessly with FlashAttention and the KV cache.

The various schemes trade these properties off against each other. They can be roughly classified along two axes: whether they encode absolute or relative position, and whether position information is added to the input embeddings or injected into the attention scores. Below we first cover the earliest absolute encodings (2.2), then relative encodings (2.3), and then focus on today's standard, RoPE (2.4). (There is also NoPE (Kazemnejad et al. 2023), which adds no positional encoding at all and relies on the position information implicit in the decoder-only causal mask, but it is not the mainstream choice.)

Interview questions

  • ★ Why does a Transformer need positional encoding, and what properties should a good one have?

2.2 Absolute Encodings: Sinusoidal and Learned ★

Sinusoidal encoding ★

\[p_{pos,\,2j} = \sin\!\left(\frac{pos}{10000^{2j/d}}\right), \qquad p_{pos,\,2j+1} = \cos\!\left(\frac{pos}{10000^{2j/d}}\right), \qquad h_{pos} = x_{pos} + p_{pos}\]
\[(x_m + p_m)^\top W (x_n + p_n) = \underbrace{x_m^\top W x_n}_{\text{content-content}} + \underbrace{x_m^\top W p_n + p_m^\top W x_n}_{\text{content-position}} + \underbrace{p_m^\top W p_n}_{\text{position-position}}, \qquad W = W_Q^\top W_K\]

The original Transformer (Vaswani et al. 2017) uses a fixed set of sine and cosine functions to produce a \(d\)-dimensional vector \(p_{pos}\) for each position, and adds it directly to the token embedding \(x_{pos}\). In the formula, \(pos\) is the position, \(j\) indexes the dimension pairs (\(j = 0, \dots, d/2-1\)), and \(d\) is the model dimension. Each pair of dimensions uses one frequency \(1/10000^{2j/d}\): dimensions with small \(j\) have high frequency and change quickly with position; dimensions with large \(j\) have low frequency and change slowly. Think of the second, minute and hour hands of a clock: the second hand tells neighboring moments apart, the hour hand tells far-apart moments apart, and together the hands give every moment a unique reading.

Why do sin and cos come in pairs? Because of the angle-addition formulas: \(\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\). In other words, \(p_{pos+k}\) equals a rotation matrix that depends only on \(k\), times \(p_{pos}\). The authors hoped this would let the model learn relative position easily. It also needs no parameters and can in principle produce an encoding for any position.

In practice it works less well than hoped, and the problem is the addition. When \(x_m + p_m\) and \(x_n + p_n\) go into attention, the score expands into four terms (see the formula). Only the last term depends purely on position; the middle two are cross terms mixing content and position, but there is usually no meaningful link between "a given word" and "a given absolute position", so these terms act more like noise that the model has to learn to ignore. And after the \(W_Q\) and \(W_K\) projections, the nice "depends only on \(k\)" property no longer holds exactly. As for extrapolation, although the formula can compute encodings for longer positions, the model has never seen what those new positions look like mixed with content, so quality drops noticeably as soon as it goes past the training length.

Interview questions

  • ★ Why does sinusoidal encoding use sin and cos at different frequencies?
  • ★ What is the problem with adding positional encodings to the input embeddings?

Learned absolute encoding ★

BERT and GPT-2 don't use a formula; they learn a table of position embeddings 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. The benefit is flexibility: the model learns whatever position representation suits it best, and within the training length it works about as well as sinusoidal encoding, sometimes slightly better.

The drawbacks are just as direct. The table size is fixed before training (512 for BERT, 1024 for GPT-2), and positions beyond it simply have no vector, so the model can't handle them at all and the input must be truncated. Even inside the table, later positions appear less often in the training data (many texts aren't that long), so their embeddings are undertrained. And it still adds absolute position to the input, so relative distance has to be inferred indirectly from two absolute positions, and the cross-term problem described above still applies.

Interview questions

  • ★ What are the pros and cons of sinusoidal vs learned positional encodings?
  • ★ Why can BERT handle at most 512 tokens?

2.3 Relative Position: T5 Bias and ALiBi ★

Since adding absolute position to the input mixes it with content, a natural idea is to keep the input embeddings purely about content and inject relative distance directly into the attention scores (the idea goes back to Shaw et al. 2018). The two methods below are the most representative; both add a bias that depends only on distance to the scores.

T5 relative bias ★

\[a_{mn} = \frac{q_m^\top k_n}{\sqrt{d_k}} + b_{h,\ \mathrm{bucket}(n-m)}\]

T5 (Raffel et al. 2019) learns a set of scalar biases \(b_h\) for each head. 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. 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 a single bucket. T5 uses 32 buckets in total and shares these biases across all layers.

Its strength is that it is a pure relative encoding with very few parameters, and because far distances all land in the same bucket, it generalizes somewhat to longer, unseen distances. It has two weaknesses. First, the bias has to be added pair by pair to the \(n \times n\) score matrix, so the attention kernel must support it specifically, and early implementations were slower. Second, the bias is just a scalar, so position can only change "attend a bit more or a bit less overall" and can't interact with content in finer ways; and since far distances are lumped into one bucket, the model can't tell 200 from 2000.

Interview questions

  • ★ How does T5's relative position bias work, and why are buckets fine nearby and logarithmic far away?

ALiBi ★

\[a_{mn} = \frac{q_m^\top k_n}{\sqrt{d_k}} - \lambda_h \,(m - n), \qquad n \le m\]

ALiBi (Press et al. 2021) is even simpler: it learns no parameters and directly subtracts a penalty proportional to distance from the score. \(m - n\) is the distance between query and key, and \(\lambda_h\) is a fixed slope per head, chosen as a geometric sequence (\(1/2, 1/4, \dots, 1/256\) for 8 heads). Heads with steep slopes are penalized heavily and only attend very close by; heads with gentle slopes can look further.

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, while training faster and using less memory. BLOOM and MPT both used ALiBi.

It still didn't become mainstream, and the reason lies in why it extrapolates. A linear penalty means that the farther away a token is, the lower its score, so distant tokens get almost zero attention weight and the model mainly uses nearby context, like a "soft sliding window". That is why perplexity doesn't blow up beyond the training length, but it doesn't mean the model really uses distant information, such as accurately retrieving a fact that appeared 50,000 tokens earlier. This strong recency bias is hard-coded, and the model can't learn its way around it. Meanwhile, RoPE combined with interpolation methods (2.6) works better on tasks that truly require long-range retrieval, so ALiBi was gradually replaced.

Interview questions

  • ★ How does ALiBi work, and why does it extrapolate?
  • ★ ALiBi extrapolates well, so why didn't it become mainstream?

2.4 Rotary Position Embedding (RoPE) ★★

The rotation formulation ★★

\[R(\phi) = \begin{pmatrix} \cos\phi & -\sin\phi \\ \sin\phi & \cos\phi \end{pmatrix}, \qquad R_m = \mathrm{diag}\big(R(m\theta_0),\, R(m\theta_1),\, \dots,\, R(m\theta_{d/2-1})\big), \qquad \tilde q_m = R_m q_m,\quad \tilde k_n = R_n k_n\]

RoPE (Su et al. 2021, RoFormer) starts from a question: is there a transformation of \(q\) and \(k\) such that the dot product after the transformation naturally depends only on relative position? The answer is rotation.

Start with two dimensions. \(R(\phi)\) is the matrix that rotates a 2D vector counterclockwise by angle \(\phi\). RoPE rotates the query at position \(m\) by \(m\theta\) and the key at position \(n\) by \(n\theta\): the later the position, the larger the angle. In \(d\) dimensions, the vector's dimensions are split into \(d/2\) pairs, each pair is treated as a 2D plane, and pair \(j\) rotates at its own frequency \(\theta_j\); together this gives the block-diagonal matrix \(R_m\) above. \(q_m\) and \(k_n\) are the vectors after the \(W_Q\) and \(W_K\) projections, \(\tilde q_m\) and \(\tilde k_n\) are the rotated results, and attention scores are computed from the rotated vectors.

A few details are worth noting:

  1. Only \(q\) and \(k\) are rotated, not \(v\). Position only needs to affect "who attends to whom", i.e. the scores; the value is the content being passed along and doesn't need to carry position.
  2. The rotation is applied again in every layer. It isn't added once at the input and forgotten; each layer rotates its current \(q\) and \(k\) before scoring, so position information doesn't fade in deep layers.
  3. It is cheap to implement. There's no need to build the matrix: each pair's rotation can be written as an element-wise operation like \(q \odot \cos(m\theta) + \mathrm{rotate\_half}(q) \odot \sin(m\theta)\), with the \(\cos\) and \(\sin\) tables precomputed, so the extra cost is tiny.

Interview questions

  • ★★ Explain how RoPE works.
  • ★ Why does RoPE rotate Q and K but not V?

Why q·k depends only on relative position ★★

\[\tilde q_m^\top \tilde k_n = (R_m q)^\top (R_n k) = q^\top R_m^\top R_n\, k = q^\top R_{n-m}\, k\]

This derivation is the heart of RoPE, and it uses two properties of rotation matrices. First, a rotation matrix is orthogonal, and its transpose is the reverse rotation: \(R(\phi)^\top = R(-\phi)\). Second, consecutive rotations in the same plane simply add their angles: \(R(a)R(b) = R(a+b)\). So \(R_m^\top R_n = R(-m\theta)R(n\theta) = R((n-m)\theta)\), and this holds for every pair of dimensions. In the final result only the content of \(q\) and \(k\) and the relative distance \(n - m\) remain; the absolute positions \(m\) and \(n\) themselves have disappeared.

The complex-number view makes this even clearer. Treat each pair of dimensions as a complex number \(q^{(j)}\); rotating by \(m\theta_j\) is just multiplying by \(e^{\mathrm{i} m\theta_j}\). The "dot product" of two such numbers is \(\mathrm{Re}\big[q^{(j)} e^{\mathrm{i} m\theta_j} \cdot \overline{k^{(j)} e^{\mathrm{i} n\theta_j}}\big] = \mathrm{Re}\big[q^{(j)}\, \overline{k^{(j)}}\, e^{\mathrm{i}(m-n)\theta_j}\big]\), which again depends only on \(m - n\).

This brings several important benefits:

  1. Multiplication instead of addition. Position enters by "multiplying in" a rotation rather than being added to the content, so the content-position cross terms of sinusoidal encoding disappear. And rotation doesn't change a vector's length, so it doesn't distort how strong the content signal is.
  2. Relative position implemented with absolute position. 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.
  3. Naturally compatible with the KV cache. Precisely because each key is rotated only by its own position, the rotated keys can be stored directly in the KV cache; a new query is rotated by its own position and scored against the cached keys, and nothing in the history needs recomputing. T5 bias, by contrast, has to add a bias pair by pair on the score matrix.

So is RoPE absolute or relative? The precise answer: it applies an absolute-position transformation to each token, but inside the attention score it behaves as a relative positional encoding. Section 2.5 will show that the model can in fact read absolute position from some dimensions, and this is exactly one source of the extrapolation problem.

Interview questions

  • ★★ Show that with RoPE, \(q \cdot k\) depends only on relative position.
  • ★ Is RoPE an absolute or a relative positional encoding?
  • ★ Why is RoPE compatible with the KV cache?

Frequency choice and long-range decay ★

\[\theta_j = b^{-2j/d}, \qquad \lambda_j = \frac{2\pi}{\theta_j} = 2\pi\, b^{2j/d}, \qquad j = 0, 1, \dots, \tfrac{d}{2} - 1\]

RoPE's frequencies follow the same geometric series as sinusoidal encoding: pair \(j\) rotates at frequency \(\theta_j\), \(b\) is the base (originally 10000), and \(d\) is the head dimension. \(\lambda_j\) is the pair's wavelength: how many tokens the position must advance for it to complete one full turn. Wavelengths range from the shortest, \(2\pi \approx 6\) tokens, up to the longest, close to \(2\pi b\) (about 54,000 tokens when \(b = 10000\) and \(d = 128\)).

Dimensions with different frequencies do different jobs. High-frequency dimensions rotate fast, so neighboring tokens already differ by a clear angle, which is good for telling nearby order apart; but over longer distances they wrap around many times and the angles repeat, so on their own they can't distinguish far distances. Low-frequency dimensions rotate slowly, so their angle only changes noticeably over long distances, and they supply coarse long-range position information. It's the same "second hand and hour hand" picture as in sinusoidal encoding: combining several scales lets the model resolve both near and far.

Long-term decay: Su et al. (2021) showed that with this frequency choice, if the content of \(q\) and \(k\) is held fixed, an upper bound on the score decays as relative distance grows. Intuitively, 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; at long distances their phases scatter and they cancel each other out. This gives the model a mild prior that nearby tokens usually matter more, which matches the statistics of language. Note, though, that this is only an upper bound in an idealized case, and the decay comes with oscillation; it isn't a hard-coded penalty like ALiBi's. The model can still attend far away by adjusting the content of \(q\) and \(k\) (especially through the low-frequency dimensions).

What the base does: the larger \(b\) is, the lower the frequency and the longer the wavelength of every pair except \(j = 0\) (whose \(\theta_0 = 1\) doesn't depend on the base), so the low-frequency dimensions reach farther and the long-term decay is slower, which suits long contexts better. That's why Llama 3 sets the base to 500,000 from the start of pretraining, Code Llama uses 1,000,000, and Qwen3 raises the base from 10,000 to 1,000,000 in its long-context stage. The cost is that the middle- and low-frequency dimensions rotate more slowly, so short-distance resolution drops slightly; and the base must match what was used in training, since changing it arbitrarily at inference breaks the position patterns the model has learned (NTK-aware scaling in 2.6 also changes the base, but by a specific rule that keeps the high-frequency dimensions almost unchanged).

Interview questions

  • ★ What roles do RoPE's high-frequency and low-frequency dimensions play?
  • ★ What does RoPE's base control, and why do long-context models increase it?
  • ★ What does RoPE's long-term decay mean, and is it a hard constraint?

Why RoPE became the standard ★★

  1. Relative position enters the score directly, while absolute information is kept. No extra bias term is needed; the dot product itself encodes distance, and there are no cross terms from addition.
  2. Zero parameters, and the score matrix is untouched. RoPE only modifies \(q\) and \(k\), and the attention computation itself is completely unchanged, so FlashAttention or any other efficient kernel can be used as is. T5 bias and ALiBi require the kernel to support adding a bias to the score matrix.
  3. Naturally compatible with the KV cache. Rotated keys can be cached and reused directly (see the previous subsection).
  4. Strong results and a positive feedback loop. After PaLM and Llama adopted it, almost every mainstream open model (Qwen, Mistral, DeepSeek and others) followed, and training and inference frameworks optimized heavily around it.
  5. Easy to extend the context. This later turned out to be especially important. RoPE's position information is entirely determined by "angle = position × frequency", so by rescaling the position or the frequencies, a small amount of continued training can extend the context from 4K to 128K or beyond (see 2.6). Learned encodings can't do this at all, and ALiBi, while it extrapolates, can't make good use of distant information.

Compared with sinusoidal encoding, RoPE uses the same geometric series of frequencies but differs in two key ways: sinusoidal encoding adds position to the input and acts only at the first layer, while RoPE multiplies (rotates) position into \(q\) and \(k\) in every layer, and the dot product depends strictly on relative distance.

Interview questions

  • ★★ Why did RoPE become the dominant positional encoding?
  • ★ How is RoPE similar to and different from sinusoidal encoding?

2.5 The Length Extrapolation Problem ★★

In practice, models usually do most of their pretraining on fairly short sequences (say 4K or 8K), because attention compute grows quadratically with length (see Chapter 1, Section 1.2) and long documents are rare in natural data anyway. Yet users want ever longer contexts. If you take a RoPE model trained at 4K and feed it an 8K input, perplexity shoots up past 4K and the output turns into gibberish. This is the length extrapolation problem. If RoPE is a relative encoding, why does it still fail?

Why models fail beyond the training length ★★

\[\text{angles seen in training: } m\theta_j \in [0,\ L\theta_j), \qquad L\theta_j < 2\pi \iff \lambda_j > L\]

There are three main reasons:

  1. Low-frequency dimensions meet angles they've never seen. With training length \(L\), pair \(j\) only ever sees rotation angles in \([0, L\theta_j)\). For high-frequency dimensions, \(L\theta_j\) is far larger than \(2\pi\): they have gone around many times in training and have seen every angle, so they're fine. But for low-frequency dimensions with wavelength \(\lambda_j > L\), training never completes even one full turn; they have only seen one arc of the circle. Take Llama 2 as an example (training length 4096, base 10000, head dimension 128): solving \(\lambda_j = 2\pi \cdot 10000^{2j/128} > 4096\) gives \(j \ge 46\), so the last 18 of its 64 pairs (\(j = 46, \dots, 63\)) don't complete a full turn within 4K. 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 \(q \cdot k\) values land in ranges the model doesn't know, the scores become unpredictable, and the errors grow layer by layer. This is why RoPE, "relative in theory", still fails to extrapolate in practice.
  2. 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" simply don't cover them.
  3. Attention gets diluted. The longer the sequence, the more keys softmax has to spread its weight over, so the distribution gets flatter and its entropy grows. The model's learned ability to "focus on a few key tokens" at the training length is watered down, and the truly relevant tokens get less weight. YaRN's temperature in 2.6 is designed to compensate for exactly this.

Interview questions

  • ★★ Why do models break beyond their training length? Isn't RoPE a relative encoding?
  • ★ Which RoPE dimensions are most likely to break when extrapolating, and why?

Extrapolation vs interpolation ★

There are two ways to handle longer inputs. Direct extrapolation keeps counting positions upward and makes the model cope with angles it has never seen; as shown above, this doesn't work. Interpolation goes the other way: it "compresses" the longer range of positions back into the range seen in training, so every angle falls in an interval the model knows. The cost is that the angle difference between neighboring positions shrinks, resolution drops, and a little continued training is needed to adapt. This idea is the starting point for every method in 2.6.

Some methods sidestep the problem architecturally. (For example, sliding-window attention lets each token see only the last \(W\) tokens (Mistral 7B uses \(W = 4096\)), so positions never exceed the window and compute grows only linearly with length; but information outside the window can only pass indirectly through stacked layers, which makes it hard to recall distant details precisely; see Chapter 6, Section 6.8.) Also keep in mind that perplexity not blowing up doesn't mean the model can really use a long context: ALiBi shows that a model can keep perplexity low using only nearby context while being unable to retrieve anything far away. So long-context ability ultimately has to be checked with retrieval-style evaluations like those in 2.8.

Interview questions

  • ★ What are length extrapolation and position interpolation?

2.6 Context Extension: PI, NTK-Aware Scaling and YaRN ★★

RoPE's rotation angle is "position \(m\) × frequency \(\theta_j\)", so every context-extension method boils down to one of two operations: rescale the position \(m\), or change the frequencies \(\theta_j\). The three methods below all belong to this family and are usually combined with a small amount of continued training on long text. Let the original training length be \(L\), the target length \(L'\), and the extension factor \(s = L'/L\).

Position Interpolation ★★

\[m \;\to\; \frac{m}{s} \quad\Longleftrightarrow\quad \theta_j \;\to\; \frac{\theta_j}{s} \quad \text{for every } j\]

Position Interpolation (Chen et al. 2023) is the most direct: divide every position by \(s\). For example, extending from 2K to 8K (\(s = 4\)), position 8000 is rotated as if it were position 2000. Every angle is thus squeezed back into the range seen in training, and the model never meets an unfamiliar angle. The paper extended LLaMA from 2K to 32K (\(s = 16\)) with no more than 1000 fine-tuning steps, and showed theoretically that the error bound for interpolation is much smaller than for direct extrapolation (by their estimate, at least about 600 times smaller).

The problem with PI is that it compresses all dimensions equally, including the high-frequency ones. Two neighboring tokens used to differ by angle \(\theta_j\) in pair \(j\); now they differ by only \(\theta_j / s\). High-frequency dimensions were the main tool for telling nearby order apart, and once compressed, neighboring tokens become hard to distinguish in them; it's like squeezing 4 tokens into the space that used to hold 1, so local resolution drops. That's why PI depends on fine-tuning to let the model adapt to these "denser" positions, and the larger \(s\) is, the more local resolution is lost and the harder that adaptation becomes.

Interview questions

  • ★★ Why is interpolation better than direct extrapolation, and what does it cost?

NTK-aware scaling ★★

\[b' = b \cdot s^{\frac{d}{d-2}}, \qquad \theta'_j = b'^{-2j/d} = \theta_j \cdot s^{-\frac{2j}{d-2}}\]

NTK-aware scaling (bloc97 2023, first proposed in the open-source community) targets exactly PI's loss of high-frequency information. It starts from an observation in NTK theory: if the input lacks high-frequency components, a neural network struggles to learn high-frequency details. PI wipes out exactly those components. So a better approach is to leave the high-frequency dimensions alone and interpolate only the low-frequency ones, shifting the compression pressure to the low-frequency side.

The simplest way to achieve this is to change only the base. Replacing \(b\) with \(b'\) changes each frequency to \(\theta'_j = \theta_j \cdot s^{-2j/(d-2)}\). Check 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; dimensions in between transition smoothly, with lower frequencies compressed more.

Its advantage is that it does noticeably better than PI even without fine-tuning. There is also a companion, Dynamic NTK: at inference, set \(s = \max(1, l/L)\) based on the current sequence length \(l\), so short inputs are completely unaffected and scaling only kicks in gradually for long inputs. Code Llama setting the base to 1,000,000 and Llama 2 Long (Xiong et al. 2023) raising it to 500,000 with continued training, the so-called ABF (adjusted base frequency), are essentially the same idea. Its weakness is that the dimensions in the middle aren't fully squeezed back into the training range: they are partly interpolated and partly extrapolated, so they still meet unseen angles. This has two consequences: the nominal \(s\) isn't the true usable extension factor, so in practice \(s\) often has to be set larger than the target; and the YaRN paper reports that after fine-tuning on long text, NTK-aware scaling actually does worse than PI.

Interview questions

  • ★★ How do PI and NTK-aware scaling differ?
  • ★ How does changing only the base keep high frequencies intact while interpolating low ones?
  • ★ Can you extend the context without fine-tuning?

YaRN ★

\[r_j = \frac{L}{\lambda_j}, \qquad \theta'_j = \begin{cases} \theta_j / s, & r_j < \alpha \\ \theta_j, & r_j > \beta \\ \text{linear blend of the two}, & \text{otherwise} \end{cases} \qquad\quad \sqrt{1/t} = 0.1 \ln s + 1\]

YaRN (Peng et al. 2023) makes the earlier ideas more precise and has two parts. The first is called NTK-by-parts: instead of adjusting everything through one base, it treats each dimension according to how many turns it makes within the training length. \(r_j\) is the number of turns pair \(j\) completes within training length \(L\). Low-frequency dimensions that don't 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 blend linearly. For the Llama family the recommended values are \(\alpha = 1\) and \(\beta = 32\).

The second part is an attention temperature: the attention logits are divided by a temperature \(t\) chosen so that \(\sqrt{1/t} = 0.1 \ln s + 1\), an empirical formula the authors fit on Llama. It targets the attention dilution described in 2.5: as sequences get longer, softmax flattens, and scaling the logits up a little refocuses attention. In practice it only requires multiplying the cos/sin rotation tables by a constant, so there is no extra cost and no change to the attention kernel.

YaRN reports needing about 10 times fewer tokens and 2.5 times fewer training steps than previous methods, extending Llama 2 to 128K. It is now widely used: after pretraining at 4K, DeepSeek-V3 used YaRN to extend to 32K and then 128K in two phases, and Qwen3 uses YaRN (together with Dual Chunk Attention) at inference to extend its usable length by a further 4 times. (Llama 3.1 also uses a similar frequency-dependent scaling.)

Position Interpolation NTK-aware YaRN
What it changes Divides all positions by \(s\) Increases the RoPE base Per-dimension interpolation + attention temperature
High-frequency dims Compressed by \(s\) Almost unchanged Unchanged
Low-frequency dims Compressed by \(s\) Compressed by up to \(s\) Compressed by \(s\)
Without fine-tuning Poor Reasonable (esp. Dynamic NTK) Good
With fine-tuning Works (2K → 32K in the paper) Worse than PI after fine-tuning Best; few tokens needed
Main weakness Loses local resolution Middle dims partly extrapolate; nominal \(s\) overstates the real extension Extra hyperparameters (\(\alpha\), \(\beta\))

Interview questions

  • ★★ How do PI, NTK-aware scaling and YaRN differ?
  • ★ Why does YaRN add an attention temperature?

2.7 Long-Context Training in Practice ★

Progressive length ★

Why not pretrain on long sequences from the start? First, attention compute grows quadratically with length, so each token in a long sequence costs more (in Chapter 1, Section 1.8, the extra attention cost is about \(n_{ctx}/12d\) of the parameter part), and training at 128K from scratch would be extremely expensive. Second, most training data is short anyway; forcing it into long sequences just glues unrelated short documents together, which doesn't teach the model to use long-range dependencies. Third, early in training the model is mostly learning local patterns like grammar and knowledge, and short sequences are enough for that. So the standard recipe is: do most of pretraining at 4K–8K, and lengthen gradually in a few steps at the very end.

Concrete examples: Llama 3 increased the context from 8K to 128K in six stages, using about 800B tokens for this long-context stage. Each stage moved on only when two conditions were met: performance on short-context evaluations had fully recovered, and the model perfectly solved needle-in-a-haystack tests at the current length. Each lengthening step is paired with a larger RoPE base (ABF) or YaRN-style scaling (2.6), so that the new length falls within angle ranges the model can adapt to. Xiong et al. (2023) also found that continued long-context training from a short-context model works about as well as training on long sequences from scratch, at a much lower cost, which supports "short first, long later" experimentally.

On the engineering side, a very long sequence doesn't fit on one GPU, so one sequence has to be split across several GPUs and computed in parallel (context parallelism / ring attention, see Chapter 5, Section 5.9), and FlashAttention is essential. At inference the KV cache grows linearly with length and is the main memory bottleneck for long-context serving (see Chapter 1, Section 1.5, and Chapter 6, Section 6.8).

Interview questions

  • ★ Why not pretrain on long sequences from the start?
  • ★★ Given a model trained with a 4K context, how would you extend it to 128K?
  • ★ How do you decide that a context-extension stage has finished training?

Long-document data ★

Long sequences alone aren't enough: there have to be real long-range dependencies inside them for the model to learn to use them. Common sources of long data are naturally long documents: books, long papers, legal documents, long web pages, and code data built by concatenating the files of one repository according to their dependencies. One can also synthesize data that requires pulling information from far away.

There are several important findings about the data mixture. Fu et al. (2024) found that continued long-context training doesn't need much data: 500 million to 5 billion tokens are enough for the model to retrieve information from any position within 128K, and continued training of the full model on 1 to 5 billion tokens is an effective and affordable recipe. The keys are two things: keep a balanced domain mix, and raise the share of long documents within each domain. Many earlier works simply upsampled books heavily (because books are the longest), and this actually worked worse, because it distorted the domain distribution. Xiong et al. (2023) likewise found that how much long text the pretraining data contains isn't the key factor; data quality and mixture matter more. Long-context data usually also mixes in a good share of short data to keep short-text ability from regressing. (For example, Qwen3's long-context stage trains at length 32K, with 75% of the text between 16K and 32K tokens long and 25% between 4K and 16K.)

One easily overlooked detail: when several short documents are packed into one long training sequence, a document-level attention mask is usually added so tokens only attend within their own document (Llama 3 does this). Otherwise the model picks up the bad habit of attending to distant, unrelated content. After pretraining, long-context SFT data (often synthetic long-document QA and summarization) is still needed to teach the model to actually use long inputs in conversation (see Post-Training Chapter 1).

Interview questions

  • ★ How much data does continued long-context training need, and how should it be mixed?
  • ★ Short-context ability dropped after context extension. What do you do?

2.8 Long-Context Evaluation ★★

Why perplexity is not enough ★

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 a small fraction, so improvements on them barely show up in average perplexity. The ALiBi example also shows that a model can keep perplexity low while looking only at nearby content. So long-context evaluations have to be designed as tasks that "can't be answered correctly without distant information".

Interview questions

  • ★ If perplexity doesn't blow up on long sequences, does that show the model uses long context well?

Needle in a haystack ★★

Needle-in-a-haystack (NIAH; Kamradt 2023) is the best-known long-context test: insert one key sentence (the "needle") at some depth in a large body of unrelated filler text (the "haystack"), then ask the model a question about that sentence. In the original version the haystack was a collection of Paul Graham's essays, and the needle was an out-of-place sentence saying, roughly, that the best thing to do in San Francisco is to eat a sandwich in Dolores Park on a sunny day. By varying both the total context length and the insertion depth, you get a heatmap that shows at a glance at which lengths and positions the model misses the information. A similar test is passkey retrieval: hide a number in noisy text and ask the model to find it.

Its strengths are that it is simple, intuitive and controllable, which is why almost every long-context model report includes this heatmap. Its limits are just as obvious: the needle and the question usually share clear literal overlap, and the needle sticks out from the haystack, so the model only needs one simple "lookup" to answer correctly, with no understanding, reasoning or combining of information from several places. As a result, many models score nearly perfectly on NIAH yet perform only so-so on real long-document tasks.

Interview questions

  • ★★ How does the needle-in-a-haystack test work, and what are its limitations?

RULER ★

RULER (Hsieh et al. 2024) is a synthetic benchmark designed to address NIAH's shortcomings, with configurable length and difficulty. It has 13 tasks in four categories: retrieval (harder NIAH variants, such as multiple needles, multiple values, multiple questions and added distractors), multi-hop tracing (e.g. variable tracking: X1 = 12345, X2 = X1, X3 = X2 …, asking which variables equal 12345, which requires following the chain step by step), aggregation (e.g. finding the most frequent words in a long text, which requires combining the whole passage) and question answering (answering questions amid many distractor documents).

RULER's most important finding: almost every model scores near-perfectly on vanilla NIAH, but on RULER their performance drops sharply as length increases. The paper evaluated 17 long-context models; all claimed contexts of 32K or more, yet only about half still performed satisfactorily at 32K. This led to the notion of effective context length: the length a model claims to support often differs greatly from the length it can actually use reliably, and evaluations should look at the latter.

Interview questions

  • ★ What does RULER test beyond needle-in-a-haystack, and what is effective context length?
  • ★ How would you evaluate a model that claims a 128K context?

Lost in the middle ★★

Liu et al. (2023) ran a simple experiment on multi-document QA and key-value retrieval: put the document containing the answer at different positions in the input and see how accuracy changes. The result is a U-shaped curve: accuracy is highest when the answer is at the beginning or the end, and clearly lower when it is in the middle. In the 20-document setting, GPT-3.5-Turbo's accuracy with the answer in the middle was even lower than its closed-book accuracy with no documents at all (56.1%). In other words, the model doesn't use the whole context evenly.

Why does this happen? There are several explanations, which may all contribute. First, the training data distribution: 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. Second, RoPE's long-term decay and the structure of causal attention naturally bias the model toward the most recent tokens (the end), while the first tokens are seen by every later position and also tend to receive more attention. Third, long-context training data doesn't contain enough 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 hasn't disappeared. For how to order retrieved documents in RAG, see RAG Chapter 3, Section 3.5; for how to choose between long context and RAG, and whether one can replace the other, see RAG Chapter 3, Section 3.6.

Interview questions

  • ★★ What is "lost in the middle", why does it happen, and how can it be mitigated?
  • ★★ With long context, do we still need RAG? (see RAG Chapter 3, Section 3.6)

2.9 Positional Encodings Compared ★★

Sinusoidal Learned absolute T5 relative bias ALiBi RoPE
Position type Absolute Absolute Relative Relative Absolute transform, relative in the score
Where it enters Added to input embeddings Added to input embeddings Scalar bias on attention scores Linear distance penalty on attention scores Rotates \(q\) and \(k\) in every layer
Extra parameters None One vector per position One scalar per bucket per head None None
Beyond training length Poor Impossible (no embedding) Somewhat (far distances share a bucket) Perplexity stays stable, but distant info is barely used Poor as is; strong with PI / NTK / YaRN
Efficient kernels and KV cache Fine Fine Kernel must add the bias Kernel must add the bias Works with any kernel; rotated keys are cached
Used by Transformer (2017) BERT, GPT-2 T5 BLOOM, MPT PaLM, Llama, Qwen, Mistral, DeepSeek

Interview questions

  • ★★ Compare the main positional encoding methods.