# Long Context: Position Extrapolation, Training Recipes and Cost

> Extending a context window from 4K to 128K takes three fixes: RoPE extensions (PI, NTK-aware scaling, YaRN) for unseen positions, staged continued training on long text, and a budget for attention compute and KV cache. This page covers all three with formulas, code and two interactive tools.

- URL: https://dmxsf.com/en/wiki/architecture/long-context/
- [DMXSF](https://dmxsf.com/en/about/)
- Advanced
- Updated: 2026-11-15
- Tags: Long context, RoPE, Positional encoding, KV cache, Pretraining

## After this page you will be able to

- Work out the three costs of long context: quadratic prefill, the KV cache per token, and reading the whole sequence at every decode step.
- Explain why position encoding limits the context length, and tell what PI, NTK-aware scaling, YaRN and Llama 3.1's piecewise scaling each change in RoPE.
- Say why long-context training proceeds in stages and needs long-text data.
- Explain why the window length is not the effective length, and choose and deploy accordingly.

A context window is the largest number of tokens a model can process at once. To take a model trained on only 4K or 8K tokens to 128K, you have to solve three problems together: **position** (at distances beyond the training length RoPE produces rotation angles the model never saw, so the frequencies must change), **training** (after changing the frequencies you still continue training on long sequences, while keeping short-text ability) and **cost** (attention compute grows with the square of the length, and the KV cache and the bytes read per decoding step grow linearly). Once those are done, you still have to check with dedicated evaluations that the model can really use such a window, because the advertised window is often longer than the effective one.

| Problem | Symptom | Common fix | Where on this page |
| --- | --- | --- | --- |
| Position extrapolation | Perplexity explodes past the training length (in the PI paper, LLaMA 7B goes above $10^3$ beyond 2048) | Change RoPE's frequencies: PI, NTK-aware scaling, YaRN, or a larger base | “Why positions limit the context length”, “Four ways to change RoPE” |
| Training | Changing positions without continued training leaves weak long-text ability; careless continued training hurts short texts | Lengthen in stages, continue training on long sequences, add long data to SFT | “Training recipes” |
| Cost | Prefill compute grows faster than linearly; KV cache and decoding reads grow linearly | FlashAttention, GQA and MLA, KV quantization, context parallelism | “The three bills of a long context”, “The systems side” |
| Evaluation | Needle-in-a-haystack is nearly perfect, but real tasks go wrong | Multi-task long-context benchmarks such as RULER, and tests on your own task | “Evaluation” |

> [!NOTE] Notation
> On this page 4K, 32K and 128K are multiples of 1024 (128K = 131,072 tokens), matching `max_position_embeddings` in model configs. $L$ is the training length, $s$ the extension factor and $L'=sL$ the target length.

## The three bills of a long context

Before looking at the fixes, it helps to know how much a longer context costs. Let the model have $n$ layers, $H$ query heads, head dimension $d_h$ and $G$ KV heads.

### Prefill: attention grows with the square of the length

Processing one sequence of $s$ tokens, the forward pass has two parts (one multiply-add counts as 2 FLOPs):

- **Linear layers**: the weight matrices of the attention projections and the MLP in every layer. The per-token cost is fixed at $2nP_{\text{block}}$, where $P_{\text{block}}$ is the number of parameters of these matrices in one layer; the total grows linearly with $s$.
- **Attention matrices**: the two matrix products $QK^\top$ and $AV$. Each (query, key) pair of each head takes $4d_h$ FLOPs, and under a causal mask there are $s(s+1)/2$ pairs, so the total is $2nHd_h\,s(s+1)$, growing with $s^2$.

The two are equal at

$$
s^{*}=\frac{P_{\text{block}}}{H\,d_h}-1 .
$$

For Llama 3 8B, $P_{\text{block}}=218.1\text{M}$ and $Hd_h=4096$, so $s^{*}\approx 53{,}000$; for Llama 3 70B, $P_{\text{block}}=855.6\text{M}$ and $Hd_h=8192$, so $s^{*}\approx 104{,}000$. Attention FLOPs depend only on the number of query heads $H$: GQA and MQA shrink the KV cache but not this term.

| Length | Llama 3 8B attention share | Llama 3 8B KV cache | Llama 3 70B attention share | Llama 3 70B KV cache |
| --- | --- | --- | --- | --- |
| 4K | 7.1% | 0.50 GiB | 3.8% | 1.25 GiB |
| 32K | 38.1% | 4.00 GiB | 23.9% | 10.00 GiB |
| 128K | 71.1% | 16.00 GiB | 55.7% | 40.00 GiB |
| 1M | 95.2% | 128.00 GiB | 90.9% | 320.00 GiB |

“Attention share” is the share of attention FLOPs in (attention + linear) FLOPs when prefilling one sequence; the KV cache is for one sequence in BF16; the numbers come from the code at the end of this section. At 128K, more than 70% of the prefill compute of the 8B model goes into the attention matrices.

That is why Llama 3 pre-trains on long sequences only at the very end: the paper notes that the compute in self-attention grows quadratically with the sequence length. The estimate agrees with measurements: Xiong et al. raised the sequence length of a 70B model from 4,096 to 16,384 (with FlashAttention) and measured about 17% lower speed; by the formula above the compute per token grows by only about 11% ($(1+16385/104448)/(1+4097/104448)\approx1.11$). The measurement is slower because attention kernels usually use the hardware less efficiently than large matrix products, which is not modeled here.

### KV cache: 128 KiB per token

During decoding, the K and V of every past token are cached. The bytes needed per token are

$$
\text{KV}_{\text{token}}=2\,n\,G\,d_h\,b ,
$$

where $b$ is the number of bytes per number. For Llama 3 8B that is $2\times32\times8\times128\times2=131{,}072$ bytes, or 128 KiB, so 16 GiB at a 128K context; Llama 3 70B has 80 layers and needs 320 KiB per token, 40 GiB at 128K. This is the cache of **one** sequence and every concurrent request holds its own, so how many long requests one card can serve is often limited by the KV cache first. See [KV Cache and Inference Performance](https://dmxsf.com/en/wiki/inference/kv-cache/) for the details and [Efficient Attention](https://dmxsf.com/en/wiki/architecture/efficient-attention/) for how GQA and MLA shrink it.

### Decoding: every step reads the whole sequence's KV again

Decoding is [memory-bound](https://dmxsf.com/en/glossary/#memory-bound): to produce one token the model reads all the weights (the input embedding table is only a lookup and is not read), and then reads the KV of the whole sequence. If one step reads $W$ bytes of weights, it reads $W+s\cdot\text{KV}_{\text{token}}$ bytes in total, and the speed limit is roughly the memory bandwidth divided by that. The two terms are equal at $s_{kv}=W/\text{KV}_{\text{token}}$: 114,516 tokens for Llama 3 8B (BF16) and 424,213 tokens for Llama 3 70B; beyond that length the main cost of decoding shifts from reading weights to reading KV. Quantizing the weights to INT4 and storing the KV in FP8 cuts the weight reads to a quarter and the KV to a half, so the crossover halves to 57,258.

There is a fourth item: a naive attention implementation writes the $s\times s$ score matrix to memory. With $s=131{,}072$, 32 heads and BF16, one layer needs $131072^2\times2\times32$ bytes, exactly 1 TiB. FlashAttention computes in tiles and never materializes this matrix, so memory grows linearly with $s$, but the FLOPs do not shrink at all, so the quadratic term above remains (see [Efficient Attention](https://dmxsf.com/en/wiki/architecture/efficient-attention/)).

Things to try:

1. **Keep the defaults: Llama 3 8B, 128K, BF16.** The KV cache is 128 KiB per token and 16.00 GiB for this sequence, more than the BF16 weights (13.98 GiB); attention takes 71% of the prefill compute, and the compute per token is 3.21 times that at 4K; with the bandwidth of one H100 the decoding speed limit is about 104 tokens/s.
2. **Drag the length down to 4K.** Attention's share falls to 7.1%, the KV cache is only 512 MiB and the speed limit rises to about 215 tokens/s: for the same model, length changes the cost by an order of magnitude.
3. **Switch the weights to INT4 and the KV to FP8.** The “KV reads = weight reads” length drops from 114,516 to 57,258; the KV cache at 128K halves to 8.00 GiB and the speed limit rises to about 271 tokens/s. Quantizing the weights shrinks them, which lets the KV become the main cost sooner.
4. **Switch to Llama 2 7B.** It uses MHA, so the KV is 512 KiB per token (128 KiB for Llama 3 8B), the 128K cache is 64 GiB, and the “KV reads = weight reads” length is only 25,205: that is what GQA is worth. Llama 2 itself supports only 4K; it is used here just to compare structures.
5. **Switch to Llama 3 70B with the bandwidth of 8 H100s.** At 128K the KV cache is 40 GiB, the weights 129.46 GiB, attention takes 56% of the prefill compute, and the crossovers move to 104,447 and 424,213 tokens: the bigger the model, the heavier the linear layers and the later attention takes over.

The code below recomputes these numbers with the fewest formulas (shapes from each model's public `config.json`) and runs as is:

```python
# Model shapes come from each model's public config.json
models = {
    "Llama 3 8B": dict(layers=32, hidden=4096, heads=32, kv_heads=8, head_dim=128, ffn=14336, vocab=128256),
    "Llama 3 70B": dict(layers=80, hidden=8192, heads=64, kv_heads=8, head_dim=128, ffn=28672, vocab=128256),
}

def block_params(m):
    d, hd = m["hidden"], m["head_dim"]
    attn = 2 * d * m["heads"] * hd + 2 * d * m["kv_heads"] * hd  # q, o and k, v projections
    mlp = 3 * d * m["ffn"]                                       # gate, up, down
    return attn + mlp

def attention_share(m, s):
    """Share of attention-matrix FLOPs in (attention + linear layers) when prefilling one s-token sequence."""
    linear = 2 * s * m["layers"] * block_params(m)
    attention = m["layers"] * m["heads"] * 4 * m["head_dim"] * (s * (s + 1) / 2)  # QK^T and AV, causal mask
    return attention / (attention + linear)

GiB = 1024 ** 3
for name, m in models.items():
    p_block = block_params(m)
    crossover = p_block / (m["heads"] * m["head_dim"]) - 1                         # attention FLOPs = linear FLOPs
    kv_token = 2 * m["layers"] * m["kv_heads"] * m["head_dim"] * 2                 # BF16, K and V of one token
    norms = (2 * m["layers"] + 1) * m["hidden"]
    weights = 2 * (m["layers"] * p_block + norms + m["vocab"] * m["hidden"])       # weights read per decoding step: no input embedding table
    print(f"{name}: prefill crossover {crossover:,.0f} tokens; KV {kv_token // 1024} KiB/token; "
          f"weights {weights / GiB:.2f} GiB; decode crossover {weights / kv_token:,.0f} tokens")
    for s in (4096, 32768, 131072, 1048576):
        print(f"  {s:>9,} tokens: attention {attention_share(m, s):6.1%}, KV cache {s * kv_token / GiB:7.2f} GiB")

# Llama 3 8B: prefill crossover 53,247 tokens; KV 128 KiB/token; weights 13.98 GiB; decode crossover 114,516 tokens
#       4,096 tokens: attention   7.1%, KV cache    0.50 GiB
#      32,768 tokens: attention  38.1%, KV cache    4.00 GiB
#     131,072 tokens: attention  71.1%, KV cache   16.00 GiB
#   1,048,576 tokens: attention  95.2%, KV cache  128.00 GiB
# Llama 3 70B: prefill crossover 104,447 tokens; KV 320 KiB/token; weights 129.46 GiB; decode crossover 424,213 tokens
#       4,096 tokens: attention   3.8%, KV cache    1.25 GiB
#      32,768 tokens: attention  23.9%, KV cache   10.00 GiB
#     131,072 tokens: attention  55.7%, KV cache   40.00 GiB
#   1,048,576 tokens: attention  90.9%, KV cache  320.00 GiB
```

These formulas agree with real implementations: counting parameters on the Hugging Face Llama implementation with the same shapes gives exactly the total and per-layer parameter counts used here for 8B and 70B, and running PyTorch's `FlopCounterMode` over a small model gives the same forward FLOPs as the formula for the linear layers, the output head and the full $s\times s$ attention matrix (plus a tiny extra for the RoPE frequency outer product). A causal mask only needs the lower triangle, so the attention FLOPs in the code are half of the full matrix; kernels such as FlashAttention skip blocks that are fully masked, so the real cost comes close to that.

## Why positions limit the context length

[Modern LLM Architecture](https://dmxsf.com/en/wiki/architecture/modern-llm-architecture/) introduces RoPE; here is the part that matters for context length. RoPE splits the $d$ dimensions of query and key into $d/2$ pairs, and pair $i$ ($i=0,\dots,d/2-1$) is rotated by $m\theta_i$ radians at position $m$,

$$
\theta_i=b^{-2i/d},\qquad \lambda_i=\frac{2\pi}{\theta_i},\qquad r_i=\frac{L}{\lambda_i} .
$$

$b$ is the base; $\lambda_i$ is the number of positions needed for one full turn, the wavelength; $r_i$ is the number of **turns** the pair makes within the training length $L$. With $d=128$ and $b=10{,}000$, $\lambda_0=6.28$, so the fastest pair turns 1 radian per position, and $\lambda_{63}=54{,}410$, so the slowest pair needs 54 thousand positions for one turn.

What matters in attention is the relative distance $m-n$ between query and key, and pair $i$ sees the angle $(m-n)\theta_i$. In training the largest distance is $L$, so pair $i$ has seen angles in $[0,L\theta_i)$:

- A pair with $r_i\ge1$ (high frequency) has gone around the full circle, so it has seen **all phases**; at a larger distance it just keeps turning through phases it already knows.
- A pair with $r_i<1$ (low frequency) only saw part of a circle in training (less than one full turn). Once the distance exceeds $L$, the angle enters a range that never occurred in training, which is true extrapolation. With $L=4096$, 18 of the 64 pairs (indices 46 to 63) are of this kind.

So the trouble comes mainly from the **low-frequency** pairs, not from “high-frequency dimensions turning too fast”, as is often said. The result of direct extrapolation is severe: in the PI paper the perplexity of LLaMA 7B goes above $10^3$ beyond its window. Fine-tuning to a longer window without changing positions helps very slowly too: the paper reports that after more than 10,000 batches the effective window only grew from 2048 to 2560.

| Approach (LLaMA 7B, PG19 perplexity, lower is better) | 2048 | 4096 | 8192 | 16384 | 32768 |
| --- | --- | --- | --- | --- | --- |
| Original model, direct extrapolation (window 2048) | 7.20 | >$10^3$ | >$10^3$ | >$10^3$ | >$10^3$ |
| Direct fine-tuning to 8192 (positions unchanged) | 7.21 | 7.34 | 7.69 | - | - |
| PI, fine-tuned to 8192 | 7.13 | 6.96 | 6.95 | - | - |
| PI, fine-tuned to 32768 | 7.23 | 7.04 | 6.91 | 6.80 | 6.77 |

The data are from Table 1 of Chen et al. (2023); the evaluation window is the column header. With direct fine-tuning, perplexity gets worse as the evaluation window grows (7.21 to 7.69), so the model has not learned to use the longer context; with PI it gets better as the window grows, and the 32768 model was fine-tuned for only 1000 steps. The PI paper also proves that, in the LLaMA 7B setting, the upper bound of the interpolation error is at least about 600 times smaller than that of extrapolation.

## Four ways to change RoPE

Extend the training length $L$ to $L'=sL$. The methods below only change the frequencies $\theta_i\to\theta_i'$ (YaRN also adds a scaling of the attention), not the model structure.

### Position interpolation (PI)

$$
\theta_i'=\frac{\theta_i}{s}
$$

This is the same as replacing the position index $m$ by $m/s$: all positions in the target length $L'$ are squeezed back into $[0,L)$, so the angle range of every pair stays inside the range seen in training, with no new phases. The price is that all frequencies slow down together, including the fastest pairs: the relative angle of two neighboring tokens shrinks to $1/s$ of what it was, and the resolution of local positions drops. The YaRN paper explains this with the result of Tancik et al. (2020) from neural tangent kernel (NTK) theory, that deep networks struggle to learn high-frequency detail from low-dimensional inputs; PI removes the high-frequency components of RoPE. Earlier PI-based fine-tunes started to degrade at an extension factor of about $s=8$.

### NTK-aware: change the base

Instead of treating all frequencies alike, change the high ones little and the low ones a lot. The simplest way is to use a larger base

$$
b'=b\,s^{\,d/(d-2)},\qquad \theta_i'=\theta_i\,s^{-2i/(d-2)} .
$$

The second equation follows directly from $\theta_i'=(b')^{-2i/d}$: at $i=0$ the factor is 1, so the fastest pair is unchanged; at $i=d/2-1$ it is exactly $1/s$, so the slowest pair is fully interpolated, and the pairs in between change exponentially. The name comes from the NTK argument above. It works without fine-tuning, but it is not pure interpolation: apart from the slowest pair, the other low-frequency pairs still reach angles that training never saw. In the example above ($d=128$, $b=10{,}000$, $s=8$), among the 18 pairs with less than one turn, NTK-aware scaling leaves “new phases” of up to 1.75 times the angle seen in training. The YaRN paper therefore notes that fine-tuning with NTK-aware scaling gives worse results than PI, and that $s$ has to be set higher than the intended extension factor; its best base can only be found by trial.

**Changing the base** also has a more direct use, called ABF (Adjusted Base Frequency): skip the formula, set the base to a much larger fixed value and continue training on a lot of long text. Xiong et al. raised Llama 2's base from 10,000 to 500,000; Llama 3 uses a RoPE base of 500,000, which the paper says is to better support long contexts; Qwen2.5-7B uses 1,000,000.

### YaRN: split by turns, then add a temperature

YaRN (Peng et al., 2023) combines the two ideas, in three parts.

**First, split by number of turns (NTK-by-parts).** For each pair, look at the number of turns $r_i$ it makes within the training length and decide how to change it:

$$
\theta_i'=\Bigl[(1-\gamma_i)\frac1s+\gamma_i\Bigr]\theta_i,\qquad
\gamma_i=\operatorname{clamp}\!\Bigl(\frac{r_i-\alpha}{\beta-\alpha},\,0,\,1\Bigr).
$$

When $r_i<\alpha$ (less than one turn, must be interpolated), $\gamma_i=0$ and the frequency is divided by $s$; when $r_i>\beta$ (many turns, all phases seen), $\gamma_i=1$ and the frequency is unchanged; in between the change is linear. For the Llama family the paper found $\alpha=1$ and $\beta=32$ to work well. High-frequency pairs then stay as they were, without losing local resolution as in PI, and low-frequency pairs are fully squeezed back into the range seen in training, without leaving new phases as NTK-aware scaling does. The paper writes the transition as a linear function of $r_i$, while the reference implementations (the YaRN repository and Hugging Face Transformers) ramp linearly in the pair index $i$; the end points are the same and the shape differs slightly. The interactive tool below follows the reference implementation.

**Second, an attention temperature.** The paper observes that after interpolation the entropy of the attention distribution grows, that is, it gets flatter; putting a temperature $t$ on the logits before the softmax, $\operatorname{softmax}\bigl(q^\top k/(t\sqrt d)\bigr)$, improves perplexity uniformly across data samples and positions. The factor was found by fitting, on LLaMA 7B, 13B, 33B and 65B without fine-tuning, the $1/t$ at the lowest perplexity for each $s$: $\sqrt{1/t}=0.1\ln s+1$, which also works fairly well for Llama 2. In the implementation the cos and sin of RoPE are both multiplied by this factor, so q and k each get one copy and the attention kernel does not change at all, with no extra cost in training or inference. At $s=8$ the factor is 1.208 and the logits are scaled by $1.208^2=1.46$.

**Third, dynamic scaling (optional).** At inference, compute $s=\max(1,\ \text{current length}/L)$ on every forward pass, so short texts are not affected at all, and the scale grows only once the length exceeds $L$; the effect is to degrade gracefully instead of breaking as soon as the window ends. One implementation detail: when $s$ changes, the RoPE of every token changes, so the KV cache must store K before the rotation.

### Llama 3.1's piecewise scaling

The release config of Llama 3.1 contains a `rope_scaling` block: `rope_type: llama3`, `factor: 8`, `low_freq_factor: 1`, `high_freq_factor: 4`, `original_max_position_embeddings: 8192`, with a base of 500,000. The rule: pairs with less than 1 turn (wavelength above 8,192) have their frequency divided by 8, pairs with more than 4 turns (wavelength below 2,048) are unchanged, and in between the change is linear in the number of turns. Formally this is YaRN's piecewise interpolation with $\alpha=1$ and $\beta=4$ and no attention scaling. With base 500,000 and $d=128$, 29 of the 64 pairs are divided by 8, 6 are in the transition, and 29 stay unchanged. Meta's reference code notes that these values come from a grid search; the Llama 3 paper only states the base of 500,000 and does not describe this scaling, which appears only in the released config and code.

### Comparison

| Method | What changes | High-frequency pairs (fast) | Low-frequency pairs (less than one turn) | Fine-tuning |
| --- | --- | --- | --- | --- |
| Position interpolation (PI) | All $\theta_i\to\theta_i/s$ | Slowed down; neighboring tokens differ by an angle $s$ times smaller | Squeezed back into the seen range | Needed; the paper used at most 1000 steps |
| NTK-aware | $b\to b\,s^{d/(d-2)}$ | Almost unchanged | Only the slowest pair is divided by exactly $s$; the others keep some new phases | Better than PI without fine-tuning, worse than PI with it |
| YaRN | Piecewise interpolation by turns, plus an attention temperature | Unchanged | Fully divided by $s$ | A little (400 steps in the paper); also usable without fine-tuning |
| Llama 3.1 style | The same piecewise rule with $\alpha=1$, $\beta=4$, no temperature | Unchanged | Fully divided by $s$ | Used together with long-context continued training |

There is also LongRoPE (Ding et al., 2024), which uses an evolutionary search to find a non-uniform interpolation factor for each dimension, extends LLaMA2 and Mistral to 2048K tokens in two steps (first to 256K, then to 2048K), and readjusts to keep short-context performance.

Things to try (the numbers are for the default setting, “Example: Llama 2, 4K extended 8× to 32K”, that is $d=128$, $b=10{,}000$, $L=4096$, $s=8$):

1. **Read the row of statistics first.** 18 / 64 pairs make less than one turn within $L$; YaRN's split is 21 / 25 / 18 (kept / blended / ÷$s$); NTK-aware scaling's new base is $b'=82{,}685$; YaRN's attention scaling is 1.208, so the logits grow by 1.46.
2. **Drag “Inspect pair i” to 63 (the slowest pair).** In the column “÷ turns seen in training” the original RoPE shows ×8.00 and the other four methods all show ×1.00: the slowest pair is brought back into the range of angles seen in training.
3. **Drag to 50 (one of the pairs with less than one turn).** PI, YaRN and the Llama 3.1 style still show ×1.00, NTK-aware scaling shows ×1.54: it is exactly ÷$s$ only on the slowest pair.
4. **Drag to 0 (the fastest pair).** PI's $\theta'$ falls from 1 radian to 0.125 radian and the wavelength grows from 6.28 to 50.3 positions, so neighboring tokens differ by only 1/8 of the angle; the other methods keep it as it was, and a ratio above 1 on this pair does not matter, since it already goes around hundreds of times.
5. **Drag to 33 (inside YaRN's transition).** YaRN's ratio is ×4.50, exactly between PI's ×1.00 and the original ×8.00; this pair sits in the middle of the transition (indices 20 to 46).
6. **Drag YaRN α from 1 to 4.** Every pair with less than 4 turns is fully interpolated, the “÷$s$” count grows from 18 to 28, the split becomes 21 / 15 / 28 and the transition narrows.
7. **Load the DeepSeek-V3 and Qwen2.5 settings.** DeepSeek-V3 (64 RoPE dimensions, $s=40$) splits 11 / 12 / 9, with attention scaling 1.369 (logits ×1.87) and a target length of 163,840; Qwen2.5 (base 1,000,000, $L=32768$, $s=4$) splits 24 / 16 / 24, with attention scaling 1.139 (logits ×1.30).

The following code needs no libraries; it implements PI, NTK-aware scaling and YaRN, and measures the “new phases” each method leaves on the pairs with less than one turn:

```python
import math

def rope_freqs(dim, base):
    return [base ** (-2 * i / dim) for i in range(dim // 2)]

def position_interpolation(freqs, s):
    return [f / s for f in freqs]

def ntk_aware(dim, base, s):
    return rope_freqs(dim, base * s ** (dim / (dim - 2)))

def yarn(freqs, dim, base, trained, s, alpha=1, beta=32):
    def pair_for_turns(turns):  # (fractional) index of the pair that makes exactly `turns` turns
        return dim * math.log(trained / (turns * 2 * math.pi)) / (2 * math.log(base))
    low = max(math.floor(pair_for_turns(beta)), 0)
    high = min(math.ceil(pair_for_turns(alpha)), dim - 1)
    out = []
    for i, f in enumerate(freqs):
        ramp = min(max((i - low) / (high - low), 0), 1)  # 0: keep, 1: fully interpolate
        out.append(f * (1 - ramp) + f / s * ramp)
    return out

dim, base, trained, s = 128, 10_000, 4096, 8
freqs = rope_freqs(dim, base)
short = [i for i, f in enumerate(freqs) if trained * f < 2 * math.pi]  # pairs with less than one turn within L
print(f"pairs with less than one turn: {len(short)} / {dim // 2}, indices {short[0]} to {short[-1]}")

methods = {
    "RoPE": freqs,
    "PI": position_interpolation(freqs, s),
    "NTK-aware": ntk_aware(dim, base, s),
    "YaRN": yarn(freqs, dim, base, trained, s),
}
for name, new in methods.items():
    # Angle at the target length s*L as a multiple of the largest angle seen in training (at L); above 1 means unseen phases
    extra = max(s * new[i] / freqs[i] for i in short)
    print(f"{name:10s} pair 0 theta'={new[0]:.3f}, slowest pair /{freqs[-1] / new[-1]:.2f}, largest unseen-phase factor {extra:.2f}")

# pairs with less than one turn: 18 / 64, indices 46 to 63
# RoPE       pair 0 theta'=1.000, slowest pair /1.00, largest unseen-phase factor 8.00
# PI         pair 0 theta'=0.125, slowest pair /8.00, largest unseen-phase factor 1.00
# NTK-aware  pair 0 theta'=1.000, slowest pair /8.00, largest unseen-phase factor 1.75
# YaRN       pair 0 theta'=1.000, slowest pair /8.00, largest unseen-phase factor 1.00
```

The frequencies from this code agree with the `linear`, `dynamic` (with `factor=1` and a sequence length of $sL$, which is static NTK-aware scaling), `yarn` and `llama3` implementations in Hugging Face Transformers, and with Meta's `apply_scaling` (compared term by term on six different $d$, $b$, $L$, $s$ settings, with relative errors within single precision).

### Beyond the window it still fails

The extended window has a clear edge. Table 7 of the YaRN paper compares several 7B models by perplexity on ten 128K Proof-pile documents (lower is better):

| Model (7B) | Method | Window | 8K | 32K | 64K | 96K | 128K |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Together | PI | 32K | 3.50 | 2.64 | >$10^2$ | >$10^3$ | >$10^4$ |
| Code Llama | NTK-aware | 100K | 3.71 | 2.74 | 2.55 | 2.54 | 2.71 |
| YaRN ($s=16$) | YaRN | 64K | 3.51 | 2.65 | 2.42 | >$10^1$ | >$10^1$ |
| YaRN ($s=32$) | YaRN | 128K | 3.56 | 2.70 | 2.45 | 2.36 | 2.37 |

The $s=16$ model does well up to 64K and breaks at 96K; the $s=32$ model started from the $s=16$ checkpoint and was trained for only 200 more steps on 64K data, and extrapolates to 128K. It is also a reminder: extend and test for the length you want; do not count on “extending a bit more for margin” to keep the quality.

## Training recipes: positions are only the start

After the frequencies are changed the model still does not know how to *use* a long context; it has to keep training on long sequences. Some public recipes:

| Model | Window | Position handling | Long-sequence training | Notes |
| --- | --- | --- | --- | --- |
| Llama 2 Long (Xiong et al., 2023) | 4K → 32K | ABF: base 10,000 → 500,000 | 400B tokens of continued training on Llama 2, 100,000 steps, 4M tokens per batch | 7B and 13B use 32,768-token sequences, 34B and 70B use 16,384-token sequences |
| Llama 3 405B | 8K → 128K | RoPE base 500,000 | About 800B tokens in six stages of increasing length (about 5% of the 15.6T total) | Each stage is accepted when short-context evaluations have fully recovered and needle-in-a-haystack is perfect at that length |
| DeepSeek-V3 | 4K → 32K → 128K | YaRN, $s=40$, $\alpha=1$, $\beta=32$, scaling $0.1\ln s+1$, applied only to the decoupled shared key of MLA | Two phases of 1000 steps each: 32K sequences with batch size 1920, then 128K sequences with batch size 480; learning rate $7.3\times10^{-6}$ | The SFT model is stable on needle-in-a-haystack up to 128K |
| YaRN's Llama 2 7B | 4K → 64K → 128K | YaRN, $s=16$ then $s=32$ | 400 steps + 200 steps (about 256 + 128 A100 GPU-hours) | Small-scale fine-tuning, to show the method itself |

Some lessons from these recipes:

1. **Long-sequence training comes last and takes only a small part.** Llama 3's long-context stage is about 5% of the pre-training tokens. Xiong et al. compared training on 32K sequences from the start with training short first and long later, and the latter saves about 40% of the FLOPs with almost no loss in performance.
2. **Data quality matters more than the share of long text.** In the ablations of Xiong et al., removing almost all long text still kept most of the gain after continued training, and greatly raising the share of long text gave no clear, consistent benefit. Their conclusion is that high-quality data matters more than text length, and that a long-context model can be trained with very limited long data.
3. **Lengthen in stages and check at every step.** Llama 3 trains on each length until short-context evaluations have fully recovered and needle-in-a-haystack is solved perfectly before it goes longer; on the last 40M tokens it linearly anneals the learning rate to 0 at 128K and raises the share of high-quality data.
4. **Be careful with the learning rate.** Xiong et al. found that the 34B and 70B models need a smaller learning rate (1e-5, against 2e-5 for 7B and 13B) for the validation loss to decrease monotonically.
5. **Post-training also needs long data.** If Llama 3's SFT used only short data, long-context ability would regress noticeably. Annotating long texts by hand is too tedious, so the data are mainly synthetic, generated by an earlier Llama 3: question-answer pairs from 8K chunks of long documents, hierarchical summaries, and code reasoning where the most-depended-on file of a repository is removed and the model must name the files that depend on it and write the missing code, bucketed into 16K, 32K, 64K and 128K. Ablations show that mixing 0.1% synthetic long data into the original short data gives the best combined short- and long-context performance; DPO with short data only does not hurt long-context ability, provided the SFT model is already good at long contexts.

## The systems side: making long sequences trainable and servable

| Technique | What it solves | What it does not solve | Example |
| --- | --- | --- | --- |
| FlashAttention | Never materializes the $s\times s$ matrix, memory grows linearly with length, less memory traffic | FLOPs stay quadratic; does not shrink the KV cache | Nearly every modern training and inference framework |
| GQA, MLA, KV quantization | Shrink the KV cache and the bytes read per decoding step | Do not change the quadratic prefill compute | Llama 3's 8 KV heads, DeepSeek-V3's MLA |
| Sliding-window attention | Limits compute and cache to the window | Information outside the window only travels through the layers | Mistral 7B ($W=4096$) |
| Context parallelism, Ring Attention | Split the sequence across cards, beyond one card's memory | Total compute is unchanged, and communication is added | Llama 3's context parallelism |
| StreamingLLM (attention sink) | Unbounded streaming generation with a fixed cache | Does not extend memory: what left the window is gone | The paper reports stable runs beyond 4 million tokens |

FlashAttention, GQA, MLA and sliding windows are covered in [Efficient Attention](https://dmxsf.com/en/wiki/architecture/efficient-attention/); the last two need a word here.

**Context parallelism (CP).** When a sequence is too long for one card, split it along its length across several cards. Llama 3 cuts the sequence into $2\times\text{CP}$ chunks and gives rank $i$ the $i$-th and the $(2\text{CP}-1-i)$-th chunk: under a causal mask the later chunks cost more, so pairing a head chunk with a tail chunk balances the load. Before attention it all-gathers K and V, then computes attention for its local Q chunk. The paper says it did not use the ring-style overlap of communication and computation of Ring Attention, for two reasons: all-gather makes it easier to support different attention masks such as a document mask; and GQA makes K and V much smaller than Q, so the communication is $O(S)$ against $O(S^2)$ for attention, and the exposed all-gather latency is negligible. Ring Attention (Liu et al., 2023) instead passes KV blocks around a ring of devices, fully overlapping the communication with blockwise computation, so trainable sequences can be up to the device count times longer than with earlier memory-efficient methods.

**StreamingLLM and the attention sink.** Keeping only the KV of the most recent window (window attention) breaks once the text outgrows the cache. Xiao et al. found that keeping the KV of the first few tokens largely restores performance: those initial tokens get high attention scores even when they carry little meaning, acting as a “sink”. StreamingLLM keeps these sink tokens plus the recent window, which lets models trained with a finite window generate stably for more than 4 million tokens without fine-tuning, and in streaming settings it is up to 22.2 times faster than recomputing over a sliding window. Note that it solves “can keep generating”; what has left the window is dropped and the model cannot recall it.

## Evaluation: the window is not the effective length

**Needle in a Haystack (NIAH).** Insert a trivial fact (the “needle”) at some depth in a long stretch of distractor text (the “haystack”), then ask the model to retrieve it. It is cheap and intuitive, and both the Llama 3 and DeepSeek-V3 reports use it to show that the model finds information within its window: Llama 3 retrieved all needles at every document depth and context length. But it only tests retrieval, and nearly every model scores close to full marks within its window, so it separates models poorly.

**RULER.** NVIDIA's RULER (Hsieh et al., COLM 2024) extends needle-in-a-haystack into 13 tasks in four categories: needles of several kinds and numbers (retrieval), variable tracking (multi-hop tracing), common and frequent word extraction (aggregation), and question answering. They evaluated 17 long-context models and found that, although needle-in-a-haystack is nearly perfect, almost all models degrade sharply as the length grows; all of them claim at least 32K, but only half keep “satisfactory” performance at 32K, where the bar is the score of Llama 2 7B at 4K (85.6%), and the longest length that passes the bar is the “effective length”.

| Model | Claimed length | RULER effective length | 4K | 32K | 64K | 128K |
| --- | --- | --- | --- | --- | --- | --- |
| Gemini-1.5-Pro | 1M | >128K | 96.7 | 95.9 | 95.9 | 94.4 |
| GPT-4 | 128K | 64K | 96.6 | 93.2 | 87.0 | 81.2 |
| Llama 3.1 70B | 128K | 64K | 96.5 | 94.8 | 88.4 | 66.6 |

The data are from Table 3 of the RULER paper (each score is the mean accuracy over 13 tasks, with a bar of 85.6%). These models all fall below the bar before 128K, except Gemini-1.5-Pro.

**Lost in the Middle.** Liu et al. found that performance is usually highest when the relevant information is at the beginning or end of the input, and degrades significantly when it sits in the middle of a long context; plotted, this is a U-shaped curve, which holds even for models built for long contexts. See the [explainer](https://dmxsf.com/en/blog/lost-in-the-middle/) and the [paper](https://arxiv.org/abs/2307.03172).

## What to do when choosing and deploying

| What you are doing | Advice |
| --- | --- |
| Feeding an existing model inputs longer than its training length | First check whether the model supports it natively (look at `max_position_embeddings` and the official notes). If you must extrapolate, use YaRN or a similar scaling in your inference framework, and test at the target length. Static scaling applies at every length: the Qwen2.5 model card says that vLLM currently supports only static YaRN, which may hurt short texts, and advises adding the setting only when long contexts are needed |
| Doing long-context continued training yourself | Change positions (YaRN, or a larger base), lengthen in stages, and accept each stage when short-text evaluations recover and needle-in-a-haystack passes; put the weight on data quality, the share of long text need not be high; add synthetic long text to SFT; run several kinds of tasks near the target length |
| Planning deployment resources | Compute the KV cache of one sequence first and divide the memory budget by it to get the concurrency; decoding speed is set by the bytes read for “weights + KV”; GQA and MLA models and KV quantization lower this bill; for repeated questions over the same long prefix, reusing the prefix's KV cache saves the repeated prefill; a hybrid whose layers are mostly fixed-size states makes the cache grow only with its few attention layers, see [State Space Models and Hybrid Architectures](https://dmxsf.com/en/wiki/architecture/state-space-and-hybrid/) |
| Building an application | Put the key information at the beginning or the end, do not expect the model to use the whole context evenly; narrow very long material down with RAG or summaries first; evaluate on your own data by length and by position |

## Common misconceptions

1. **“Advertised 128K means 128K works well.”** The advertised length reflects what training or configuration supports. In RULER, Llama 3.1 70B advertises 128K and has an effective length of 64K.
2. **“With RoPE you can extrapolate indefinitely.”** With direct extrapolation, the perplexity of LLaMA 7B in the PI paper goes above $10^3$. In Table 7 of YaRN, the 64K model also breaks at 96K.
3. **“Extrapolation fails because the high-frequency dimensions turn too fast.”** The high-frequency pairs have seen every phase; the trouble comes mainly from the low-frequency pairs with less than one turn. Conversely, PI slows the high-frequency pairs as well and hurts the resolution of local positions.
4. **“Long-context training has to use long sequences from start to end.”** Llama 3's long-sequence stage is only about 5% of its pre-training tokens; in Xiong et al., short-then-long saves about 40% of the FLOPs with almost no change in performance.
5. **“A longer context is just a memory problem.”** Prefill attention compute grows with the square of the length, and the bytes read per decoding step grow with it too; memory is only one aspect.
6. **“The bigger the window the better, so put all the material in.”** Cost grows with length, and models use the middle unreliably. Retrieving first and putting in the relevant passages is often both cheaper and more accurate.

## Summary and exercises

**Key points:**

1. Extending the context means solving position, training and cost together; the advertised window is often longer than the effective length.
2. Pair $i$ of RoPE makes $r_i=L/\lambda_i$ turns within the training length; only the low-frequency pairs with less than one turn get unseen phases at larger distances.
3. PI divides everything by $s$, NTK-aware scaling changes the base to $b'=b\,s^{d/(d-2)}$, YaRN splits by turns and adds the attention scaling $0.1\ln s+1$, and Llama 3.1 uses a piecewise scaling with $\alpha=1$, $\beta=4$.
4. Prefill attention grows with $s^2$ and equals the linear layers at $s^{*}=P_{\text{block}}/(Hd_h)-1$; the KV cache takes $2nGd_hb$ bytes per token; each decoding step reads $W+s\cdot\text{KV}_{\text{token}}$.
5. Recipes: long sequences last, lengthen in stages and check, put the weight on data quality, and add synthetic long data to SFT.
6. Do not rely on needle-in-a-haystack alone: RULER and Lost in the Middle show the effective length is shorter and position matters.

### Quick check

**1. For RoPE with $d=128$, $b=10{,}000$ and a training length of 4096, which pairs make less than one turn within the training length?**

- [ ] The fastest few pairs (small index $i$)
- [x] The slowest 18 pairs (indices 46 to 63)
- [ ] All pairs
- [ ] Only the last pair

> The wavelength of pair $i$ is $2\pi b^{2i/d}$, growing from 6.28 to 54,410; pairs with a wavelength above 4096 make less than one turn, which are indices 46 to 63, 18 pairs. These low-frequency pairs get angles at larger distances that training never showed.

**2. Position interpolation (PI) divides all frequencies by $s$. What is its main side effect?**

- [ ] The low-frequency pairs get unseen phases
- [x] Neighboring tokens differ by only $1/s$ of the angle on the high-frequency pairs, so the resolution of local positions drops
- [ ] The KV cache gets bigger
- [ ] The tokenizer has to be retrained

> PI squeezes all positions of the target length back into the range seen in training, so there are no new phases; the price is that even the fastest pairs are slowed by a factor of $s$, and neighboring positions become harder to tell apart.

**3. What does the NTK-aware base change $b'=b\,s^{d/(d-2)}$ guarantee?**

- [ ] Every pair is divided by exactly $s$
- [x] The fastest pair is unchanged, the slowest is divided by exactly $s$, and the pairs in between change exponentially
- [ ] All low-frequency pairs are brought back into the seen range
- [ ] The attention scores are scaled up by $s$

> $\theta_i'=\theta_i\,s^{-2i/(d-2)}$: the factor is 1 at $i=0$ and $1/s$ at $i=d/2-1$. The other low-frequency pairs have a factor above $1/s$ and still leave new phases.

**4. Why does Llama 3 put long-sequence training at the end of pre-training rather than at the start?**

- [ ] There is not enough long data
- [x] Self-attention compute grows quadratically with sequence length, so long-sequence training is expensive
- [ ] RoPE only converges on short sequences
- [ ] It makes learning-rate annealing easier

> The reason the paper gives is that the compute in self-attention grows quadratically with the sequence length. The long-context stage is about 800B tokens, around 5% of the 15.6T total.

**5. Which of these statements about long contexts are correct? (multiple choice)**

- [x] Attention FLOPs depend only on the number of query heads; GQA shrinks the KV cache, not this term
- [x] Once the sequence is long enough, each decoding step reads more KV than weights
- [ ] FlashAttention removes both the quadratic attention compute and the KV cache
- [x] RULER's results show the advertised window can be longer than the effective length

> FlashAttention reduces memory traffic and never materializes the $s\times s$ matrix; the FLOPs are the same and the KV cache is no smaller. The other three come from the derivations on this page and from the RULER results.

**Exercises:**

1. Derive that the slowest pair of NTK-aware scaling satisfies $\theta'_{d/2-1}=\theta_{d/2-1}/s$.
2. Qwen2.5-7B has 28 layers, 4 KV heads and head dimension 128. How big is the KV cache of a 128K context in BF16?
3. With Llama 3 8B's weights quantized to INT4 and the KV stored in FP8, at what length do KV reads equal weight reads? Why is it shorter than with BF16?
4. DeepSeek-V3 uses $s=40$. What is YaRN's attention scaling factor $0.1\ln s+1$, and by how much are the logits scaled? Why is $4096\times40$ greater than 128K?
5. In Table 7 of the YaRN paper, the $s=16$ 7B model has a perplexity above $10^1$ at 96K, while the $s=32$ model has 2.36. How are their training data related? What does the result show?

<details>
<summary>Reference answers</summary>

1. $\theta'_i=(b')^{-2i/d}=b^{-2i/d}\,s^{-\frac{d}{d-2}\cdot\frac{2i}{d}}=\theta_i\,s^{-2i/(d-2)}$. At $i=d/2-1$ the exponent is $-(d-2)/(d-2)=-1$, so $\theta'_{d/2-1}=\theta_{d/2-1}/s$.
2. $2\times28\times4\times128\times2=57{,}344$ bytes, 56 KiB per token; times 131,072 gives 7,516,192,768 bytes, exactly 7 GiB.
3. A step reads about $15.01\text{GB}\times\tfrac14\approx3.75\text{GB}$ of weights and the KV is 64 KiB per token (FP8), so the crossover is about 57,258 tokens. It is shorter than with BF16 (114,516) because the weights shrink to a quarter while the KV only halves, so the KV's share grows.
4. $0.1\ln40+1=1.369$, and the logits are scaled by $1.369^2=1.874$. $4096\times40=163{,}840>131{,}072$: $s$ was chosen with some margin, and `max_position_embeddings` in DeepSeek-V3's config is 163,840, although the model was trained only to 128K.
5. The $s=32$ model was obtained from the $s=16$ checkpoint by training 200 more steps on 64K data. The result shows that a model is reliable only inside the windows it was trained for: the $s=16$ 64K model breaks at 96K. Extending a bit further is not “margin”; for the length you want, extend, train and test for that length.

</details>

## Further reading

- Related pages: [Efficient Attention](https://dmxsf.com/en/wiki/architecture/efficient-attention/), [Modern LLM Architecture](https://dmxsf.com/en/wiki/architecture/modern-llm-architecture/), [KV Cache and Inference Performance](https://dmxsf.com/en/wiki/inference/kv-cache/).
- Chen et al., [Extending Context Window of Large Language Models via Position Interpolation](https://arxiv.org/abs/2306.15595) (2023): PI, the theory in Section 2.3 and Table 1 in Section 3.2.
- Peng et al., [YaRN: Efficient Context Window Extension of Large Language Models](https://arxiv.org/abs/2309.00071) (2023): NTK-aware, NTK-by-parts, dynamic scaling and the attention temperature; Appendix A.2 derives the base change.
- Xiong et al., [Effective Long-Context Scaling of Foundation Models](https://arxiv.org/abs/2309.16039) (2023): ABF, and ablations of the data mix and the training curriculum.
- Meta, [The Llama 3 Herd of Models](https://arxiv.org/abs/2407.21783) (2024): Section 3.4.2 on long-context pre-training, Section 4.3.4 on long-context SFT, Section 3.3.2 on context parallelism; for `rope_scaling` see the config.json of Llama 3.1 and Meta's [apply_scaling](https://github.com/meta-llama/llama-models/blob/main/models/llama3/model.py).
- DeepSeek-AI, [DeepSeek-V3 Technical Report](https://arxiv.org/abs/2412.19437) (2024): Section 4.3 on long-context extension.
- Ding et al., [LongRoPE: Extending LLM Context Window Beyond 2 Million Tokens](https://arxiv.org/abs/2402.13753) (2024).
- Hsieh et al., [RULER: What's the Real Context Size of Your Long-Context Language Models?](https://arxiv.org/abs/2404.06654) (2024): task design and Table 3.
- Liu et al., [Lost in the Middle: How Language Models Use Long Contexts](https://arxiv.org/abs/2307.03172) (2023).
- Xiao et al., [Efficient Streaming Language Models with Attention Sinks](https://arxiv.org/abs/2309.17453) (2023); Liu et al., [Ring Attention with Blockwise Transformers for Near-Infinite Context](https://arxiv.org/abs/2310.01889) (2023).
- The [`modeling_rope_utils.py`](https://github.com/huggingface/transformers/blob/main/src/transformers/modeling_rope_utils.py) of Hugging Face Transformers: reference implementations of the `linear`, `dynamic`, `yarn` and `llama3` RoPE scalings; the [Qwen2.5-7B-Instruct model card](https://huggingface.co/Qwen/Qwen2.5-7B-Instruct) explains how to enable YaRN.
- Llama 3.1's 128K context: six stages of continued pre-training on about 800B tokens, and the RoPE frequency scaling that is in the released code but not in the paper: see the [Llama 3 breakdown](https://dmxsf.com/en/blog/the-llama-3-herd-of-models/).
- A reproduction of StreamingLLM on Qwen2.5-0.5B: how window attention collapses when the cache fills, how much attention the sink soaks up, why one initial token is enough for this model, and the memory distance measured by a mini StreamEval: see the [paper breakdown](https://dmxsf.com/en/blog/efficient-streaming-language-models-with-attention-sinks/).
- DeepSeek-V3.2 adds the sparse attention DSA to a dense model by continued training, cutting the attention cost of a 128K context from O(L²) to O(Lk): see the [paper breakdown](https://dmxsf.com/en/blog/deepseek-v32-pushing-the-frontier-of-open-large-language-models/).
- DeepSeek-V4.1-Flash reaches a one-million-token context: sequence compression, cross-layer sharing and FP4 multiply to bring the global KV cache down to 890 bytes per token; with the byte layout in the [paper breakdown](https://dmxsf.com/en/blog/deepseek-v41-flash-pushing-the-limits-of-kv-cache-compression/), the global KV of one 1M-token sequence is about 0.87 GiB (sliding-window KV not included).

- Bai et al., [LongBench](https://arxiv.org/abs/2308.14508) (2023) and Yen et al., [HELMET](https://arxiv.org/abs/2410.02694) (2024): taxonomic benchmarks for long-context ability, scoring retrieval, summarization, and reasoning separately so one aggregate cannot hide a weakness.
- Wu et al., [LongMemEval](https://arxiv.org/abs/2410.10813) (2024): grades long-term memory — recalling details from conversations days ago — rather than one-shot long-document stuffing.

## Companion code

[Position encodings and length extrapolation](https://github.com/dmxsf/dmxsf/tree/main/labs/architecture/positional-encoding): Sinusoidal encodings as clocks, RoPE's score depending only on distance, the stretching recipes (position interpolation, NTK-aware, YaRN, the Llama 3.1 rule) computed side by side, and five position schemes trained on short text and tested on long text.

- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run architecture/positional-encoding`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/architecture/positional-encoding/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/architecture/positional-encoding/README.en.md)
- [`position.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/architecture/position.py)
- [Find this lab in the catalog](https://dmxsf.com/en/code/#positional-encoding)

## FAQ

### How do you extend a model trained on 4K or 8K tokens to a 128K context?

In two steps. First change the position encoding: on a RoPE model, rescale the rotation frequencies of the dimensions with position interpolation (PI), NTK-aware base scaling or YaRN, so that new positions land in a range of phases the model has seen. Then continue training on long sequences near the target length, while protecting short-context ability. Llama 3 went from 8K to 128K in six stages at the end of pre-training, using about 800B tokens, roughly 5% of the 15.6T total; DeepSeek-V3 used YaRN (s = 40) and two training phases of 1000 steps each, from 4K to 32K and then to 128K.

### What is the difference between position interpolation (PI), NTK-aware scaling and YaRN?

All three only change RoPE's rotation frequencies. PI divides every frequency by the extension factor s: simple, but the high-frequency dimensions can no longer tell neighboring tokens apart. NTK-aware scaling changes the base to b′ = b·s^(d/(d−2)), which leaves the highest frequency almost untouched and divides the slowest pair by exactly s, but the other low-frequency pairs are still extrapolated slightly. YaRN splits the pairs by how many turns they make within the training length: pairs with many turns are kept, pairs with less than one turn are divided by s, and those in between are blended; it also scales the attention logits by a factor tied to ln s (√(1/t) = 0.1·ln s + 1). In the YaRN paper's experiments it reaches a lower perplexity than PI and NTK-aware scaling with the same fine-tuning budget.

### How big is the KV cache at a 128K context?

Each token caches 2 × layers × KV heads × head dimension × bytes. For Llama 3 8B (32 layers, 8 KV heads, head dimension 128) that is 128 KiB per token in BF16, so 16 GiB at a 128K context; Llama 3 70B (80 layers) needs 320 KiB per token, 40 GiB at 128K. That is the cache of one sequence, and each concurrent request holds its own.

### A model advertises 128K. Why is the quality often worse in practice?

The advertised length only says what the training or configuration supports, not that every task works well. RULER (NVIDIA, 2024) tested 17 models on 13 tasks: all claim at least 32K, but only half keep a score no lower than Llama 2 7B scores at 4K (85.6%) at 32K. Llama 3.1 70B advertises 128K, and RULER puts its effective length at 64K, with the score at 128K down to 66.6. Lost in the Middle adds that models use information in the middle of the context worst. So test on your own task, at the target length and at different positions.

### Do I still need RAG when the context window is long?

Usually yes, the two complement each other. A long context costs more as it grows: attention compute in the prefill grows with the square of the length, the KV cache and the bytes read per decoding step grow linearly, and models use the middle of a long text unreliably. RAG retrieves first and puts in only the relevant passages, which is cheap, keeps knowledge updatable and traceable; a common pattern is to narrow things down with RAG and then use a longer window for more complete material.
