YaRN: Extending RoPE Models to a 128K Context Window with Light Fine-Tuning
YaRN extends a RoPE model's context window by interpolating each rotary dimension according to how many turns it makes within the training length and adding a softmax temperature tied to ln s. 400 to 600 fine-tuning steps take Llama 2 to 128K. This post covers PI, NTK-aware and the evidence.
On this page
- Why This Paper Matters
- What the Paper Contributes
- Background: Why RoPE Cannot Simply Extrapolate
- From PI to YaRN: A Chain of Patches
- NTK-aware: Why Change the Base
- NTK-by-parts: Splitting by the Number of Turns
- YaRN: Add a Temperature
- Dynamic Scaling
- Experiments: One Set of Llama 2 Models and One Ablation
- Training Setup
- Long-Sequence Language Modeling
- Ablation: Who Is Better at the Same Budget
- Open the Component and Check Against the Paper’s Settings
- Passkey Retrieval
- Has Short-Text Ability Degraded?
- Training Cost
- Hands-On: Why Dynamic Scaling Must Cache the Key Before Rotation
- Limitations and What to Watch For
- What to Take Away from This Paper
- Further Reading
- FAQ
Why This Paper Matters
RoPE is now standard in open large models; Llama, Qwen and DeepSeek all use it. But a model trained with RoPE fails once it goes past its training length: the abstract itself says that these models fail to generalize past the sequence length they were trained on. In 2023 the open-source community came up with several low-cost methods that change only RoPE: position interpolation (PI, proposed around the same time by Chen et al. and kaiokendev), NTK-aware scaling (a post by bloc97 on Reddit), Dynamic NTK (a post by emozilla) and NTK-by-parts (a GitHub pull request by bloc97). By the paper’s account, Dynamic NTK is meant for models without fine-tuning, and NTK-by-parts performs best after a little fine-tuning on longer text.
The YaRN (Yet another RoPE extensioN method) paper does two things. First, it writes up these informal pieces of work in full and explains why each step is made. Second, it adds an attention temperature on top of NTK-by-parts, which gives YaRN. The paper notes that NTK-aware scaling already appears in Code Llama (which manually sets the base to 1,000,000, calling it the “adjusted base frequency”) and Dynamic NTK is used in Qwen 7B. Later, DeepSeek-V3 used YaRN for its 128K extension; see the DeepSeek-V3 explainer.
The abstract makes three claims: it needs 10x fewer tokens and 2.5x fewer training steps than previous methods; LLaMA models can effectively use context much longer than their original pretraining allows and surpass the previous best extension methods; and the method can also extrapolate beyond the length of the fine-tuning data, that is, “train short, test long”.
This post follows the order of the paper. The full derivation of the formulas, the values used by various models and an interactive component where you can drag the parameters are in the wiki page on Long Context. Here the interest is in how the paper argues, what the experiments show and where to apply a discount.
What the Paper Contributes
- A unified notation. It writes every method as two edits to RoPE, a position function and a frequency function , which makes item-by-item comparison easy.
- The community methods, written up as a paper. It explains the motivation and procedure of NTK-aware, NTK-by-parts and Dynamic NTK in full.
- YaRN. NTK-by-parts plus an attention temperature. Both changes touch only the precomputed RoPE tables, add no inference cost and work directly with FlashAttention 2.
- Experiments. Llama 2 7B and 13B are extended to 64K and 128K, trained on 64K data and evaluated at 128K; and on LLaMA 7B there is an equal-budget ablation against PI, NTK-aware and NTK-by-parts.
Background: Why RoPE Cannot Simply Extrapolate
RoPE gives every pair of dimensions a rotation frequency, and the inner product of a query and a key depends only on the relative distance. This post follows the notation of the wiki: is the index of the dimension pair, is the head dimension (written in the paper, with index ), and with base the frequency of pair is . The wavelength and the number of turns within the training length are:
Since RoPE is a relative position encoding, it is a little odd that it cannot extrapolate. The paper’s explanation is that RoPE does not encode only relative position. If the wavelength of a pair is longer than the training length (), it does not complete a turn during training, so the distance from each position to the first token is unique and the network can use it to infer absolute position, whereas dimensions with very short wavelengths can provide only relative position information. For this step the paper uses the words “we presume”; there is no rigorous proof. Three design principles follow:
- Do not touch dimensions whose wavelength is much shorter than ; they distinguish the order of neighboring tokens.
- Dimensions whose wavelength is at least are only interpolated, never extrapolated, because larger distances are out of distribution for them.
- Dimensions between the two get a bit of both treatments.
From PI to YaRN: A Chain of Patches
The table below lists, in the order of the paper’s narrative, the problem each method solves, what it does and what it leaves behind ( is the extension factor and is the target length):
| Method | Problem to solve | What it does | What it leaves behind |
|---|---|---|---|
| Position interpolation (PI) | With direct extrapolation, positions fall outside the training range and perplexity explodes | Scales position to , that is , pressing everything back into the training range, then fine-tunes | All frequencies slow down together and the high-frequency (local position) information is lost; the paper says earlier PI-based fine-tuning starts to lose accuracy at an extension factor of about |
| NTK-aware | PI wipes out the high frequencies of RoPE | Replaces the base with : the highest frequency is unchanged, the lowest equals linear interpolation, and the ones in between change smoothly | Not pure interpolation, some dimensions are still extrapolated, and it fine-tunes worse than PI; the best base has to be found by trial, and in practice must be set larger than the target factor |
| NTK-by-parts | NTK-aware only happens to keep high frequencies and move low ones, and not precisely | Splits explicitly by the number of turns : dimensions with few turns are interpolated like PI, dimensions with many turns are left alone, with a linear blend in between | Still not ideal without fine-tuning (see the ablation table below) |
| YaRN | Lower perplexity further on top of NTK-by-parts | Adds a temperature before the softmax, with the factor determined by | An empirical formula fitted on LLaMA |
| Dynamic scaling | With a fixed , short sequences lose accuracy and beyond quality collapses | Computes from the current sequence length at each forward pass | The implementation must cache the key before rotation |
NTK-aware: Why Change the Base
The paper cites the conclusion that Tancik et al. (2020, Fourier Features Let Networks Learn High Frequency Functions in Low Dimensional Domains) derived from neural tangent kernel (NTK) theory: when the input dimension is very low and the embedding lacks high-frequency components, a deep network has trouble learning high-frequency information. A position is a single number, and RoPE expands it into a multi-dimensional complex vector much like Fourier features; PI stretches all dimensions by the same ratio, which wipes out the high-frequency components. So the goal of NTK-aware scaling is that the lowest frequency be scaled as in linear interpolation while the highest stays unchanged. Choose so that the wavelength of the last pair equals its wavelength after linear interpolation:
It has two problems. First, it is not pure interpolation: some dimensions are slightly extrapolated to out-of-range values, so after fine-tuning it does worse than PI, and the theoretical does not describe the actual extension factor accurately; in practice has to be set larger than the target factor. Second, given a target factor, the best base is hard to determine in advance and usually has to be found by experiment.
NTK-by-parts: Splitting by the Number of Turns
Introduce two thresholds and a ramp function ( means no interpolation):
Dimensions that turn fewer than times are divided by as in PI, and dimensions that turn more than times are left unchanged. and depend on the model; the good values the paper found for the Llama family are and .
YaRN: Add a Temperature
The paper finds that introducing a temperature before the softmax has a consistent effect on perplexity for any data sample and at any position in the extended window (Appendix A.3):
The coefficient comes from fitting, with NTK-by-parts interpolation on non-fine-tuned LLaMA 7B, 13B, 33B and 65B, the that minimizes perplexity for each extension factor. The paper says the same values largely work for Llama 2 7B, 13B and 70B too, and guesses from this that the property of “increased entropy” and the temperature constant may be fairly universal. Appendix A.3 checks LLaMA 7B on 896 RedPajama documents of 16K tokens: with fixed, the best is essentially the same across samples and positions; the paper adds that this holds for different and that the best matches the recommended formula closely. At the factor is 1.208.
When , , which scales the logits up by and sharpens the attention distribution. The paper mentions “increased entropy” in a single sentence in Section 3.3, without elaboration and without measuring entropy. You can read the temperature as offsetting the entropy increase that interpolation brings, but that is the reader’s inference, and the paper’s evidence is perplexity.
In implementation, the attention code does not change: multiply both the cos and sin of RoPE by , q and k each receive one factor, and the logits are divided by as a whole. These tables are precomputed and reused in training and inference, so there is no extra cost. NTK-by-parts plus this temperature is YaRN.
Dynamic Scaling
When there are many forward passes and the sequence length grows from 1 to the maximum (for example autoregressive generation), there are two ways to use it: fix for the whole inference process, or update with the current sequence length at each forward pass. The former may lose accuracy when the length is below and quality drops suddenly beyond ; the latter lets the model degrade smoothly instead of collapsing when it hits the limit. This is an inference-time trick that can be combined with any interpolation method. Combined with NTK-aware scaling it is called Dynamic NTK, first seen in emozilla’s Reddit post; combined with YaRN it is called Dynamic-YaRN.
Appendix B.7 compares them on one GovReport document with a Llama 2 that has not been fine-tuned: dynamic scaling prevents perplexity from exploding beyond 4096, and the long-range perplexity of Dynamic-YaRN is better than Dynamic-PI. This is the curve of a single sample (Figure 8) and no numbers are given.
Experiments: One Set of Llama 2 Models and One Ablation
Training Setup
Llama 2 7B and 13B are extended to 128K with the architecture left unchanged except for how the RoPE frequencies are computed, taking and . The learning rate is with no weight decay and a linear warmup of 20 steps, and AdamW uses , . The model is fine-tuned for 400 steps on PG19 cut into 64K segments, with a global batch of 64, FSDP and FlashAttention 2. For the model, because of limited compute, training resumes from the trained checkpoint for only 200 more steps, still on 64K segments, so its behavior at 128K is purely extrapolated. The ablation uses LLaMA 7B with 32K segments, and 400 training steps; the training loss curves in the paper (Figure 2) show YaRN converging faster than the other three interpolation methods, with a consistently lower loss.
How many tokens did training use? The estimate below assumes “a global batch of 64 sequences of 64K (65,536) tokens each”:
batch, seq = 64, 64 * 1024 # global batch of 64 sequences, 64K (65,536) tokens
llama2_tokens = 2e12 # the Llama 2 pretraining corpus: about 2 trillion tokens
for name, steps in (("s=16, 400 steps", 400), ("s=32, 400+200 steps", 600)):
tokens = steps * batch * seq
print(f"{name}: {tokens / 1e9:.2f}B tokens, "
f"{tokens / llama2_tokens:.3%} of Llama 2 pretraining")
Output:
s=16, 400 steps: 1.68B tokens, 0.084% of Llama 2 pretraining
s=32, 400+200 steps: 2.52B tokens, 0.126% of Llama 2 pretraining
So the paper’s “less than about 0.1% of the original pretraining data” is an order-of-magnitude statement: the s=16 model is indeed below 0.1%, and the s=32 model is a bit above.
Long-Sequence Language Modeling
The evaluation uses the GovReport and Proof-pile test sets, with perplexity computed with a sliding window (stride ), an algorithm that counts the perplexity of the whole document even when the model’s window is shorter. Table 1 comes from 10 randomly sampled Proof-pile documents of at least 128K tokens each, truncated to the evaluation window (lower is better; “>10” means above 10):
| Model | s | Training steps | 8K | 16K | 32K | 64K | 128K |
|---|---|---|---|---|---|---|---|
| Llama 2 7B + YaRN | 16 | 400 | 3.51 | 2.99 | 2.65 | 2.42 | >10 |
| Llama 2 7B + YaRN | 32 | 400+200 | 3.56 | 3.04 | 2.70 | 2.45 | 2.37 |
| Llama 2 13B + YaRN | 16 | 400 | 3.25 | 2.79 | 2.50 | 2.29 | >10 |
| Llama 2 13B + YaRN | 32 | 400+200 | 3.29 | 2.83 | 2.53 | 2.31 | 2.24 |
The models are fine up to 64K and collapse beyond the length of the training data; the models, trained for another 200 steps and also having seen only 64K data, push the window to 128K, and their perplexity keeps falling as the window grows. The paper credits this to extrapolation ability and transfer learning: only 200 more steps on top of the checkpoint are needed.
The paper also compares YaRN’s two models with two public long-context models fine-tuned from Llama 2 (Table 7, 7B, the same ten documents). Together.ai’s PI model has a 32K window, and beyond that its perplexity explodes (above 100 at 64K and above at 128K). Code Llama’s NTK-aware model has a 100K window and gets 3.71 at 8K and 2.71 at 128K, while YaRN () gets 3.56 and 2.37 at those two points. GovReport (50 documents of at least 16K tokens, fixed 32K window, no dynamic scaling) tells a similar story: the 7B YaRN models get 3.59 () and 3.64 (), Together gets 3.67 and Code Llama 4.44; for 13B, YaRN gets 3.35 and 3.39 and Code Llama 4.22.
From this the paper calls YaRN the first method to successfully extend the effective context of Llama 2 to 128K. That claim should be read together with the passkey results below: 13B Code Llama has the same 99.4% passkey accuracy at 128K. And Code Llama was obtained from Llama 2 by continued training on 500B tokens of mostly code data, with long-context fine-tuning on 16K sequences (see the Code Llama paper), so the comparison with Llama 2 itself is not clean.
Ablation: Who Is Better at the Same Budget
On LLaMA 7B (original window 2K, extended to 32K, ), the paper compares four interpolation methods in three settings: no fine-tuning, no fine-tuning with dynamic scaling, and 400 steps of fine-tuning. The table below excerpts the perplexity at three evaluation windows, 2048, 8192 and 32768 (Table 5). The original model gets 4.05 at 2048:
| Setting | Method | 2048 | 8192 | 32768 |
|---|---|---|---|---|
| No fine-tuning, fixed s | PI | >100 | >100 | >100 |
| No fine-tuning, fixed s | NTK-aware | 5.23 | 5.22 | >10 |
| No fine-tuning, fixed s | NTK-by-parts | 6.04 | >10 | >10 |
| No fine-tuning, fixed s | YaRN | 4.61 | 4.18 | 3.45 |
| No fine-tuning, dynamic s | PI | 4.05 | 6.18 | >100 |
| No fine-tuning, dynamic s | NTK-aware | 4.05 | >10 | >10 |
| No fine-tuning, dynamic s | NTK-by-parts | 4.05 | 4.11 | >10 |
| No fine-tuning, dynamic s | YaRN | 4.05 | 3.65 | 3.45 |
| Fine-tuned 400 steps | PI | 5.70 | 4.64 | 3.57 |
| Fine-tuned 400 steps | NTK-aware | 4.39 | 3.73 | 8.49 |
| Fine-tuned 400 steps | NTK-by-parts | 4.14 | 3.62 | 2.81 |
| Fine-tuned 400 steps | YaRN | 4.19 | 3.30 | 2.77 |
A few points are worth noting:
- PI is unusable without fine-tuning. With a fixed , perplexity is above 100 at every window.
- The temperature is the key without fine-tuning. With the same and no fine-tuning, NTK-by-parts is above 10 from 8192 up, while YaRN with the temperature still gets 3.45 at 32768.
- Dynamic scaling protects short text. Under dynamic scaling the perplexity at 2048 equals that of the original model (4.05), whereas YaRN with a fixed gets 4.61 at 2048.
- NTK-aware collapses at the end of the window after fine-tuning. After 400 steps it gets 8.49 at 32768 against 3.57 for PI, which agrees with the paper’s judgment that NTK-aware fine-tunes worse than PI because some dimensions are extrapolated.
- YaRN is not best everywhere. After fine-tuning, NTK-by-parts (4.14) is slightly better than YaRN (4.19) at 2048; YaRN leads by 0.32 at 8192 (3.30 vs 3.62) and by only 0.04 at 32768 (2.77 vs 2.81). The paper says YaRN is consistently better than the other methods; a more accurate reading is that it is best overall, with the biggest advantage without fine-tuning, a smaller gap to NTK-by-parts after fine-tuning, and in a few windows slightly worse.
The paper also gives a training-efficiency comparison (Table 6, Llama 2 7B, extending 4K to 8K, ): the PI side is LLongMA-2 7B, trained for 1000 steps with the method of Chen et al., while YaRN trains for only 400 steps, with 2.5 times fewer steps and less data. The perplexity at the 8192 window is 3.34 and 3.35, essentially level; without fine-tuning, YaRN’s 3.49 is also lower than PI’s 3.65 (original Llama 2 gets 4.00 and 3.58 at 2048 and 4096).
Open the Component and Check Against the Paper’s Settings
The component below is the same one as in the wiki. Under “Load a setting” choose “Custom”, set “Trained length L” to 4096 and “Factor s” to 16 and then 32, and you have the paper’s two Llama 2 128K models (, ).
You can check these numbers:
- Summary rows. There are 18 dimension pairs (out of 64) that do not complete one turn within , and YaRN’s split is 21 / 25 / 18 (kept / blended / divided by ); this split depends only on , and , not on . The target lengths are 65,536 () and 131,072 (); the new bases for NTK-aware are 167,199 and 338,097; YaRN’s attention scaling is 1.277 (logits ×1.63) and 1.347 (×1.81).
- Inspect pair 63 (the lowest frequency). For plain RoPE, ”÷ turns seen in training” is , while PI, NTK-aware and YaRN all give : the slowest pair is pressed back into the range seen in training.
- Inspect pair 50 (less than one turn). PI and YaRN give , NTK-aware gives () and (), which is what the paper means by “not pure interpolation, some dimensions are still extrapolated”.
- Inspect pair 33 (YaRN’s blend region). At YaRN gives , between PI’s and the original’s ; NTK-aware gives .
- Inspect pair 0 (the fastest turning). YaRN and NTK-aware keep the original frequency while PI divides it by , which is exactly where PI loses local position resolution.
Passkey Retrieval
The passkey task hides a five-digit passkey inside a lot of meaningless text and asks the model to retrieve it. For the 64K and 128K YaRN models, the paper runs 10 trials at each window from 8K to 128K, with the passkey position uniformly random in the window; it reports that the 7B and 13B models pass across the whole window with high accuracy (>99%). Table 9 gives more comparisons (“passkey context” is the largest tested window with accuracy of at least 80%, and “accuracy” is the average over all tested lengths up to that window):
| Model | Method | Window | Training data length | Passkey context | Accuracy |
|---|---|---|---|---|---|
| Together 7B | PI | 32K | 32K | 32K | 100% |
| Code Llama 7B | NTK-aware | 100K | 16K | 112K | 94.3% |
| YaRN 7B (s=16) | YaRN | 64K | 64K | 64K | 96.3% |
| YaRN 7B (s=32) | YaRN | 128K | 64K | 128K | 99.4% |
| Code Llama 13B | NTK-aware | 100K | 16K | 128K | 99.4% |
| YaRN 13B (s=16) | YaRN | 64K | 64K | 64K | 97.5% |
| YaRN 13B (s=32) | YaRN | 128K | 64K | 128K | 99.4% |
The paper draws a worthwhile observation: the lowest perplexity does not reflect the “effective context length”. Code Llama 13B’s perplexity gets worse beyond 100K, yet its retrieval at 128K is still accurate; trained 200 steps more than and has similar perplexity but higher passkey accuracy. The paper therefore speculates that perplexity cannot fully measure whether a model can attend to all tokens, and it considers the model possibly undertrained on the passkey task.
Has Short-Text Ability Degraded?
To check whether extension hurts existing abilities, the paper evaluates on four benchmarks of the Hugging Face Open LLM Leaderboard (25-shot ARC-Challenge, 10-shot HellaSwag, 5-shot MMLU, 0-shot TruthfulQA) (Table 10, 7B, accuracy in %):
| Model | Window | ARC-c | HellaSwag | MMLU | TruthfulQA |
|---|---|---|---|---|---|
| Llama 2 | 4K | 53.1 | 77.8 | 43.8 | 39.0 |
| YaRN (s=16) | 64K | 52.3 | 78.8 | 42.5 | 38.2 |
| YaRN (s=32) | 128K | 52.1 | 78.4 | 41.7 | 37.3 |
| Together (PI) | 32K | 47.6 | 76.1 | 43.3 | 39.2 |
| Code Llama (NTK-aware) | 100K | 39.9 | 60.8 | 31.1 | 37.8 |
The paper concludes that YaRN degrades very little against the Llama 2 baseline, and says that the and models differ by 0.49% on average, so the loss from iteratively extending from 64K to 128K is negligible. Computing from the average of the four benchmarks in Table 3, the 7B is 0.575 points lower and the 13B 0.400 points lower, 0.4875 on average, consistent with the paper’s 0.49. The paper also says the PG19 used for fine-tuning is very different from Llama’s pretraining data, so some fluctuation is expected. Two more points when reading the table: the largest drop is on MMLU (43.8 to 41.7); and the low scores of the Code Llama row cannot be blamed on NTK-aware alone, since that model was itself trained further for code.
In the LLaMA 7B ablation (Table 2, 400 steps each, original model 51.0 / 77.8 / 35.7 / 34.3), the four methods also trade wins: YaRN is highest on HellaSwag (77.2) and TruthfulQA (35.1), NTK-by-parts is higher on ARC-c (48.5) and MMLU (32.7), and PI is lowest on ARC-c, HellaSwag and MMLU (44.8 / 70.2 / 25.9). All four methods fall below the original model’s 35.7 on MMLU, by 3.0 to 9.8 points.
Training Cost
Table 4 of the paper puts the training costs of several methods side by side (in A100 GPU hours):
| Model | Method | Extension factor | Effective context | GPU hours |
|---|---|---|---|---|
| LLaMA 7B (YaRN) | YaRN | 2K × 16 | 32K | 128 |
| Llama 2 7B (YaRN) | YaRN | 4K × 16 | 64K | 256 |
| Llama 2 7B (YaRN) | YaRN | 4K × 32 | 128K | 256 + 128 |
| Chen et al. | PI | 2K × 8 | 16K | 640 |
| Together.ai | PI | 4K × 8 | 32K | marked ”?” in the paper |
| Xiong et al. | NTK-aware | 4K × 44.2 | about 50K | 64000 |
| Code Llama | NTK-aware | 4K × 88.6 | about 100K | 6400 |
This table is only an order-of-magnitude reference: the rows differ in base model, training data, target length and training purpose, and the paper does not explain how each number was obtained.
Hands-On: Why Dynamic Scaling Must Cache the Key Before Rotation
In Section 3.4 the paper warns that when dynamic scaling is used with a KV cache, the key should be cached before rotation, because every time changes the RoPE of every token changes. The code below verifies the warning with PI-style position scaling and shows how wrong a cached, already-rotated K gets. Take a training length and a current sequence length :
import numpy as np
L, d, base = 4096, 64, 10_000.0
rng = np.random.default_rng(0)
q, k = rng.normal(size=d), rng.normal(size=d)
def rope(x, pos, s):
"""Apply RoPE to vector x at position pos, with positions scaled by s."""
ang = pos / s * base ** (-2 * np.arange(d // 2) / d)
c, sn = np.cos(ang), np.sin(ang)
out = np.empty_like(x)
out[0::2] = x[0::2] * c - x[1::2] * sn
out[1::2] = x[0::2] * sn + x[1::2] * c
return out
def scale(length): # dynamic scaling: s = max(1, current length / L)
return max(1.0, length / L)
# the effective position of each token at the moment it enters the cache: p / s
print([round(p / scale(p + 1), 1) for p in (1000, 4000, 5000, 5998)])
N = 6000 # current sequence length; the query sits at position N-1
s_now = scale(N)
qn = rope(q, N - 1, s_now)
for j in (1, 10, 100, 1000):
p = N - 1 - j # the cached key at position p was computed j steps ago
right = qn @ rope(k, p, s_now) # rotated again with the current s
stale = qn @ rope(k, p, scale(p + 1)) # reuse the stale, rotated key
off_stale = (N - 1) / s_now - p / scale(p + 1)
print(f"j={j:<4d} offset right {j / s_now:6.2f} cached {off_stale:5.2f}"
f" | logit right {right:6.2f} cached {stale:6.2f}")
# only the relative offset matters: rotating the query by the offset alone
# reproduces the last "right" value
print(np.isclose(right, rope(q, j / s_now, 1.0) @ k))
Output:
[1000.0, 4000.0, 4095.2, 4095.3]
j=1 offset right 0.68 cached 0.00 | logit right -8.82 cached -9.70
j=10 offset right 6.83 cached 0.00 | logit right -11.19 cached -9.70
j=100 offset right 68.27 cached 0.01 | logit right -5.16 cached -9.68
j=1000 offset right 682.67 cached 0.14 | logit right 6.91 cached -9.50
True
The first line is the key: once the sequence exceeds , the effective position of a token when it is written into the cache is , almost always near 4095, so every token beyond the window is pinned to the same position. The relative offset between a cached, already-rotated K and the current query is then always close to 0 (the “cached” column), while the correct offsets are 0.68, 6.83, 68.27 and 682.67 (the “right” column), and the attention logits are distorted accordingly. The last line verifies that RoPE’s logit depends only on the relative offset. This is an example with PI-style scaling; YaRN scales each dimension separately, but the reasoning is the same: whenever can change, the cache should hold the key before rotation. For how the KV cache works, see KV Cache.
Limitations and What to Watch For
- The evaluation is narrow. The paper’s main evidence is perplexity and passkey retrieval, plus four short-text benchmarks. Passkey only tests retrieving a five-digit number from meaningless text, which is not reasoning over a long document; the position of information in a long context also affects how well the model uses it, see the Lost in the Middle explainer. The paper itself points out that perplexity cannot fully characterize the effective context length.
- Beyond the window it still fails. The 64K model has perplexity above 10 at 96K and 128K windows, and the PI model from Together explodes beyond 32K.
- The temperature formula is empirical. was fitted on LLaMA, and the paper words its generality as “may be fairly universal”; and were tuned for the Llama family, and the paper stresses that these two values depend on the model.
- Comparisons with other models are not clean. Together and Code Llama in the tables are other people’s training setups, with different base models, data and target lengths.
- A notation detail. In the paper (arXiv version 3), Equation (9) in Section 2.3 writes PI as , while Appendix A.1 writes , that is ; the latter is consistent with the definition used throughout, and this post follows it.
- The base models are old. The experiments use the 2023 LLaMA and Llama 2; with newer models, every number needs to be re-verified.
What to Take Away from This Paper
- The key to extending the window is knowing how many turns each RoPE dimension makes within the training length. Dimensions that turn many times carry local relative position and must not be touched; dimensions that do not complete a turn encode absolute position and must be interpolated, not extrapolated.
- YaRN = piecewise interpolation + attention temperature. The first decides how to change the frequencies, and the second is an empirical coefficient depending on the extension factor; both touch only the precomputed RoPE tables, add no inference cost and work directly with FlashAttention, and the paper concludes that it can be a drop-in replacement for PI.
- It works without fine-tuning and works better with it. The temperature makes static scaling usable without fine-tuning, dynamic scaling leaves short text almost unaffected, and a little fine-tuning (a few hundred steps) pushes the window to 64K to 128K.
- Evaluate with both perplexity and retrieval tasks, then add your own tasks. The comparison of Code Llama and YaRN in the paper shows that the two kinds of metric can give different conclusions.
- Cache the key before rotation. Whenever changes with length, this is a correctness issue, not an optimization.
Further Reading
- The paper: YaRN: Efficient Context Window Extension of Large Language Models (this post follows arXiv version 3; the authors’ code link is in the abstract)
- Related wiki pages on this site: Long Context (four ways to change RoPE, the interactive component and code), Positional Encoding, KV Cache
- Other paper explainers in this series: DeepSeek-V3 (extends to 128K with YaRN)
- Earlier work: Extending Context Window of Large Language Models via Positional Interpolation (PI), RoFormer (RoPE), Fourier Features Let Networks Learn High Frequency Functions in Low Dimensional Domains (the theoretical basis of NTK-aware scaling), Effective Long-Context Scaling of Foundation Models (Xiong et al., which raises the base from 10,000 to 500,000 and continues training), Code Llama (an application of NTK-aware scaling)
FAQ
- How does YaRN differ from position interpolation (PI) and NTK-aware scaling?
- All three change only the rotary frequencies of RoPE, not the architecture. PI divides the frequencies of every dimension by the extension factor s, which is simple but throws away the high frequencies, the local position information between neighboring tokens. NTK-aware scaling changes the base so that high frequencies move little and low frequencies move a lot; it works without fine-tuning, but some dimensions are still extrapolated and it fine-tunes worse than PI. YaRN goes further and treats each dimension by how many turns it makes within the training length. Dimensions that turn often are left alone, those that do not complete a turn are interpolated by s, the ones in between are blended, and an attention temperature tied to ln s is added. In the paper's ablations YaRN reaches lower perplexity overall at the same number of training steps, and it also works without fine-tuning, but it is not the best at every window and on every metric.
- Where does YaRN's attention temperature 0.1·ln(s)+1 come from?
- The paper finds that introducing a temperature t into the logits before the softmax affects perplexity in a way that is essentially independent of the data sample and the position in the sequence. In practice both the cos and sin of RoPE are multiplied by √(1/t), so q and k each get one factor, the attention kernel needs no change and there is no extra cost. The recommended factor √(1/t)=0.1·ln(s)+1 was fitted on non-fine-tuned LLaMA 7B, 13B, 33B and 65B with NTK-by-parts interpolation, taking for each extension factor the value that minimizes perplexity; the paper says it also largely works for Llama 2. At s=8 the factor is about 1.208 and the logits grow by about 1.46 times overall. It is an empirical formula, so re-verify it on other models.
- Does YaRN require fine-tuning, and how much does training cost?
- Not necessarily, since it can be used with a little fine-tuning or with none at all. To take Llama 2 7B and 13B to 128K, the paper fine-tunes the s=16 model for 400 steps on PG19 text cut into 64K pieces with a global batch of 64, then trains the s=32 model for another 200 steps starting from it. By these numbers the training amounts to about 1.68B and 2.52B tokens, 0.084% and 0.126% of the Llama 2 pretraining corpus (about 2T tokens); the paper says less than about 0.1% of the original pretraining data. Without fine-tuning, Dynamic-YaRN, which adds dynamic scaling, can extrapolate the window to more than twice its original size.
- Can a model extended to 128K really use all 128K?
- The paper's evidence is perplexity and passkey retrieval. For the Llama 2 7B s=32 model, perplexity on ten 128K Proof-pile documents falls as the window grows, with 3.56, 2.70 and 2.37 at 8K, 32K and 128K. On passkey retrieval (recovering a five-digit passkey from meaningless text), the 128K 7B and 13B models both average 99.4%. The limits are also clear. The s=16 64K model has perplexity above 10 at the 96K and 128K windows, so it still fails beyond its window, and neither test is real long-document reasoning, so test it on your own tasks.
- What is dynamic scaling, and why must the KV cache store the key before rotation?
- Dynamic scaling recomputes s=max(1, l′/L) from the current sequence length l′ on every forward pass. While the sequence is no longer than the training length L, s=1 and the model is unchanged; beyond that the interpolation grows gradually, so quality degrades smoothly instead of collapsing the moment the window is exceeded. Combined with NTK-aware scaling it is called Dynamic NTK, and combined with YaRN it is Dynamic-YaRN. Because s changes at every step, the RoPE of every token changes with it, so the cache must hold the key before rotation and rotate it with the current s when it is used. If you cache the already-rotated key, every old token is pinned to an effective position of about L and the position information collapses; in this post's code experiment the relative offsets drop from tens or hundreds to nearly 0.