AI Logic

Positional Encodings

YaRN

Updated:

How YaRN works. Left: the flow of an attention layer. As in RoPE, queries and keys are rotated, but the rotation speed is scaled per pair and multiplied by √(1/t) before the scores are computed. Top right: the per-pair rotation-speed ratio when extending LLaMA 7B by 16×. RoPE stays at 1×, Position Interpolation is 1/16× for all pairs, and YaRN keeps the fast pairs 0–16 at 1×, sets pairs 41 and above to 1/16×, and connects them smoothly in between. Bottom right: √(1/t) = 0.1 ln s + 1 as a function of the extension factor s, 1.208 at s = 8 and 1.277 at s = 16

What is YaRN?

YaRN (Yet another RoPE extensioN method) extends the context window of a pretrained language model that uses RoPE. It scales the rotation angle differently for each dimension pair and also adjusts the temperature of the attention scores. It was proposed in 2023 by Peng, Quesnelle, Fan, and Shippole. The authors extended the context of Llama 2 from 4096 to 128k (131072) tokens and report that fine-tuning needed 10× fewer tokens and 2.5× fewer steps than previous methods.

The earlier Position Interpolation uniformly scales position indices by 1/s1/s (where s=L′/Ls = L'/L is the extension factor). This is equivalent to slowing down the rotation of every RoPE pair by the same amount. The YaRN paper points out two problems with this uniform scaling.

  • It also scales the fast-rotating pairs: The fast-rotating pairs encode the fine-grained order of adjacent words. Slowing them down makes it harder to distinguish the order of nearby words.
  • Attention becomes blurred over long contexts: Extending the context changes the distribution of attention scores. The paper found that scaling the scores by a constant factor before the softmax lowers perplexity uniformly.

YaRN leaves the fast-rotating pairs unchanged, scales only the slow-rotating pairs by 1/s1/s as in Position Interpolation, and connects the two smoothly in between (an interpolation called NTK-by-parts). Combined with the temperature adjustment of the scores, this is YaRN.

The left side of the figure at the top of this article shows where positional information is injected. It has the same layout as the figures in the RoPE and Position Interpolation articles; only the scaling of the rotation angle and the factor applied to queries and keys differ. The top right shows the per-pair rotation-speed ratio, computed in the same frame as for Position Interpolation. The bottom right shows the size of the temperature adjustment for each extension factor.

Theory (grouping pairs by wavelength and scaling them differently)

The explanation follows the equations in Sections 2–3 of the paper. Let LL be the pretraining context length, L′L' the target length, s=L′/Ls = L'/L the extension factor, and ∣D∣|D| the head dimension. RoPE rotates the dd-th pair by the angle mθdm\theta_d (θd=b−2d/∣D∣\theta_d = b^{-2d/|D|}, b=10000b = 10000).

  1. For each pair, compute the number of tokens needed for one full rotation (the wavelength) λd\lambda_d.
  2. Compute how many rotations the pair completes over the training length LL: r(d)=L/λdr(d) = L / \lambda_d.
  3. Choose how to scale the rotation speed θd\theta_d according to r(d)r(d). Pairs with r(d)>βr(d) > \beta (many rotations) are left unchanged, pairs with r(d)<αr(d) < \alpha (less than one rotation over LL) become θd/s\theta_d / s as in Position Interpolation, and pairs in between mix the two linearly.
  4. Divide the pre-softmax scores by a temperature tt. In practice, both queries and keys are multiplied by 1/t\sqrt{1/t}.
  5. Fine-tune briefly on data at the extended length (400 steps in the paper).

Steps 1 and 2 are the following equations (Eqs. (8) and (10) in the paper).

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

The mixing in step 3 is expressed with a ramp function γ\gamma that goes from 0 to 1 (Eqs. (11) and (13)). Position indices are kept as they are (g(m)=mg(m) = m); only the rotation speed changes.

γ(r)={0(r<α)1(r>β)r−αβ−α(otherwise)h(θd)=(1−γ(r(d)))θds+γ(r(d)) θd\gamma(r) = \begin{cases} 0 & (r < \alpha) \\ 1 & (r > \beta) \\ \dfrac{r - \alpha}{\beta - \alpha} & (\text{otherwise}) \end{cases} \qquad h(\theta_d) = \bigl(1 - \gamma(r(d))\bigr)\frac{\theta_d}{s} + \gamma(r(d))\,\theta_d

For the LLaMA family, α=1\alpha = 1 and β=32\beta = 32 are recommended. The top right of the figure at the top of this article shows h(θd)/θdh(\theta_d)/\theta_d when LLaMA 7B (L=2048L = 2048, ∣D∣=128|D| = 128) is extended with s=16s = 16. The fast pairs 0–16 stay at 1×, pairs 41 and above are at 1/161/16× as in Position Interpolation, and the pairs in between are connected smoothly.

The temperature in step 4 changes the attention weights as follows (Eqs. (14) and (15)).

softmax ⁣(qm⊤knt∣D∣),1t=0.1ln⁡s+1\mathrm{softmax}\!\left(\frac{q_m^\top k_n}{t\sqrt{|D|}}\right), \qquad \sqrt{\frac{1}{t}} = 0.1 \ln s + 1

For s=16s = 16, 1/t≈1.277\sqrt{1/t} \approx 1.277. This formula was obtained by finding, for each extension factor, the 1/t\sqrt{1/t} that gives the lowest perplexity without fine-tuning on LLaMA 7B–65B, and fitting a curve to the results. The authors state that it also fits Llama 2 well.

If 1/t\sqrt{1/t} is folded into RoPE's cos⁡\cos and sin⁡\sin tables, it is automatically applied to both queries and keys. The attention code stays unchanged, and since the cos⁡\cos and sin⁡\sin tables are precomputed and reused, there is no extra computation in training or inference. This makes it directly compatible with FlashAttention-2 and similar kernels.

Why scale each pair differently?

RoPE encodes relative positions, but the paper argues that in practice different pairs carry different kinds of information. Think of a clock with a second hand, a minute hand, and an hour hand.

  • Fast-rotating pairs (second hand): They rotate dozens of times over the training length LL, so their angle only reveals short relative distances, i.e., how many words apart two tokens are. They are essential for telling the order of adjacent words apart, so they are kept unscaled. Scaling them as in Position Interpolation shrinks the angle difference between neighbors to 1/s1/s and makes nearby order hard to distinguish.
  • Slow-rotating pairs (hour hand): They complete less than one rotation over LL (λ>L\lambda > L), so the angle from the start is unique for each position and also serves as a cue for absolute position. On long inputs they would reach angles never seen during training, so they are always scaled (interpolated) to stay within the trained range.
  • Pairs in between (minute hand): They have a bit of both properties, so the two scalings are mixed.

YaRN was reached through a series of incremental improvements.

MethodHow the rotation speed changesCharacteristics
Position InterpolationAll pairs scaled by 1/s1/sSimple, but loses information in the fast pairs. According to the paper, output starts to break down around s=8s = 8 even with fine-tuning
NTK-awareChanges the RoPE base bb to $b' = b \cdot s^{D
NTK-by-partsGroups pairs by wavelength and switches the scaling with γ\gamma aboveAvoids extrapolation while keeping the fast pairs
YaRNNTK-by-parts + temperature adjustment of the scoresIn the paper's comparison, the lowest perplexity on long contexts (8192 and above), with or without fine-tuning

As for why the temperature adjustment works, the paper reports in its appendix that a suitable tt lowers perplexity across the whole extended context, and that the optimal tt is nearly the same regardless of document or position. Since 1/t>1\sqrt{1/t} > 1, the scores are enlarged by a factor of 1/t1/t and the attention weights become slightly sharper.

Experimental results

Comparison with other interpolation methods (Table 5 in the appendix): Perplexity (lower is better) of LLaMA 7B (pretraining length 2048) extended with s=16s = 16 (32k), evaluated on 10 long documents from Proof-pile, a dataset of mathematical proofs. The original model scores 4.05 at length 2048.

MethodFine-tuning204881921638432768
Position InterpolationNone> 100> 100> 100> 100
YaRNNone4.614.183.663.45
Position Interpolation400 steps5.704.643.973.57
NTK-aware400 steps4.393.733.218.49
NTK-by-parts400 steps4.143.623.122.81
YaRN400 steps4.193.303.092.77

Without fine-tuning, Position Interpolation with s=16s = 16 broke down, while YaRN kept perplexity low up to 32768. With the same 400 steps of fine-tuning, YaRN achieved the best values on long contexts.

Extension to 128k and extrapolation (Table 1): Models obtained by extending Llama 2 (pretraining length 4096). The s=32s = 32 models were trained for only 200 more steps on 64k-length data, starting from the s=16s = 16 models.

ModelFactor81923276865536131072
7Bs=16s = 16 (64k)3.512.652.42> 10
7Bs=32s = 32 (128k)3.562.702.452.37
13Bs=16s = 16 (64k)3.252.502.29> 10
13Bs=32s = 32 (128k)3.292.532.312.24

The s=32s = 32 models kept improving in perplexity even at 128k, longer than the training data (64k). On the passkey retrieval task (retrieving a 5-digit number hidden in a long text), the 7B and 13B models extended to 128k achieved over 99% accuracy across the whole range up to 128k (Appendix B.5).

Performance on short contexts (Tables 2 and 3): Four benchmarks from the Hugging Face Open LLM Leaderboard. In the comparison of LLaMA 7B extended with s=16s = 16, YaRN preserved the original model's performance better than Position Interpolation.

ModelARC-cHellaSwagMMLUTruthfulQA
Original LLaMA 7B51.077.835.734.3
Position Interpolation (s=16s = 16)44.870.225.934.1
YaRN (s=16s = 16)48.177.230.035.1

For Llama 2 7B, the drop after extending to 128k was small: ARC-c went from 53.1 to 52.1 and MMLU from 43.8 to 41.7.

Training efficiency (Tables 6 and 4 in the appendix): In the comparison of extending Llama 2 7B to 8192, YaRN reached almost the same perplexity in 400 steps as Position Interpolation did in 1000 steps (3.35 vs. 3.34 at 8192).

Practical considerations

α\alpha, β\beta, and the temperature formula 1/t=0.1ln⁡s+1\sqrt{1/t} = 0.1 \ln s + 1 are values determined by experiments on LLaMA and Llama 2. The paper states that α\alpha and β\beta should be tuned per model. For other model families they may not work as is, so verify them first, for example with perplexity without fine-tuning.

Keep the following points in mind as well.

  • Sudden breakdown beyond the extended length: A model extended to 64k with s=16s = 16 exceeded a perplexity of 10 at 128k. Choose the factor to match the maximum length to be used.
  • The factor can also change at inference time: The paper also presents Dynamic Scaling, which sets s=max⁡(1,l′/L)s = \max(1, l'/L) for each input length l′l'. It prevents the sudden breakdown beyond the training length even in models without fine-tuning. However, when a KV cache is used, keys and values must be cached before RoPE is applied, because changing ss changes the rotation of every token.
  • Also check performance at the original length: The drop is smaller than with Position Interpolation, but depending on the fine-tuning data (the book dataset PG-19 in the paper), benchmark scores may decrease slightly.

In Hugging Face Transformers, YaRN is enabled by passing {"type": "yarn", "factor": s} as rope_scaling in the config. The defaults match the paper: β=32\beta = 32 (beta_fast), α=1\alpha = 1 (beta_slow), and a temperature of 0.1ln⁡s+10.1 \ln s + 1. Note, however, that this implementation makes the ramp linear in the pair index dd rather than in rr (the paper also notes that other ramp shapes are possible).

Comparison with other positional encodings

YaRN is not a new positional encoding but a method for extending the context of a pretrained RoPE model. The table compares it with other positional encodings in terms of how they handle sequences longer than those seen in training.

MethodWhere position is injectedLearned parametersSequences longer than the training lengthTypical use
Learned positional embeddingAdded to the input embeddings (once)Yes (Lmax⁡×dL_{\max} \times d)Cannot be representedBERT, GPT
RoPERotates queries and keys in each layer by an angle proportional to positionNoneOnly slightly longerLLaMA and others
Position InterpolationSame as RoPE, with positions scaled by 1/s1/s before rotationNone (short fine-tuning)Maps up to L′L' into the trained rangeExtending the context of a pretrained RoPE model
YaRN (this article)Same as RoPE, with per-pair scaling and a temperature on the scoresNone (short fine-tuning)Extends to L′L' and extrapolated beyond the fine-tuning data lengthExtending the context of a pretrained RoPE model by a large factor
ALiBiSubtracts a penalty proportional to distance from the scores in each layerNoneTends to preserve accuracyWhen long sequences are planned from pretraining
  • To extend the context of a pretrained RoPE model by tens of times with little compute, YaRN is a good fit. In the paper's comparison, with the same amount of fine-tuning, it achieved lower perplexity on long contexts (8192 and above) than Position Interpolation, NTK-aware, and NTK-by-parts.
  • For small factors (around 2–4×) where simplicity matters most, Position Interpolation may be enough. The only setting is the factor itself.
  • Methods aiming at even longer contexts have also been proposed, such as LongRoPE, which searches for per-pair scaling.

PyTorch example

Show code
python
import math
import torch


def yarn_inv_freq(d: int, L: int, s: float, base: float = 10000.0,
                  alpha: float = 1.0, beta: float = 32.0) -> torch.Tensor:
    """YaRN rotation speed h(θ_j) (Eqs. (8), (10), (11), (13) in the paper)"""
    theta = base ** (-torch.arange(0, d, 2).float() / d)       # θ_j = b^(-2j/|D|)
    wavelength = 2 * math.pi / theta                             # λ_j
    r = L / wavelength                                           # Rotations over the training length L
    gamma = ((r - alpha) / (beta - alpha)).clamp(0.0, 1.0)       # 0 if r < α, 1 if r > β
    return (1 - gamma) * theta / s + gamma * theta               # Slow pairs: θ/s, fast pairs: θ unchanged


def yarn_cos_sin(seq_len: int, d: int, L: int, s: float):
    inv_freq = yarn_inv_freq(d, L, s)
    angle = torch.arange(seq_len).float()[:, None] * inv_freq    # Position indices unchanged (g(m) = m)
    mscale = 0.1 * math.log(s) + 1.0                             # √(1/t) (Eq. (15))
    cos = angle.cos().repeat_interleave(2, dim=-1) * mscale      # Folding it into cos/sin applies it to both q and k
    sin = angle.sin().repeat_interleave(2, dim=-1) * mscale
    return cos, sin


def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
    x1, x2 = x[..., 0::2], x[..., 1::2]
    rotated = torch.stack((-x2, x1), dim=-1).flatten(-2)
    return x * cos + rotated * sin


L, s, d = 2048, 16, 128                                          # Extend LLaMA 7B by 16x (32k)
ratio = yarn_inv_freq(d, L, s) / (10000.0 ** (-torch.arange(0, d, 2).float() / d))
print(ratio[:3], ratio[-3:])                                     # Fast pairs: 1.0, slow pairs: 0.0625 (= 1/16)

B, h, n = 1, 8, 4096
q, k, v = (torch.randn(B, h, n, d) for _ in range(3))
cos, sin = yarn_cos_sin(n, d, L, s)
q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin)          # Scores are scaled by 1/t
out = torch.nn.functional.scaled_dot_product_attention(q, k, v, is_causal=True)
print(out.shape)                                                 # torch.Size([1, 8, 4096, 128])

# In Hugging Face Transformers, a config setting is enough (then fine-tune briefly)
# model = AutoModelForCausalLM.from_pretrained(name, rope_scaling={"type": "yarn", "factor": 16.0})

FAQ

Q. Should I use YaRN or Position Interpolation?
A.

The larger the factor, the greater YaRN's advantage. In the paper's comparison (LLaMA 7B extended 16×), Position Interpolation without fine-tuning broke down while YaRN kept perplexity low, and with the same 400 steps of fine-tuning YaRN also scored better. The implementation effort is about the same, and the paper describes YaRN as a "drop-in replacement" for Position Interpolation.

Q. Can it be used without fine-tuning?
A.

To some extent. In the comparison of LLaMA 7B extended 16×, perplexity at 32768 was 3.45 even without fine-tuning. The paper also states that combining it with Dynamic Scaling, which adjusts the factor to the input length, extended the context by more than 2× without fine-tuning. The best results, however, come with fine-tuning.

Q. What does the temperature $t$ do?
A.

It divides the pre-softmax scores by tt, adjusting how sharp the attention weights are. Since 1/t=0.1ln⁡s+1\sqrt{1/t} = 0.1 \ln s + 1 is greater than 1, the scores become larger and the weights slightly sharper. The paper showed that a suitable tt lowers perplexity across the whole extended context, regardless of document or position. In practice, it only requires multiplying RoPE's cos⁡\cos and sin⁡\sin by 1/t\sqrt{1/t}.

References

  1. B. Peng, J. Quesnelle, H. Fan, and E. Shippole, "YaRN: Efficient Context Window Extension of Large Language Models," arXiv:2309.00071, 2023.
  2. S. Chen, S. Wong, L. Chen, and Y. Tian, "Extending Context Window of Large Language Models via Position Interpolation," arXiv:2306.15595, 2023.
  3. J. Su, Y. Lu, S. Pan, A. Murtadha, B. Wen, and Y. Liu, "RoFormer: Enhanced Transformer with Rotary Position Embedding," arXiv:2104.09864, 2021.
  4. Hugging Face Transformers, modeling_rope_utils.py (_compute_yarn_parameters)