Özer Cem KELAHMETKELAHMET
Articles · Concepts

Extending context windows with RoPE scaling: position interpolation, NTK, YaRN and Llama 3

A model trained on 4,096-token sequences usually breaks on longer ones, and rotary position embeddings explain why. This article computes RoPE's frequencies, shows what each scaling method changes, works through YaRN's per-frequency ramp and attention factor with numbers, and explains the configuration you will meet.

Download Markdown
At a glance
Reading time
13 min
Sections
7
Code examples
3
Tables
1
Sources
8
Published
23 Nov 2026
In 30 seconds
What changed
Transformers 5.24.0 is released
Why it matters
RoPE scaling is why advertised context windows often exceed the lengths a model mostly trained on.
What to do
Read the model's config before extending

Most open language models encode word order with rotary position embeddings (RoPE). RoPE works well within the sequence lengths a model saw in training, but performance usually collapses when you feed it longer inputs. Yet many models are released with context windows far longer than most of their pre-training data, and teams routinely extend context further during fine-tuning.

The bridge is RoPE scaling: a family of small changes to RoPE's frequencies that let a model handle longer sequences, often with little or no extra training. The methods have names like position interpolation, NTK-aware scaling, YaRN and Llama 3 scaling, and they appear as a few lines in a model's configuration file. This article explains what those lines do, with the actual formulas and worked numbers.

What happened

Transformers 5.24.0 is released (21 November 2026)

Hugging Face's Transformers library published version 5.24.0 on PyPI on 21 November 2026, its third release of the month. Its current RoPE utilities documentation lists six rotary types (default, linear, dynamic, yarn, longrope and llama3), configured through a rope_parameters field in a model's config. It also documents per-layer-type RoPE settings for models such as Gemma 3, which mix full attention with sliding-window attention and can give each layer type its own base frequency and scaling.

Training frameworks expose the same settings. NVIDIA's NeMo RL documentation, for example, describes YaRN scaling for supervised fine-tuning, GRPO, DPO, reward modelling and distillation, with an example that extends a model from a 40,960-token pre-training context to 131,072 tokens using a factor of 3.2, and passes the same settings to vLLM so that rollouts and training use identical positions.

How RoPE encodes position

RoPE splits each query and key vector of dimension d into d/2 pairs. Pair j is treated as a point on a plane and rotated by an angle proportional to the token's position m:

angle = m · θ_j, with θ_j = b^(−2j/d)

where b is the base, often 10,000 (many recent models use larger bases). When a query at position m meets a key at position n, the rotations combine so that the dot product depends only on the difference m − n. That is how RoPE gives attention a sense of relative distance.

The pairs rotate at very different speeds. Take d = 128 and b = 10,000:

  • Pair 0 has θ = 1, a wavelength of 2π ≈ 6.3 tokens. It spins quickly and tracks fine local order.
  • Pair 63, the slowest, has a wavelength of about 54,410 tokens. Over a 4,096-token context it completes only 0.075 of a turn.

A good analogy is a clock with many hands. The second hand distinguishes nearby moments; the hour hand tells you about long spans. RoPE gives each attention head a clock with 64 hands turning at geometrically spaced speeds.

Why longer contexts break

During training on 4,096-token sequences, the slow pairs only ever see angles in a small part of their circle. At position 10,000, those slow pairs reach angles the model has never seen. The attention layers react to unfamiliar inputs unpredictably, and quality drops sharply. The fast pairs are fine: they have spun through full circles hundreds of times during training, so any angle is familiar.

This asymmetry, harmless for fast pairs and harmful for slow ones, is what every scaling method tries to handle.

Four ways to stretch RoPE

Position interpolation (linear)

The simplest method, position interpolation, divides every position by the scale factor s. With s = 4, position 16,000 is treated as position 4,000, so all angles stay inside the trained range. Transformers calls this linear.

The cost is resolution. Every pair, including the fast ones that never needed help, now turns four times more slowly, so neighbouring tokens look more alike. Models usually need some fine-tuning after linear interpolation to recover local precision.

NTK-aware and dynamic scaling

NTK-aware scaling changes the base instead of the positions. A larger base slows the low-frequency pairs a lot and the high-frequency pairs very little, because θ_j = b^(−2j/d) depends on b more strongly as j grows. That keeps local detail while stretching the long-range hands.

Transformers' dynamic type computes the new base on the fly from the current sequence length L, when it exceeds the original maximum L₀:

b′ = b · (s · L / L₀ − (s − 1))^(d/(d−2))

With b = 10,000, d = 128, L₀ = 4,096 and s = 4, the base stays 10,000 up to 4,096 tokens, becomes about 51,300 at 8,192 tokens and about 135,400 at 16,384 tokens. The advantage is that short inputs see the original model unchanged. The drawback is that the effective positions change as the sequence grows, which complicates caching of keys computed under an earlier base.

YaRN: treat each frequency differently

YaRN, published in 2023, combines both ideas with a rule per frequency. It measures how many full rotations each pair makes over the original context, r_j = L₀ / λ_j, where λ_j is the pair's wavelength. Then:

  • Pairs with many rotations (more than β_fast, default 32) are left alone; they already generalise.
  • Pairs with few rotations (fewer than β_slow, default 1) are fully interpolated by s, as in linear scaling.
  • Pairs in between get a linear blend of the two.

YaRN also scales attention logits by a temperature. Transformers computes an attention factor of 0.1 · ln(s) + 1 and applies it to the cosine and sine tables, so it multiplies both queries and keys. The logits therefore scale by its square. This compensates for attention becoming more diffuse over longer sequences.

Llama 3 scaling

Llama 3.1's scheme uses the same idea with wavelength thresholds instead of rotation counts. In Transformers' implementation, pairs whose wavelength is shorter than L₀ / high_freq_factor are unchanged, pairs with wavelength longer than L₀ / low_freq_factor are divided by the factor, and pairs in between are smoothly blended. The code comments give the original values: factor 8, low_freq_factor 1, high_freq_factor 4 and an original context of 8,192. That puts the thresholds at wavelengths of 2,048 and 8,192 tokens.

Table 1. Llama 3 scaling
Method Transformers rope_type What changes Keeps local detail Needs fine-tuning
Position interpolation linear positions divided by s no usually
Dynamic NTK dynamic base grows with sequence length mostly often not, for modest s
YaRN yarn per-frequency blend plus logit temperature yes little
Llama 3 llama3 per-frequency blend by wavelength yes applied in training
LongRoPE longrope searched per-dimension factors yes varies

YaRN with numbers

Take d = 128, b = 10,000, an original context L₀ = 4,096 and a target of 16,384, so s = 4. Transformers finds the boundary pairs by inverting the rotation formula:

j(r) = d · ln(L₀ / (2π r)) / (2 ln b)

For r = 32 (β_fast) this gives 20.9, which rounds down to 20. For r = 1 (β_slow) it gives 45.0, which rounds up to 46. So, of the 64 pairs:

  • pairs 0 to 20 (21 pairs) keep their original frequency;
  • pairs 46 to 63 (18 pairs) are slowed by the full factor of 4;
  • pairs 21 to 45 (25 pairs) are blended linearly between the two.

The attention factor is 0.1 · ln 4 + 1 = 1.139, so the logits are multiplied by 1.139² ≈ 1.30. In NeMo RL's example with s = 3.2, the factor is 0.1 · ln 3.2 + 1 = 1.116.

The code below reproduces these numbers with the same formulas Transformers uses:

import math, numpy as np
base, dim, L0, s = 10000.0, 128, 4096, 4.0
inv = base ** (-np.arange(0, dim, 2) / dim)                 # theta_j for 64 pairs

def corr_dim(n_rot):                                         # pair index with n_rot turns over L0
    return dim * math.log(L0 / (n_rot * 2 * math.pi)) / (2 * math.log(base))

low, high = math.floor(corr_dim(32)), math.ceil(corr_dim(1))  # 20, 46
ramp = np.clip((np.arange(dim // 2) - low) / (high - low), 0, 1)
inv_yarn = (inv / s) * ramp + inv * (1 - ramp)
ratio = inv / inv_yarn
print(low, high, (np.isclose(ratio, 1)).sum(), (np.isclose(ratio, s)).sum())  # 20 46 21 18
print(0.1 * math.log(s) + 1)                                   # 1.1386

Reading a config

A YaRN block in a model config usually looks like this:

"rope_parameters": {
  "rope_type": "yarn",
  "rope_theta": 1000000,
  "factor": 4.0,
  "original_max_position_embeddings": 32768
}

factor times original_max_position_embeddings gives the intended context, here 131,072 tokens. Two optional fields, mscale and mscale_all_dim, change how the attention factor is computed, and some model families set them. In Transformers' code, the ratio form is used only when both are present and non-zero; otherwise the plain 0.1 · ln(s) + 1 formula applies.

What it means in practice

RoPE scaling is why advertised context windows often exceed the lengths a model mostly trained on. Many models are pre-trained mainly at shorter lengths and then extended with a scaling method plus a smaller amount of long-sequence training. That is efficient, but it means the far end of the window is the least-trained part of the model.

For practitioners, three points follow. First, configuration must match between training and serving: a model fine-tuned with YaRN at factor 4 must be served with the same settings, which is why NeMo RL passes them to vLLM explicitly. Second, static methods such as YaRN change the frequencies for every input, including short ones, so they can slightly change behaviour on short prompts compared with no scaling; enable them only when you need long inputs. Third, an extended window is not the same as reliable long-context reasoning. Retrieval of a single fact across 100,000 tokens is easier than using many facts spread across them.

The positional encoding simulation shows how rotation angles change with position and frequency, and the KV cache simulation shows how memory grows as you extend context. For the attention computation itself, see the attention mechanism page.

What to do now

  1. Read the model's config before extending. Check rope_theta, any existing rope_parameters and original_max_position_embeddings, since many models are already scaled.
  2. Compute the factor from real needs. Set the factor to your target length divided by the original length, and do not extend further than your use case requires.
  3. Prefer per-frequency methods. Use YaRN or a model's native scheme rather than plain linear interpolation, which blurs local order.
  4. Fine-tune briefly at the target length. A short run on long sequences after enabling scaling usually recovers most quality, and the continued pre-training page covers longer runs; keep the same scaling settings in training and serving.
  5. Keep serving and training settings identical. Store the RoPE block with every checkpoint and pass it unchanged to your inference engine.
  6. Test short prompts too. Check that enabling static scaling does not hurt quality on the short inputs that make up most traffic.
  7. Evaluate real long-context tasks. Go beyond single-needle retrieval: test multi-fact questions, long summaries and code across many files at the full length.
  8. Budget the memory. A four-fold context increase means a four-fold larger KV cache per sequence, because every extra token adds keys and values at every layer; plan batch sizes, hardware and any cache quantisation accordingly.

Risks and open questions

Extended windows are uneven. Quality often degrades toward the end of a scaled window, and headline context lengths rarely come with per-length accuracy figures.

Configuration mismatches fail quietly. A model served with a different factor, base or attention temperature than it was trained with still produces fluent text, but its long-range accuracy can drop without obvious errors.

Dynamic scaling and caching conflict. Methods that change frequencies with sequence length make cached keys computed earlier inconsistent with later ones, which serving engines must handle carefully.

Mixed attention layouts add variables. Models that combine sliding-window and full-attention layers, with different RoPE settings per layer type, behave differently from uniform models under scaling.

Watch next: whether models publish accuracy by context length alongside headline windows, and whether learned or searched per-dimension scaling, such as LongRoPE, replaces fixed formulas.

Frequently asked questions

Why do models fail beyond their training length?

RoPE's slow-rotating pairs only see a small range of angles during training. Beyond the training length they reach unseen angles, and the attention layers respond unpredictably.

What is the difference between linear scaling and YaRN?

Linear scaling slows every frequency by the same factor, which blurs fine local positions. YaRN leaves fast frequencies alone, fully scales the slowest ones, blends those in between, and adds a small attention temperature.

Do I need to fine-tune after enabling YaRN?

Not always, but a short fine-tune on long sequences usually helps. The YaRN paper reports efficient extension with far less training than earlier methods, and many teams still run a brief long-context stage.

What does the factor in rope_parameters mean?

It is the ratio between the target context and the original training context. With an original length of 32,768 and a factor of 4, the intended context is 131,072 tokens.

Does a larger rope_theta help with long context?

A larger base slows all rotations, which is the idea behind NTK-aware scaling, and many models are pre-trained with large bases for this reason. Changing the base of an already trained model without further training usually needs a principled method such as dynamic NTK or YaRN.

Summary

RoPE encodes position by rotating pairs of dimensions at geometrically spaced speeds, so the dot product between a query and key depends on their distance. Beyond the training length, the slowest pairs reach unfamiliar angles and the model degrades. Position interpolation slows every pair uniformly, dynamic NTK raises the base as sequences grow, Llama 3 scaling blends by wavelength, and YaRN blends by rotation count and adds an attention temperature of 0.1 · ln(s) + 1. In the worked example with a factor of 4, YaRN leaves 21 of 64 pairs untouched, fully scales 18, and blends 25. Use the model's native scheme, keep training and serving settings identical, and evaluate at the lengths you actually serve. For more, see the Transformers page and the inside an LLM topic.

Sources

Cite this article

Kelahmet, Ö. C. (2026, November 23). Extending context windows with RoPE scaling: position interpolation, NTK, YaRN and Llama 3. Özer Cem KELAHMET. https://www.ozercemkelahmet.com/articles/rope-scaling-yarn-context-extension

BibTeX
@online{kelahmet2026rope,
  author = {Kelahmet, {\"O}zer Cem},
  title  = {{Extending context windows with RoPE scaling: position interpolation, NTK, YaRN and Llama 3}},
  year   = {2026},
  month  = {nov},
  url    = {https://www.ozercemkelahmet.com/articles/rope-scaling-yarn-context-extension}
}
Version historyfirst version
  1. Published

Factual corrections are listed here with what changed. Wording and formatting edits are not listed.

Last updated Nov 23, 2026
Type to search.
    ↑↓ navigate↵ open