Positional Encoding · August 2023
YaRN — Yet Another RoPE eXtensioN
intermediate
long-contextinference-only
Extend a pretrained RoPE model's usable context far beyond the training length with only a short fine-tune, by treating fast and slow rotation bands differently.
§ 1 · Premise
RoPE’s training-length boundary
Rotary position embeddings (Su et al., 2021) rotate the -th coordinate pair of every query and key by an angle proportional to the token’s absolute position:
with base in the original RoPE recipe. The head dimension is partitioned into rotation rates that form a geometric ladder from (one radian per position) down to . During pretraining the model observes positions for some fixed — 2048 for Llama 1, 4096 for Llama 2 and DeepSeek V1, 8192 for OLMo 3. The fast dimensions ( near ) cycle through the unit circle many times across that window; the slow dimensions ( near ) traverse only a small arc.
The naive way to extend the model to context is to keep RoPE unchanged and let positions feed through directly. This fails for a frequency-specific reason that matters for the rest of the entry. The fast bands have already toured the full circle; rotating them further produces angles drawn from the same training distribution and they remain in-domain. The slow bands have only ever been rotated by small angles in ; rotating to positions feeds the model angles it has never seen, and the attention dot product between far-apart tokens collapses (Chen et al., 2023, §2; Peng et al., 2023, §3). The Position Interpolation paper attributes the failure to “high-frequency catastrophe” only in passing; the more careful YaRN analysis distinguishes it as a slow-band extrapolation problem with a fast-band aliasing problem layered on top once interpolation is applied.
Position Interpolation (Chen et al., June 2023) takes the simplest route: rescale every position by so that all rotation angles stay in the trained range. It works, but uniformly degrades the fast bands’ positional acuity — adjacent tokens that previously differed by one full radian of rotation now differ by only . The NTK-aware recipe (bloc97, July 2023; later formalized in the YaRN paper) corrects this by rescaling the base instead, which by the geometric ladder hits slow bands much harder than fast ones. NTK-aware works zero-shot up to but its band treatment is still tied to a single closed-form. YaRN’s contribution is to make the band treatment explicit: classify each dimension by its wavelength relative to the training window and apply a different rescaling per class, then correct the softmax entropy drift that any positional rescaling at long context induces.
§ 2 · Derivation
NTK-by-parts and the temperature ramp
RoPE’s frequency-band structure. Each rotation rate has an associated wavelength — the number of positions required for the -th coordinate pair to complete one full rotation. For the canonical , geometry, positions at the fastest band and at the slowest. The rotation count over training window is
A dimension with has been “saturated” — it cycled through the unit circle many times and the model saw its full rotational support. A dimension with has only ever swept a fraction of the circle. This distinction drives every later decision (Peng et al., 2023, §3.3).
Step 1: Position Interpolation as uniform stretch. PI rescales every angle by :
Every band’s wavelength stretches by . The slow bands benefit (their new angles still fall in the trained range), but the fast bands lose precision: two adjacent positions that previously had phase difference now differ by , well below the phase noise the model learned to handle. The model’s short-range positional acuity drops, which is why PI needs fine-tuning even at modest (Chen et al., 2023, Table 5).
Step 2: NTK-aware as band-dependent stretch. Replacing the base with produces
which equals at (fastest dimension untouched) and at $i = d_h/2
- 1iir_iib = 10000$ has very different saturation behavior than a 128-dimensional head with the same base; the NTK-aware rescaling treats them the same.
Step 3: NTK-by-parts. Peng et al. propose classifying dimensions by their saturation rather than their index . Define two cutoffs and on the rotation count:
- Slow band (): dimension has not saturated. Interpolate it (PI’s recipe) because extrapolating untrained angles is the failure mode.
- Fast band (): dimension has saturated. Leave it untouched. Both extrapolated and interpolated angles fall inside the trained support.
- Middle band (): smoothly blend. Define the ramp
and apply
At the original survives; at the band gets full PI rescaling; in between the band’s effective rotation rate is a linear interpolation in between the two. The paper defaults to for Llama-2 7B/13B at , which puts roughly the fastest dimension pairs in the untouched fast band, the slowest in the interpolated slow band, and the remainder in the smooth middle (Peng et al., 2023, §3.3 and Figure 2).
The “by-parts” naming makes the contrast with NTK-aware explicit: instead of a global geometric ramp tied to head index, YaRN applies a piecewise ramp tied to per-band saturation. The two schedules agree only by coincidence on specific architectures.
Step 4: Attention temperature. A second effect surfaces independently of the rescaling choice. At inference with sequence length , the attention softmax distributes mass over keys per query; the entropy of the distribution grows roughly with . The pretraining model was calibrated for entropy near . Stretching the context to without compensation leaves attention “flatter” than training — a phenomenon Peng et al. report as a measurable perplexity penalty independent of which rescaling scheme is chosen (Peng et al., 2023, §3.4 and Figure 3).
Their fix: divide attention logits by a temperature before the softmax, with chosen so the average per-query entropy matches the pretraining length. The empirically fit form is
For this gives ; for , . The constants and were fit to Llama-1 7B and reused for Llama-2 7B/13B without per-model tuning. Because attention logits are computed as , the temperature can be folded into the existing denominator: divide by at inference, equivalent to scaling the query (or key) by before the dot product. This makes the temperature correction free at inference time, in contrast to the rescaling step which is also free but requires recomputing the cosine/sine tables.
Parameter count and compute. YaRN adds zero parameters — it changes the precomputed table and a single scalar temperature. The cost at inference is the same as standard RoPE plus one multiplication per logit by . The training cost is the fine-tune itself: 400 steps at on M tokens for Llama-2 7B/13B (Peng et al., 2023, §4.1), roughly 0.1% of pretraining tokens.
§ 3 · Reference implementation
Sketch
# Shapes: d_h head dim, T_train training context, s extension factor.
# Frequencies and ramp computed once per layer at config time; applied per token.
def yarn_frequencies(d_h, base=10000.0, T_train=4096,
s=16.0, r_min=1.0, r_max=32.0):
i = arange(d_h // 2) # [d_h/2]
theta = base ** (-2 * i / d_h) # [d_h/2] original RoPE
wavelength = 2 * pi / theta # [d_h/2] λ_i
rotations = T_train / wavelength # [d_h/2] r_i
# piecewise ramp γ(r_i): 0 = preserve, 1 = interpolate
gamma = clip((r_max - rotations) / (r_max - r_min), 0.0, 1.0)
theta_yarn = (1 - gamma) * theta + gamma * (theta / s) # [d_h/2]
return theta_yarn
def yarn_temperature(s):
# 1/sqrt(t) = 0.1 ln s + 1; fold into the sqrt(d_h) denominator at inference
return (0.1 * log(s) + 1.0) ** 2
def yarn_attention(q, k, v, theta_yarn, pos, d_h, s):
# q, k, v: [B, T, H, d_h]; pos: [T]
angles = pos[:, None] * theta_yarn[None, :] # [T, d_h/2]
cos, sin = angles.cos(), angles.sin()
q = apply_rotary(q, cos, sin) # standard RoPE rotation
k = apply_rotary(k, cos, sin)
t = yarn_temperature(s) # scalar
logits = einsum("bthd,bshd->bhts", q, k) / sqrt(d_h * t) # [B, H, T, T]
return softmax(logits, dim=-1) @ v
r_max to push more dims into the smooth blend; raise the context scale to see how much the slow band gets pushed down.§ 4 · Empirical evidence
Ablations and adoption
Perplexity on PG19 and Proof-Pile. Peng et al. fine-tune Llama-2 7B and 13B for 400 steps at from a 4K base. On PG19 at the 64K evaluation point, YaRN at reaches lower perplexity than PI and the NTK-by-parts ablation (no temperature) at matched fine-tune budget; the temperature correction is the load-bearing difference between rows 4 and 5 of the paper’s Table 1. On Proof-Pile the gap widens — Peng et al. report YaRN beating PI and dynamic-NTK by roughly 0.1 perplexity points at 64K and more at 128K (Peng et al., 2023, Table 2). The temperature term contributes a consistent improvement over NTK-by-parts alone: small per token, free at inference.
Passkey retrieval. Table 3 of the paper reports near-perfect retrieval at depths through 80-100K on the Llama-2 7B 64K and 128K models, with PI dropping substantially at the deepest probe and zero-shot NTK-aware dropping further still. The discrepancy between perplexity and passkey results is non-trivial — perplexity gaps are tenths of points, retrieval gaps are tens of percentage points. The paper does not resolve this: a model can score well on average next-token prediction while still missing the specific long-range copy operation that needle-in-a-haystack measures. Later analyses (Liu et al., 2023, “Lost in the Middle”) confirm that retrieval-style probes are more sensitive to positional acuity than averaged perplexity, but the dissociation remains an open question for any RoPE extension scheme.
Adoption in production decoders. DeepSeek-V2 reports YaRN as the chosen recipe for extending its 4K-trained base to 128K, citing sample efficiency over uniformly scaled base RoPE (DeepSeek-V2, §3.3). DeepSeek-V3 keeps the same 4K → 128K YaRN extension across its 671B-parameter geometry (DeepSeek-V3, §3.4). OLMo 3 32B applies YaRN with scaling factor 8 to extend from 8K to 64K during a dedicated long-context fine-tuning stage (OLMo 3 model card). The Qwen 3 family uses YaRN combined with Dual Chunk Attention to extend beyond a 32K ABF-trained window (Qwen 3 technical report); Qwen 3-Next reportedly pushes the 262K native context to ~1M via YaRN (Qwen 3-Next model card). The gpt-oss-120b release documents YaRN scaling from a 4K base to 131K with RoPE base 150K.
Where YaRN is not used. Llama 3.1 reaches 128K context without YaRN, using long continued pretraining over a much larger token budget with a uniformly scaled RoPE base (Llama 3.1 paper, §5). The Meta team’s note is that with sufficient training tokens, simpler base scaling matches YaRN’s quality and removes the recipe complexity. This is consistent with the YaRN paper’s own framing of the method as a sample-efficient extension, not a quality ceiling — at 0.1% of pretraining tokens YaRN beats the alternatives, but the gap narrows when continued pretraining is generous.
Unresolved questions. Three are worth flagging. First, no public study isolates the temperature term’s contribution at very large (256+); the constants and were fit at moderate scales. Second, the perplexity-vs-retrieval divergence noted above means low PG19 perplexity is not a sufficient proxy for long-context recall, but no replacement metric has become standard. Third, the choice of defaults is justified by visual inspection in the paper’s Figure 2; whether other architectures need different cutoffs is not systematically studied. LongRoPE sidesteps the cutoff question by treating the per-dimension factors as a search variable, which empirically recovers non-monotone schedules YaRN cannot express — evidence that the closed-form ramp is good but not optimal at extreme extensions.
Adopted by
- DeepSeek V2 · DeepSeek-AI — YaRN used for 4K → 128K context extension. [source]
- OLMo 3 32B · Allen Institute for AI (AI2) — YaRN scaling factor 8 extends the 8K pretraining context to 64K; applied during a dedicated long-context stage (Longmino). [source]
- DeepSeek V3 · DeepSeek-AI — YaRN used for the 128K context extension from the base 4K window. [source]
- Qwen3 235B-A22B · Alibaba (Qwen Team) — YaRN + Dual Chunk Attention (DCA) for context extension beyond the ABF-trained 32K window. [source]
- Qwen3 32B · Alibaba (Qwen Team) — Same YaRN + DCA extension recipe across the Qwen 3 family. [source]
- Qwen3-Next 80B-A3B · Alibaba (Qwen Team) — YaRN extension from the 262K native context to ~1M reported by the Qwen team. [source]
Lineage
Cite
BibTeX entry for the original paper
@article{arxiv2309_00071,
title = {YaRN: Efficient Context Window Extension of Large Language Models},
author = {Bowen Peng, Jeffrey Quesnelle, Honglu Fan, Enrico Shippole},
year = {2023},
eprint = {2309.00071},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/2309.00071}
} Or cite the paper directly: arXiv:2309.00071.
Export
BibTeX
@article{arxiv_2309_00071,
title = {YaRN: Efficient Context Window Extension of Large Language Models},
author = {Bowen Peng and Jeffrey Quesnelle and Honglu Fan and Enrico Shippole},
year = {2023},
eprint = {2309.00071},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/2309.00071}
} CSL JSON
{
"id": "arxiv_2309_00071",
"type": "article-journal",
"title": "YaRN: Efficient Context Window Extension of Large Language Models",
"author": [
{
"literal": "Bowen Peng"
},
{
"literal": "Jeffrey Quesnelle"
},
{
"literal": "Honglu Fan"
},
{
"literal": "Enrico Shippole"
}
],
"issued": {
"date-parts": [
[
2023
]
]
},
"URL": "https://arxiv.org/abs/2309.00071",
"number": "2309.00071",
"source": "arXiv"
} RIS
TY - JOUR
TI - YaRN: Efficient Context Window Extension of Large Language Models
AU - Bowen Peng
AU - Jeffrey Quesnelle
AU - Honglu Fan
AU - Enrico Shippole
PY - 2023
JO - arXiv
AN - arXiv:2309.00071
UR - https://arxiv.org/abs/2309.00071
ER -