Search

Search papers and lessons

YaRN: Efficient Context Window Extension of Large Language Models

Bowen Peng, Jeffrey Quesnelle, Honglu Fan et al. · 2023

YaRN stretches the rotary position frequencies of a pretrained model unevenly and rescales attention by a fixed temperature, so LLaMA-family models read contexts far longer than they were trained on.

On this page

  • Colour = topic mix
  • Calculus
  • Discrete math
  • Linear algebra
  • Neural network basics
  • Architectures
  • Probability
  • ReadReady to readNot yet

TL;DR

A transformer trained on 4,096-token windows usually breaks on much longer inputs, because its rotary position embeddings meet rotation angles it never saw in training. YaRN fixes this by stretching each rotation frequency by a different amount: fast dimensions are left alone, slow dimensions are interpolated, and the attention logits are scaled by one fixed temperature. The paper reports that LLaMA 2 models extended this way read 128k-token contexts after fine-tuning on less than about 0.1 percent of the original pretraining data.

Builds on: Rotary Position Embedding, Position Interpolation, Softmax Temperature · Leads to: Llama 2, the base models it extends, and FlashAttention-2, the attention kernel the paper's training used

Why it mattered

Many open models of 2023 were trained on short windows, then needed to read whole books and codebases. Extending a window by retraining from scratch is expensive, so the question was how to stretch the position encoding of a model that already works. YaRN is a recipe for that stretch, and the paper gives it a cost comparison as well as quality results.

The paper's Table 4 lists training time in A100 GPU-hours. Extending LLaMA with YaRN to a 32k window used 128 GPU-hours. Earlier Position Interpolation work reported 640 GPU-hours for a 16k window. The abstract claims YaRN needs 10 times fewer tokens and 2.5 times fewer training steps than previous methods.

Methods from the same family were already in use when the paper appeared. The paper notes that Code Llama used NTK-aware interpolation, and that Qwen 7B used Dynamic NTK at inference. YaRN is the paper's account of these methods and of a combination that the authors found works best.

The problem

Rotary position embedding (RoPE) turns each pair of hidden dimensions into a complex number and rotates it by an angle that grows with the token's position. Dimension dd has a frequency θd=b−2d/∣D∣\theta_d = b^{-2d/|D|}, with base b=10000b = 10000, so each dimension rotates at its own speed. The attention score between two tokens depends only on the distance between them, which is why RoPE is called a relative encoding.

In theory, that should let a model handle longer distances than it saw. In practice it does not, and the paper gives the reason. For a training window of length LL, some dimensions have a wavelength longer than LL. Those dimensions never complete a full turn during training, so the angle at each position is unique in them, and they carry absolute position information. A longer input moves those dimensions to angles the model has never seen.

The earlier fix, Position Interpolation, divides every position by a scale ss so the longest input maps back into the trained range. It works, but it squeezes every dimension equally. That removes the high-frequency detail that tells nearby tokens apart. The paper reports that earlier fine-tunes using Position Interpolation could reach a scale of about 8 before outputs degraded, even after training. "NTK-aware" scaling changes the base instead, which spreads the squeeze over several dimensions, but the best base has to be found by trial for each extension.

How it works

We trace the method for a model trained on L=4096L = 4096 tokens that must read L′=16384L' = 16384 tokens, so the scale is s=L′/L=4s = L'/L = 4. Three dimensions illustrate the three regimes. Their wavelengths are λ=2π/θ\lambda = 2\pi/\theta: dimension A has λ=8192\lambda = 8192, dimension B has λ=512\lambda = 512 and dimension C has λ=64\lambda = 64.

  1. Count the rotations in the training window. For each dimension compute r=L/λr = L/\lambda, the number of turns it makes over the training length. A has r=4096/8192=0.5r = 4096/8192 = 0.5, B has r=4096/512=8r = 4096/512 = 8 and C has r=4096/64=64r = 4096/64 = 64. Check: A never completes a turn in training, B makes eight, C makes 64.
  2. Choose a regime from rr. The ramp γ(r)\gamma(r) is 0 when rr is below α=1\alpha = 1, meaning the dimension is fully interpolated. It is 1 when rr is above β=32\beta = 32, meaning it is left alone. In between it moves smoothly. A gets γ=0\gamma = 0, B gets γ=(8−1)/(32−1)=0.226\gamma = (8 - 1)/(32 - 1) = 0.226 and C gets γ=1\gamma = 1. Check: each γ\gamma lies between 0 and 1.
  3. Compute the new frequency. The new frequency is h(θ)=(1−γ) θ/s+γ θh(\theta) = (1 - \gamma)\,\theta/s + \gamma\,\theta. For A it is θ/4=0.000192\theta/4 = 0.000192. For B it is 0.774×0.012272/4+0.226×0.012272=0.0051460.774 \times 0.012272/4 + 0.226 \times 0.012272 = 0.005146. For C it is unchanged, 0.0981750.098175. Check: a fully interpolated frequency is exactly ss times smaller, and an untouched one is the same as before.
  4. Check A stays inside what it saw. A's new wavelength is 4×8192=327684 \times 8192 = 32768. At position 16,384 its angle is (2π/32768)×16384=π(2\pi/32768) \times 16384 = \pi, which is the largest angle A reached during training. Check: the stretched dimension does not leave the trained range.
  5. Rescale attention by a temperature. The paper scales the logits by 1/t1/t, where 1/t=0.1ln⁡s+1\sqrt{1/t} = 0.1 \ln s + 1. For s=4s = 4, 1/t=1.1386\sqrt{1/t} = 1.1386, so 1/t=1.29651/t = 1.2965 and every query-key score is multiplied by about 1.30 before the softmax. Check: the scale grows with ss, so longer extensions sharpen attention more.

The flow of the method is shown below.

flowchart LR
  T["Trained window L and target L prime"] --> S["Scale s = L prime over L"]
  S --> R["For each dimension: r = L over wavelength"]
  R --> G["Ramp gamma(r): 0 interpolate, 1 keep"]
  G --> H["New frequency h(theta)"]
  H --> A["Attention logits times 1 over t"]
  A --> O["Model reads L prime tokens"]

The math

Definition: YaRN

YaRN is the combination of two changes to a RoPE model: the "NTK-by-parts" interpolation, which chooses a frequency for each dimension from its ratio of rotations to the training length, and a constant temperature tt that multiplies the attention logits. Both are applied once, before inference, so they add no cost at run time.

Keep the setup from the trace. The query and key of a token at position mm are rotated in complex coordinates by eimθde^{im\theta_d} in dimension dd. The interpolation methods in the paper all have the form f(xm,g(m),h(θ))f(x_m, g(m), h(\theta)), where gg changes the position and hh changes the frequency. For NTK-by-parts, g(m)=mg(m) = m.

Step 1 in symbols: the ratio of rotations

r(d)=Lλd=L2π b2d/∣D∣r(d) = \frac{L}{\lambda_d} = \frac{L}{2\pi\, b^{2d/|D|}}

Here LL is the training length, λd\lambda_d is the wavelength of dimension dd, bb is the base and ∣D∣|D| is the number of hidden dimensions. For the trace, r(A)=0.5r(A) = 0.5.

Step 2 in symbols: the ramp

γ(r)={0,r<α1,r>βr−αβ−α,otherwise\gamma(r) = \begin{cases} 0, & r < \alpha \\ 1, & r > \beta \\ \dfrac{r - \alpha}{\beta - \alpha}, & \text{otherwise} \end{cases}

The paper finds α=1\alpha = 1 and β=32\beta = 32 good for the LLaMA family, and says these values should be tuned for each model.

Step 3 in symbols: the new frequency

h(θd)=(1−γ(r(d)))θds+γ(r(d)) θdh(\theta_d) = \left(1 - \gamma(r(d))\right)\frac{\theta_d}{s} + \gamma(r(d))\,\theta_d

When γ=0\gamma = 0 this is pure Position Interpolation for that dimension. When γ=1\gamma = 1 the dimension keeps its original frequency. The paper notes that a harmonic mean, or a linear ramp over wavelengths, would also work.

Step 4 in symbols: the temperature

softmax⁡(qmTknt∣D∣),1t=0.1ln⁡s+1\operatorname{softmax}\left(\frac{\mathbf{q}_m^T \mathbf{k}_n}{t \sqrt{|D|}}\right), \qquad \sqrt{\frac{1}{t}} = 0.1 \ln s + 1

The paper finds the second relation by fitting the lowest perplexity of LLaMA 7B, 13B, 33B and 65B models without fine-tuning. Because the rotary embeddings are complex, the scale can be applied to both q\mathbf{q} and k\mathbf{k} by multiplying them by 1/t\sqrt{1/t}, so the attention code does not change. For s=16s = 16 this gives 1/t=1.2773\sqrt{1/t} = 1.2773 and 1/t=1.63141/t = 1.6314.

Dynamic scaling

At inference the scale can instead be set per forward pass as s=max⁡(1,l′/L)s = \max(1, l'/L), where l′l' is the length of the current sequence. The paper says this lets a model degrade gracefully instead of breaking at the trained limit. It also warns that the key-value cache must store keys before the rotary embedding is applied, because the rotation of every cached token changes when ss changes.

Worked examples

Example
1. Tiny: three dimensions, one ramp each

Use L=4096L = 4096, s=4s = 4 and θ=0.1\theta = 0.1 for every dimension, with α=1\alpha = 1 and β=32\beta = 32.

  1. A dimension with r=0.5r = 0.5: γ=0\gamma = 0, so h=θ/s=0.1/4=0.025h = \theta / s = 0.1 / 4 = 0.025.
  2. A dimension with r=64r = 64: γ=1\gamma = 1, so h=θ=0.1h = \theta = 0.1.
  3. A dimension with r=8r = 8: γ=(8−1)/(32−1)=0.2258\gamma = (8 - 1)/(32 - 1) = 0.2258, so h=0.7742×0.025+0.2258×0.1=0.01935+0.02258=0.04194h = 0.7742 \times 0.025 + 0.2258 \times 0.1 = 0.01935 + 0.02258 = 0.04194.

Interpretation: the slow dimension is divided by 4 completely, the fast one is untouched, and the middle one lands between the two, in proportion to how many turns it made in training.

Example
2. Standard: the temperature for a 16x extension

A LLaMA-style model is extended to s=16s = 16.

  1. Compute the square-root factor: 0.1ln⁡16+1=0.1×2.7726+1=1.27730.1 \ln 16 + 1 = 0.1 \times 2.7726 + 1 = 1.2773.
  2. Square it to get 1/t1/t: 1.27732=1.63141.2773^2 = 1.6314.
  3. Each attention logit qmTkn/∣D∣\mathbf{q}_m^T \mathbf{k}_n / \sqrt{|D|} is multiplied by 1.63141.6314 before the softmax.
  4. Check: the factor is larger than 1, so the softmax becomes sharper, which the paper relates to the increased entropy of attention over long inputs.

Interpretation: the temperature is a single number chosen from the scale, not tuned per model, and it counters the flattening that a long window causes.

Example
3. Realistic: perplexity at a 128k window

Table 1 of the paper reports sliding-window perplexity on ten 128k Proof-pile documents, where lower is better. For the 13B model extended with s=32s = 32 (400 steps, then 200 more), the values are 3.29 at 8,192 tokens, 2.83 at 16,384, 2.53 at 32,768, 2.31 at 65,536 and 2.24 at 131,072. For the 7B model at s=16s = 16, the value at 131,072 is reported as above 10.

  1. Compare the 13B model at 8,192 tokens (3.29) with 131,072 tokens (2.24). The model predicts the text better when given more of it.
  2. The drop is 3.29−2.24=1.053.29 - 2.24 = 1.05 perplexity points.
  3. The 7B model at s=16s = 16 does not manage the full 128k window: its value is above 10, far higher than every other entry in the table, so this is a clear failure rather than a small loss.
  4. The paper says the s=32s = 32 model was only trained on 64k data and still reaches 128k, which is the transfer result it highlights.

Interpretation: the perplexity table shows that extension can work at the full target length, and that the scale choice can matter a great deal. The table is for the paper's own evaluation, not a general claim about all long tasks.

Try it: use the 7B model with s=32s = 32 in the same table. Its values are 3.56 at 8,192 tokens and 2.37 at 131,072. What is the drop in perplexity between those two lengths, and what percentage of the 8,192-token value is it, to one decimal place? Answer: the drop is 3.56−2.37=1.193.56 - 2.37 = 1.19, and 1.19/3.56≈0.3341.19 / 3.56 \approx 0.334, so about 33.4 percent.

Results

The paper evaluates on long-sequence perplexity, passkey retrieval and the Open LLM Leaderboard tasks, and compares YaRN with Position Interpolation, NTK-aware and NTK-by-parts scaling.

  • Long-sequence perplexity (Table 1). The 13B model at s=16s = 16 has 3.25 at 8,192 tokens and 2.29 at 65,536. At s=32s = 32 it reaches 2.24 at 131,072. The paper highlights transfer from 64k training data to 128k: the s=32s = 32 models were trained for 200 steps beyond the s=16s = 16 models and still reach 128k.
  • Ablation at 32k (Figure 3 and Appendix B.1). For the 7B model, fine-tuned for 400 steps with the same budget, YaRN has lower perplexity and higher passkey accuracy than the other interpolation methods. Figure 2 plots the training-loss curves of the same interpolation methods.
  • Short-context benchmarks (Table 2 and Table 3). For the 7B LLaMA model extended with s=16s = 16, YaRN's MMLU score is 30.0, against 25.9 for PI, 27.7 for NTK-aware, 32.7 for NTK-by-parts and 35.7 for the unextended model. For Llama 2 models, YaRN loses little: the 7B model's ARC-c score goes from 53.1 to 52.3 at s=16s = 16.- Cost (Table 4). A LLaMA model extended to 32k with YaRN used 128 A100 GPU-hours. The Position Interpolation entry in the table is 640 GPU-hours for 16k.

Limits. The results are fine-tuned on PG19, a book corpus, which the paper says differs from the original pretraining data. The 7B model at s=16s = 16 fails at 128k in Table 1. The paper's best α\alpha, β\beta and temperature were found for the LLaMA and Llama 2 families, and the paper says they should be tuned for other models. The paper does not claim that long contexts are used well on every task; its tests are perplexity, passkey retrieval and short benchmarks.

Common mistakes and tradeoffs

It is tempting to think that a longer context is free once the position numbers are scaled. In fact the model must be trained or at least shown the new angles, and the paper's own unfine-tuned results depend on the scale and temperature, with the best settings found by fitting.

It is tempting to think that scaling every frequency by the same factor is the natural method. In fact that squeezes the fast dimensions too, which removes the detail that separates nearby tokens. YaRN leaves those dimensions alone and interpolates only the slow ones.

It is tempting to think that the temperature is a minor tweak. In fact the paper found that a temperature on the logits has a uniform effect on perplexity across positions and samples, which is why a single formula for the scale works.

Use YaRN when a RoPE model must read much longer inputs and a small amount of fine-tuning or a dynamic scale is affordable. Do not expect it to add reasoning ability, and check the perplexity at the length you need, since the paper shows one size that fails. Alternatives include plain Position Interpolation for small scales, NTK-aware scaling with a tuned base, and retrieval or chunking when the task allows it.

History

Transformers used absolute sinusoidal positions in 2017, then learned absolute positions, then relative schemes such as RoPE in 2021. The paper notes that these encodings fail to generalise past the sequence length they were trained on. Position Interpolation in 2023 showed that squeezing positions back into the trained range extends the window with fine-tuning, but only up to a scale of about 8. The "NTK-aware" idea came from the neural tangent kernel view of learning high frequencies, and it was shared as blog posts and code before this paper. YaRN collected those unpublished methods, explained them, and added the temperature and the ramp that combines them.

Recap

  • RoPE encodes position as rotations, and some dimensions never complete a turn during training, so long inputs push them to unseen angles.
  • Position Interpolation squeezes every frequency equally, which loses the high-frequency detail that separates nearby tokens.
  • NTK-by-parts interpolates slow dimensions and leaves fast ones alone, with a ramp between them controlled by r=L/λr = L / \lambda.
  • A temperature 1/t=0.1ln⁡s+1\sqrt{1/t} = 0.1 \ln s + 1 rescales attention logits, and it is applied as a scale on the rotary embeddings.
  • Read next: Neural Tangent Kernel: Convergence and Generalization in Neural Networks for the kernel view behind the high-frequency argument, and Llama 2: Open Foundation and Fine-Tuned Chat Models for the models the paper extends.

Reading guide

Check yourself

QuestionWhy does a RoPE model fail on inputs longer than its training window, and why does Position Interpolation alone not fix the problem well?Show answer

Some dimensions have wavelengths longer than the training window, so they never complete a turn in training, and longer inputs push them into angles the model has never seen. Position Interpolation fixes this by dividing all positions by the scale, but it squeezes every dimension equally, which removes the high-frequency detail that distinguishes nearby tokens and limits the usable scale.

QuestionA model is trained on 4,096 tokens and extended to 16,384 tokens, so s = 4. A dimension has wavelength 8192. What is its ratio r, and which regime does it fall in?Show answer

The ratio is r = 4096 / 8192 = 0.5. Since r is below alpha = 1, the ramp gives gamma = 0, so the dimension is fully interpolated: its frequency is divided by 4.

QuestionCompute the attention temperature factor 1/t for a scale of s = 8. Use sqrt(1/t) = 0.1 ln s + 1, and round to three decimals.Show answer

ln 8 is about 2.0794, so sqrt(1/t) = 0.1 times 2.0794 plus 1, which is 1.20794. Squaring gives 1/t = 1.4591, so about 1.459. Each attention logit is multiplied by this factor before the softmax.

QuestionIn the 13B model of Table 1, the perplexity at 131,072 tokens is 2.24 and at 8,192 tokens is 3.29. Why might a reader be cautious about saying the model handles any long task equally well?Show answer

The table measures sliding-window perplexity on Proof-pile documents, which shows that the model predicts text better with more context. It does not show performance on other long tasks, and the same paper reports that the 7B model at s = 16 fails at 131,072 tokens, so the result depends on the model and the scale.

Sources

Read the full paper

Bowen Peng, Jeffrey Quesnelle, Honglu Fan et al., 2023. arXiv:2309.00071