Skip to content
Transformers and LLMs Advanced 28 min read

Long context

A model that accepts a million tokens has to clear four separate walls: quadratic compute, a linearly growing cache, positions it never saw in training, and the harder question of whether it actually uses what it was given. Advertised context length measures only the first three.

10,000 ft

The context window is a language model's working memory: everything it can condition on without retraining. It grew from 2,048 tokens in GPT-3 (2020) to 100K in Claude (May 2023), a million in Gemini 1.5 (2024) and 10 million advertised for Llama 4 Scout (2025). Longer context turns whole codebases, contracts, books and hours of video into a prompt, and it is what lets agents and reasoning models keep long trajectories in view. But attention is quadratic in compute and linear in cache memory, RoPE positions do not extrapolate on their own, long training documents are scarce, and benchmarks show that models which pass the famous needle-in-a-haystack test still degrade badly well before their advertised limit. This page covers all four walls. Alternatives that avoid them by design — retrieval and recurrent and state-space models — are the neighbouring ideas.

2,000 ft

Long context is four problems with four families of fix:

  1. Compute — attention FLOPs grow as \(n^2\). Fixes: fused exact kernels (FlashAttention), local/sliding windows, sparse patterns that pick which keys to read, and splitting one sequence across many GPUs (ring/context parallelism).
  2. Memory — the KV cache grows as \(n\). Fixes: GQA/MLA, cache quantisation, sliding-window layers whose cache is bounded, hybrids with fixed-size recurrent state.
  3. Position — RoPE angles beyond the training length are out of distribution. Fixes: raise the RoPE base before long training, or remap frequencies (position interpolation, NTK, YaRN), then train briefly on long data.
  4. Use — attention dilutes over many tokens, and models favour the start and end of the prompt. Fixes: long, genuinely interdependent training data, staged length curricula, and evaluation beyond the needle test (RULER, NoLiMa, LongBench v2).

Four walls between a model and a usable million-token context
Four walls between a model and a usable million-token context. long prompt (n tokens), Compute O(n²) FLOPs, Memory KV cache O(n), Position unseen RoPE angles, Use dilution, lost in the middle, FlashAttention, sliding window, sparse, ring attention, GQA/MLA, KV quantisation, local layers, hybrids, raise base, PI, NTK, YaRN + short long-data training, long-data curriculum, RULER-style evalsFour walls between a model and a usable million-token context. long prompt (n tokens), Compute O(n²) FLOPs, Memory KV cache O(n), Position unseen RoPE angles, Use dilution, lost in the middle, FlashAttention, sliding window, sparse, ring attention, GQA/MLA, KV quantisation, local layers, hybrids, raise base, PI, NTK, YaRN + short long-data training, long-data curriculum, RULER-style evals

Ground level

What length costs

Take a model shaped like Llama 3 8B (32 layers, width 4,096, 8 KV heads of 128) and feed it one long prompt on one H100 at half of its dense BF16 peak. Real output of the third snippet in Build it:

prompt attention FLOPs ÷ weight-matmul FLOPs prefill time KV cache
8,192 tokens 0.13 0.3 s 1.0 GiB
131,072 tokens 2.15 13.3 s 16.0 GiB
1,048,576 tokens 17.18 617 s 128 GiB

At 8K tokens attention is a rounding error; the familiar \(C \approx 2N\) FLOPs per token holds. At 128K it is already twice the cost of all the weight matmuls, and at a million it is 17 times — about ten minutes of prefill on one GPU and a cache larger than any single GPU's memory. The ratio is \(L\,n\,d/N\), which for a standard dense block is about \(n/(12d)\) (derived on the transformer block page): attention overtakes the rest once the context exceeds roughly twelve times the model width.

So million-token serving is a systems achievement — sharded caches, sparse or hybrid layers, cache reuse across requests — as much as a modelling one.

Why RoPE does not extrapolate

RoPE rotates each of the \(d_h/2\) dimension pairs of every query and key by an angle proportional to position, pair \(i\) at frequency \(\theta_i = b^{-2i/d_h}\) (base \(b\) = 10,000 originally). The fast pairs complete many full turns within the training context: every angle they will ever produce has already been seen. The slow pairs do not. With \(d_h = 128\) and a 4,096-token training context, 18 of the 64 pairs never complete a single turn; the largest angle each of them ever reached was \(\theta_i \times 4096\).

Run the trained model at 32,768 tokens and those 18 pairs produce angles up to 8× larger than anything in training. Because the slow pairs are exactly where models tend to store content-like, position-insensitive information (they barely rotate, so they act almost like position-free channels), corrupting them corrupts what attention reads. Chen et al. found that extrapolating "may lead to catastrophically high attention scores that completely ruin the self-attention mechanism" (arXiv:2306.15595). Perplexity explodes a little past the training length.

Four ways to remap positions

Every fix maps the long context back into angles the model knows. Real output of the first snippet in Build it, extending a 4K-trained model to 32K (\(s = 8\)):

method slow pairs out of trained range worst overshoot fastest pair's speed
extrapolate (do nothing) 18 8.00× 1.000×
position interpolation 0 1.00× 0.125×
NTK-aware base change 17 1.75× 1.000×
YaRN (NTK-by-parts) 0 1.00× 1.000×

Position interpolation (PI) divides every position by \(s\), so 32,768 positions occupy the angles 4,096 used to. Nothing is out of range — but the fast pairs are slowed 8× too, so neighbouring tokens are now an eighth of a step apart in angle and harder to distinguish. A short fine-tune repairs much of this: Chen et al. extended LLaMA 7B–65B "to up to 32768 with minimal fine-tuning (within 1000 steps)", and proved the interpolation error bound is "at least ∼600× smaller than that of extrapolation".

NTK-aware scaling (proposed by the user bloc97 in 2023, credited in the YaRN paper) raises the base instead: \(b' = b\,s^{d_h/(d_h-2)}\). Fast pairs are untouched, the slowest pair is slowed by exactly \(s\), and pairs in between by \(s^{2i/(d_h-2)}\). The table shows the catch: intermediate slow pairs are slowed by less than \(s\) and still overshoot (by up to 1.75×). That is why NTK scaling works surprisingly well without fine-tuning at modest factors but degrades at large ones. Dynamic NTK recomputes \(s\) from the current sequence length at every step, so short prompts are untouched.

YaRN (Peng, Quesnelle, Fan, Shippole, 2023) treats pairs by how many turns they make within the training length, \(r_i = L/\lambda_i\). Pairs with \(r_i < \alpha = 1\) (never a full turn) are interpolated by the full \(s\); pairs with \(r_i > \beta = 32\) (many turns, purely positional) are left alone; a linear ramp blends in between. It also sharpens attention by a temperature, \(\sqrt{1/t} = 0.1\ln s + 1\) (logits × 1.459 at \(s = 8\)), to counter the dilution described below. Its authors report "10x less tokens and 2.5x less training steps than previous methods" (arXiv:2309.00071).

1½¼⅛ r = 32r = 1 PI NTK-aware YaRN pair 0 (fastest)pair 63 (slowest) How much each method slows each RoPE pair when extending 4K → 32K (s = 8, d_h = 128, base 10,000).
PI slows every pair by 8×. NTK slows them geometrically, reaching 8× only at the very last pair. YaRN leaves fast pairs alone, fully interpolates the pairs that never complete a turn in training, and ramps between.

Raise the base before you train long. The cleanest fix needs no remapping: train the long-context stage with a much larger base so the slow pairs stay unambiguous over the new length. Code Llama increased the base "from 10,000 to 1,000,000 for fine-tuning" on 16,384-token sequences and saw "stable behavior on very long sequences of up to 100,000 tokens" (arXiv:2308.12950); Llama 3 used 500,000 from the start of pre-training (arXiv:2407.21783). Remapping methods are what you reach for when you are extending someone else's checkpoint; base changes are what you design in. LongRoPE pushed remapping further by searching for per-pair scale factors, extending to 2 million tokens (arXiv:2402.13753).

The alternatives to RoPE — ALiBi's distance penalty and NoPE layers with no positional signal at all — extrapolate more gracefully by construction, which is why Llama 4 interleaves position-free attention layers among its RoPE layers.

Dilution: why more tokens blur attention

Positions are only half the story. Suppose one "needle" key scores \(\Delta\) logits higher than \(n-1\) equally scored distractors. Its attention weight is

\[ a_\text{needle} = \frac{e^{\Delta}}{e^{\Delta} + (n-1)}. \]

For a fixed margin, this falls as \(1/n\). Real output of the second snippet:

context \(n\) margin 5 margin 8 margin 8, logits × \(\log n/\log 4096\)
1,000 0.129 0.749 0.435
4,096 0.035 0.421 0.421
32,768 0.005 0.083 0.402
131,072 0.001 0.022 0.389
1,048,576 0.000 0.003 0.371

A head that cleanly retrieved its target at 4K gives it 2% of its attention at 128K: the needle's value is drowned in an average of everything else. To keep the needle at 50% the margin must grow as \(\ln n\) — 13.9 logits at a million tokens. Two consequences follow. First, a model trained at 4K never needed such large margins and must learn them during long-context training. Second, scaling logits by \(\log n\) is a principled patch: Chiang and Cholak proposed exactly this ("scaling the logits of each attention layer by \(\log n\)") to fix length generalisation (arXiv:2202.12172), and YaRN's temperature is a fixed version of the same idea.

Training a long-context model

Nobody pre-trains on million-token sequences from scratch: attention cost would dominate, and there is little natural text that long. The standard recipe is pre-train short, then extend:

  • Stage the length. Llama 3 "increased context length gradually in six stages, starting from the original 8K context window" to 128K, using "approximately 800B training tokens", moving to the next stage only once "model performance on short-context evaluations has recovered completely" and "the model perfectly solves 'needle in a haystack' tasks up to that length" (arXiv:2407.21783, §3.4.2).
  • The data matters more than the count. Fu et al. argue the ability to use any position "is mostly already acquired through large-scale pretraining" and that "500 million to 5 billion tokens are enough to enable the model to retrieve information anywhere within the 128K context" — but only with a balanced domain mix, not just upsampled books (arXiv:2402.10171).
  • Mix in short data, and train longer than you evaluate. Gao et al. found code repositories and books are excellent long data but must be combined with high-quality short data, that training beyond the evaluation length helps, and that short instruction data suffices for SFT; their ProLong-8B used "only 5% as many tokens" of long-context training as Llama-3.1-8B-Instruct and outperformed it on most long tasks (arXiv:2410.02660).
  • Mask across documents. When short documents are packed into one long training sequence, a mask that stops tokens attending across document boundaries keeps the model from learning spurious long-range dependencies; it matters most in the long stages (see pre-training data).
  • Spread the sequence over devices. A 128K training sequence's activations exceed one GPU, so long-context stages use context parallelism: each device holds a slice of the sequence and keys/values circulate between devices.

Making attention affordable at length

Exact attention with FlashAttention is the default up to hundreds of thousands of tokens. Beyond that — or to cut cost at any length — models restrict which keys each query reads.

Sliding windows. Each token attends to the previous \(W\) only. Cost per token and cache per layer are bounded by \(W\), and stacking layers still lets information travel: after \(k\) layers a token can draw on \(k(W-1)+1\) positions (checked by matrix powers in the third snippet). Mistral 7B uses \(W = 4096\) and notes "a theoretical attention span of approximately 131K tokens" at the last layer, with a rolling-buffer cache that "reduces the cache memory usage by 8x" at 32K (arXiv:2310.06825). The span is theoretical: information must be relayed hop by hop, and it degrades.

Local–global interleaving. Most layers local, a few global. Gemma 2 alternated them; Gemma 3 increased "the ratio of local to global attention layers" while "keeping the span on local attention short" specifically to tame the cache (arXiv:2503.19786). The global layers do the long-range retrieval; the local layers do the cheap bulk of language modelling.

Sparse patterns. The Sparse Transformer (Child et al., 2019) used strided and fixed patterns for \(O(n\sqrt n)\) attention (arXiv:1904.10509); Longformer combined a sliding window with a few global tokens (arXiv:2004.05150); BigBird added random links and proved such sparse attention keeps the expressive power of full attention (arXiv:2007.14062). Fixed patterns lost to dense attention plus FlashAttention for years. The modern revival is learned, content-dependent sparsity designed around hardware: DeepSeek's Native Sparse Attention combines compressed coarse tokens, selected top blocks and a sliding window, trains end to end, and matches or exceeds full attention while running much faster at 64K (arXiv:2502.11089); DeepSeek-V3.2-Exp (September 2025) uses a light "indexer" to pick the top-scoring keys for each query (model repository). For prefill only, MInference applies dynamic sparse patterns to a dense model without retraining (arXiv:2407.02490).

Ring attention. When one sequence's keys and values don't fit on one device, split it. Each of \(P\) devices holds one block of queries and passes its key/value block around a ring; after \(P - 1\) hops every query block has seen every key block, and each device merges partial results with the online-softmax rule. Communication overlaps with computation, so the context grows with the device count "without resorting to approximations" (Liu, Zaharia, Abbeel, arXiv:2310.01889).

Ring attention: query blocks stay put, key/value blocks circulate
Ring attention: query blocks stay put, key/value blocks circulate. GPU 1 Q block 1 holds KV 1, GPU 2 Q block 2 holds KV 2, GPU 3 Q block 3 holds KV 3, GPU 4 Q block 4 holds KV 4, each GPU merges partial (m, ℓ, Õ) after every hop, KVRing attention: query blocks stay put, key/value blocks circulate. GPU 1 Q block 1 holds KV 1, GPU 2 Q block 2 holds KV 2, GPU 3 Q block 3 holds KV 3, GPU 4 Q block 4 holds KV 4, each GPU merges partial (m, ℓ, Õ) after every hop, KV

Compressive memory and recurrence. Transformer-XL (2019) cached the previous segment's hidden states and attended to them, extending context by recurrence (arXiv:1901.02860); Infini-attention adds a linear-attention memory alongside local attention in every block (arXiv:2404.07143). This line merges into linear attention and state-space models, and into hybrids that keep a few full-attention layers for exact recall.

Does the model use its context?

Accepting a long input is not the same as using it.

Needle in a haystack. Greg Kamradt's 2023 test hides one sentence in a long filler essay at varying depths and asks for it back (repository). It made long-context failures visible as heatmaps and became a release ritual; by 2024 frontier models scored near-perfectly, with Gemini 1.5 reporting "near-perfect retrieval (>99%) up to at least 10M tokens" (arXiv:2403.05530). It is now considered necessary but nowhere near sufficient: the needle shares words with the question, so a single attention head doing literal matching passes it.

Lost in the middle. Liu et al. moved the relevant document around in multi-document QA and found accuracy "is often highest when relevant information occurs at the beginning or end of the input context, and significantly degrades when models must access relevant information in the middle" — a U-shaped curve, "even for explicitly long-context models" (arXiv:2307.03172). Causal masking gives early tokens more chances to be attended (and to become attention sinks); recency favours the end.

RULER generalises the needle into 13 tasks: multiple needles, multi-key and multi-value retrieval, variable tracking across hops, aggregation of frequent words, QA with distractors. Of 17 models evaluated, "while these models all claim context sizes of 32K tokens or greater, only half of them can maintain satisfactory performance at the length of 32K" (arXiv:2404.06654). It introduced the useful notion of effective context length: the longest length at which a model stays above a fixed quality bar.

NoLiMa removes the literal overlap: the question and the needle share no keywords, so the model must make a one-hop association. Of 13 models claiming at least 128K, "at 32K, for instance, 11 models drop below 50% of their strong short-length baselines"; GPT-4o fell from 99.3% to 69.7% (arXiv:2502.05167). LongBench v2 uses 503 hard, realistic multiple-choice questions over 8K to 2M words, where human experts scored 53.7% under a time limit, the best direct-answer model 50.1%, and o1-preview, reasoning at length, 57.7% (arXiv:2412.15204).

Perplexity is not a long-context metric

Perplexity on long documents mostly measures how well the model predicts each token from the last few thousand. A model can have flat, excellent long-document perplexity while being unable to answer a question about page 3 of 300. Evaluate retrieval and reasoning at the lengths you will actually use.

Long context versus retrieval

The practical question is not "how long can it go?" but "should this information be in the prompt at all?". Retrieval-augmented generation selects a few relevant chunks; long context gives the model everything and lets attention select.

Long context Retrieval (RAG)
Cost per query grows with the full corpus in the prompt (prefix caching helps when it repeats) grows with the retrieved chunks only
Latency prefill of the whole context search plus a short prefill
Failure mode dilution, lost in the middle relevant chunk never retrieved
Cross-document reasoning natural hard unless retrieval anticipates it
Corpus size bounded by the window effectively unbounded
Freshness re-send on change re-index on change

In practice the two combine: retrieve generously, then let a long-context model read and reason over dozens of documents instead of three, with stable content placed first so that prefix caches can be reused.

History

From 512 tokens to ten million

2017–2019 — The original transformer trains on sentences; GPT-2 has 1,024 positions, BERT 512. The Sparse Transformer (April 2019) and Transformer-XL (January 2019) attack length by sparsity and recurrence. 2020 — GPT-3 uses 2,048 tokens (arXiv:2005.14165); Longformer, BigBird and a wave of efficient-attention variants. 2021 — RoPE and ALiBi. 2022 — FlashAttention makes exact long attention affordable. 2023 — Position Interpolation (June), NTK-aware scaling on Reddit (June), Anthropic's 100K-token Claude (May), "Lost in the Middle" (July), Code Llama's base change (August), YaRN (August), StreamingLLM and ring attention (September–October). 2024 — Gemini 1.5 and million-token production windows (February), RULER (April), Llama 3.1 at 128K (July). 2025 — Native Sparse Attention (February), NoLiMa (February), Llama 4 Scout advertising 10M tokens (April), DeepSeek's sparse attention in production (September).

First principles

Why attention is quadratic, and what it would take not to be. Every query compares itself with every key because the model does not know in advance which keys matter. Any sub-quadratic method must decide without looking which pairs to skip (fixed sparsity), decide cheaply (learned indexers, compressed summaries), or summarise the past into a fixed-size state (recurrence). Each gives up something: fixed patterns miss unexpected dependencies, cheap selectors miss what they can't score well, and fixed states cannot hold arbitrarily many independent facts — the trade-off made precise in beyond transformers.

Why position must be interpolated, not extrapolated. A neural network is reliable on inputs from its training distribution. RoPE's slow pairs at unseen lengths produce rotation angles that are literally outside that distribution; no amount of clever reading fixes a feature that has never been seen. Interpolation trades this for a denser use of seen angles, which a short fine-tune can learn to resolve. Raising the base before long training makes the problem never arise.

Why dilution is unavoidable with softmax. Softmax is a competition with a fixed total budget of 1. Adding \(n\) competitors with similar scores divides any winner's share by about \(n\). To keep a winner, its logit margin must grow as \(\ln n\), which means larger query/key norms or sharper heads — a capability the model must learn for each length it is trained at. This is also why models trained short and used long behave as though they are "distracted".

Why the middle is lost. Under a causal mask the first tokens are visible to every query, so training pushes attention mass onto them (attention sinks), and recency matters most for next-token prediction, so heads also favour the end. Information in the middle has neither advantage. Training on tasks that require middle retrieval flattens the U but does not remove the underlying biases.

The maths

RoPE frequencies and wavelengths. For head dimension \(d_h\), base \(b\) and pair \(i = 0, \dots, d_h/2 - 1\):

\[ \theta_i = b^{-2i/d_h},\qquad \lambda_i = \frac{2\pi}{\theta_i} = 2\pi\, b^{2i/d_h}. \]

Pair \(i\) completes a full turn within training length \(L\) iff \(\lambda_i \le L\), i.e.

\[ i \le \frac{d_h}{2}\log_b\!\frac{L}{2\pi}. \]

For \(b = 10^4\), \(d_h = 128\), \(L = 4096\): \(64 \times \log_{10^4}(651.9) = 64 \times 0.7036 = 45.0\), so pairs 0–45 complete a turn and the 18 pairs 46–63 do not.

Position interpolation replaces position \(m\) by \(m/s\), i.e. \(\theta_i \to \theta_i/s\) for all \(i\), with \(s = L'/L\).

NTK-aware scaling replaces the base: \(b' = b\,s^{d_h/(d_h-2)}\), giving per-pair factor

\[ \frac{\theta'_i}{\theta_i} = s^{-2i/(d_h-2)}, \]

which is 1 for \(i = 0\) and exactly \(1/s\) for the last pair \(i = d_h/2 - 1\).

YaRN (NTK-by-parts). With \(r_i = L/\lambda_i\) and ramp \(\gamma(r) = 0\) for \(r < \alpha\), \(1\) for \(r > \beta\), \((r-\alpha)/(\beta-\alpha)\) otherwise:

\[ \theta'_i = \big(1 - \gamma(r_i)\big)\frac{\theta_i}{s} + \gamma(r_i)\,\theta_i, \qquad \text{logits} \times \frac{1}{t},\quad \sqrt{\tfrac{1}{t}} = 0.1\ln s + 1, \]

with \(\alpha = 1\), \(\beta = 32\) recommended for the Llama family.

Derivation: the margin a needle needs grows as ln n

Let one key have logit \(z + \Delta\) and \(n - 1\) keys have logit \(z\). Softmax is shift-invariant, so

\[ a = \frac{e^{z+\Delta}}{e^{z+\Delta} + (n-1)e^{z}} = \frac{e^\Delta}{e^\Delta + n - 1}. \]

Setting \(a\) to a target \(a^\ast\) and solving: \(e^\Delta(1 - a^\ast) = a^\ast(n-1)\), so

\[ \Delta = \ln\frac{a^\ast}{1-a^\ast} + \ln(n-1) \approx \operatorname{logit}(a^\ast) + \ln n. \]

For \(a^\ast = \tfrac12\), \(\Delta = \ln(n-1)\): 8.3 at \(n = 4096\), 13.9 at \(n = 2^{20}\). If distractor logits are not equal but spread with variance \(\sigma^2\) (approximately Gaussian), \(\sum e^{z_j} \approx (n-1)e^{\bar z + \sigma^2/2}\) and the requirement becomes \(\Delta \approx \ln n + \sigma^2/2 + \operatorname{logit}(a^\ast)\): noisy distractors make it worse. Multiplying all logits by \(c\ln n\) multiplies \(\Delta\) too, which is why log-length scaling keeps the needle's share roughly constant.

Attention cost. For \(L\) layers of width \(d\), a causal prompt of \(n\) tokens costs about

\[ C_\text{prefill} \approx 2Nn + 2Ln^2d,\qquad \frac{C_\text{attn}}{C_\text{dense}} = \frac{Lnd}{N} \approx \frac{n}{12d}\ \ (N \approx 12Ld^2), \]

and decoding token \(t\) adds \(4Ltd\) FLOPs and reads \(2Lh_{kv}d_h t\) cached numbers.

Sliding window reach. With window \(W\) (a token sees itself and the \(W-1\) before it), the set of input positions that can influence position \(t\) after \(k\) layers is \([t - k(W-1), t]\): each layer extends the reach by \(W - 1\). The reachability matrix is the \(k\)-th Boolean power of the banded mask.

Build it

1. Where RoPE extrapolation breaks, and what each fix does.

import numpy as np
d, base, L, Lnew = 128, 10_000, 4_096, 32_768   # head dim, RoPE base, trained length, target length
s = Lnew / L                                     # extension factor (8)
i = np.arange(d // 2)
theta = base ** (-2 * i / d)                     # rotation per position for each of the 64 pairs
wavelength = 2 * np.pi / theta                   # positions per full turn

def yarn(theta, alpha=1, beta=32):               # "NTK-by-parts" frequencies (YaRN eq. 13)
    r = L / (2 * np.pi / theta)                  # full turns each pair makes within the trained length
    g = np.clip((r - alpha) / (beta - alpha), 0, 1)
    return (1 - g) * theta / s + g * theta

methods = {
    "extrapolate (do nothing)": theta,
    "position interpolation":   theta / s,
    "NTK-aware base change":    (base * s ** (d / (d - 2))) ** (-2 * i / d),
    "YaRN (NTK-by-parts)":      yarn(theta),
}
seen = theta * L                                 # largest angle each pair reached in training
print(f"pairs that never complete a turn in {L} tokens: {(wavelength > L).sum()} of {d//2}")
print(f"{'method':26s} {'slow pairs out of range':>24s} {'worst overshoot':>16s} {'fastest pair speed':>19s}")
for name, th in methods.items():
    ood = ((th * Lnew > seen * 1.0001) & (wavelength > L)).sum()   # slow pairs leave the seen range
    over = (th * Lnew / seen)[wavelength > L].max()                  # 1.0 = stays inside what training saw
    print(f"{name:26s} {ood:>24d} {over:>15.2f}x {th[0] / theta[0]:>18.3f}x")
print("YaRN attention temperature: logits x", round((0.1 * np.log(s) + 1) ** 2, 4))
pairs that never complete a turn in 4096 tokens: 18 of 64
method                      slow pairs out of range  worst overshoot  fastest pair speed
extrapolate (do nothing)                         18            8.00x              1.000x
position interpolation                            0            1.00x              0.125x
NTK-aware base change                            17            1.75x              1.000x
YaRN (NTK-by-parts)                               0            1.00x              1.000x
YaRN attention temperature: logits x 1.4591

2. Dilution, and log-length scaling.

import numpy as np
# One "needle" key scores delta above n-1 identical distractor keys. How much attention does it get?
def needle_weight(delta, n): return np.exp(delta) / (np.exp(delta) + n - 1)
n_train = 4_096
print(f"{'context n':>10s} {'margin 5':>9s} {'margin 8':>9s} {'margin 8, log-n scaled':>23s}")
for n in [1_000, 4_096, 32_768, 131_072, 1_048_576]:
    scaled = 8 * np.log(n) / np.log(n_train)      # logits multiplied by log n / log n_train
    print(f"{n:>10,d} {needle_weight(5, n):>9.3f} {needle_weight(8, n):>9.3f} {needle_weight(scaled, n):>23.3f}")
print("margin needed for 50% weight at n = 1M:", round(np.log(1_048_575), 2))
 context n  margin 5  margin 8  margin 8, log-n scaled
     1,000     0.129     0.749                   0.435
     4,096     0.035     0.421                   0.421
    32,768     0.005     0.083                   0.402
   131,072     0.001     0.022                   0.389
 1,048,576     0.000     0.003                   0.371
margin needed for 50% weight at n = 1M: 13.86

3. Sliding-window reach, and the price of a long prompt.

import numpy as np
# 1) Sliding-window attention: how far back can information travel after k layers?
n, W = 200, 8                                    # tokens, window (each token sees itself + 7 previous)
i, j = np.indices((n, n))
M = ((j <= i) & (i - j < W)).astype(int)         # one layer's causal sliding-window mask
reach = np.eye(n, dtype=int)
for k in range(1, 6):
    reach = (M @ reach > 0).astype(int)          # composition of k layers
    print(f"after {k} layer(s): last token can draw on {reach[-1].sum():3d} tokens (k*(W-1)+1 = {k*(W-1)+1})")

# 2) What a long prompt costs: Llama-3-8B-shaped model (32 layers, width 4096, 8 KV heads x 128)
N, L, d = 8.0e9, 32, 4096
for ctx in [8_192, 131_072, 1_048_576]:
    dense = 2 * N * ctx                          # matmuls with the weights
    attn = 2 * L * ctx**2 * d                    # causal QK^T and AV: 4*L*d per pair, half the pairs
    kv_gib = ctx * 2 * L * 8 * 128 * 2 / 2**30
    secs = (dense + attn) / (0.5 * 989e12)       # one H100 at 50% of dense BF16 peak
    print(f"{ctx:>9,d} tokens: attention/dense FLOPs = {attn/dense:5.2f}, prefill ~ {secs:7.1f} s, KV cache {kv_gib:6.1f} GiB")
after 1 layer(s): last token can draw on   8 tokens (k*(W-1)+1 = 8)
after 2 layer(s): last token can draw on  15 tokens (k*(W-1)+1 = 15)
after 3 layer(s): last token can draw on  22 tokens (k*(W-1)+1 = 22)
after 4 layer(s): last token can draw on  29 tokens (k*(W-1)+1 = 29)
after 5 layer(s): last token can draw on  36 tokens (k*(W-1)+1 = 36)
    8,192 tokens: attention/dense FLOPs =  0.13, prefill ~     0.3 s, KV cache    1.0 GiB
  131,072 tokens: attention/dense FLOPs =  2.15, prefill ~    13.3 s, KV cache   16.0 GiB
1,048,576 tokens: attention/dense FLOPs = 17.18, prefill ~   616.8 s, KV cache  128.0 GiB

Things to try

  • In snippet 1, change base to 500,000 (Llama 3) and L to 8,192. How many pairs never complete a turn? Extend to 128K and compare the four methods.
  • Plot the NTK-aware overshoot per pair. Which pairs overshoot most, and why are they the middle ones rather than the slowest?
  • In snippet 2, give the distractors Gaussian logits with standard deviation 1 instead of equal ones. Check the derivation's prediction that the needed margin rises by about \(\sigma^2/2\).
  • Build your own needle test: generate a 20,000-token haystack of random "key: value" lines, insert one target, and query a local model at depths 0%, 25%, 50%, 75%, 100%. Do you see the U?
  • Add one global token (attends to and from everyone) to the sliding-window mask in snippet 3. How many layers does information now need to cross 200 positions?

In practice

  • Read the effective length, not the advertised one. Look for RULER-style or NoLiMa-style results at the lengths you need, and run your own needle-plus-reasoning test on your data.
  • Put instructions at the end, documents at the start. Long-context guides from model providers commonly recommend placing long documents first and the question last; the U-shaped curve explains why.
  • Cost scales with what you send. At API prices, a 500K-token prompt costs hundreds of times a retrieval prompt. Use prompt/prefix caching for repeated long context, and retrieval to prune what isn't needed.
  • Extending an open model: use YaRN or the base-change built into the checkpoint's RoPE scaling config, then continue training on a few billion tokens of balanced long data mixed with short data, and verify short-context benchmarks have recovered.
  • Serving long context: cache size, not FLOPs, usually sets the limit on concurrency — see the per-token cache table in KV cache and efficient attention.

Common misconceptions

  • "A 1M-token window means the model reasons over 1M tokens." It means it accepts them. Effective use is measured separately and is usually much shorter for anything harder than literal retrieval.
  • "Passing needle-in-a-haystack proves long-context ability." The needle shares keywords with the question, so a single literal-matching head passes it.
  • "Sliding-window models see 131K tokens." Their theoretical receptive field is that large; information must hop window by window through layers and degrades on the way.
  • "Long context makes RAG obsolete." Cost, latency and corpus size still favour retrieval for large or changing collections; the best systems combine both.

Check yourself

With d_h = 128 and base 10,000, which RoPE pairs complete a full turn within a 4,096-token training context, and why do the others cause trouble beyond it?

Pair \(i\) completes a turn iff \(\lambda_i = 2\pi b^{2i/d_h} \le 4096\), i.e. \(i \le 64\log_{10^4}(4096/2\pi) = 45.0\). Pairs 46–63 never complete a turn, so the angles they produce beyond 4,096 tokens were never seen in training.

Position interpolation removes out-of-range angles. What does it cost, and how does YaRN avoid that cost?

It slows every pair by \(s\), including the fast pairs that resolve neighbouring tokens; adjacent positions become \(1/s\) of a step apart in angle. YaRN interpolates only the pairs that never complete a turn within the training length, leaves high-frequency pairs untouched, and ramps between them.

A needle scores 8 logits above 131,071 equal distractors. What attention weight does it get? What margin would give it 50%?

\(e^8/(e^8 + 131{,}071) = 2981/134{,}052 \approx 0.022\). For 50%: \(\Delta = \ln(131{,}071) \approx 11.8\).

Why does attention compute overtake the weight matmuls at long context, and at roughly what length for a model of width d?

Per token, weight matmuls cost about \(2N \approx 24Ld^2\) FLOPs, while attention costs about \(2Lnd\) averaged over a causal prompt (scores plus weighted sum over the prefix). The ratio is \(n/(12d)\), so attention dominates beyond about \(12d\) tokens: roughly 49K tokens for \(d = 4096\).

Mistral 7B uses a 4,096-token sliding window and 32 layers. What is the theoretical receptive field, and why isn't it the effective one?

About \(32 \times 4096 \approx 131\)K tokens. Information from far back must be relayed through intermediate positions, one window per layer, and each hop mixes it with other content; long-range facts arrive weakened and blurred, so retrieval of a specific distant token is unreliable.

Hard: why do NoLiMa scores fall much faster with length than needle-in-a-haystack scores?

In NIAH, question and needle share keywords, so a head can match them by near-literal similarity — a large logit margin that survives dilution. NoLiMa removes lexical overlap, so the needle must be found by a latent association with a smaller margin; dilution (\(a \approx e^\Delta/n\)) then drives its attention weight down quickly as \(n\) grows, and multi-hop association compounds the loss.

Hard: ring attention distributes one sequence over P GPUs. Why is the result exact, and what limits it?

Each GPU keeps its query block and receives every key/value block once as they circulate; it accumulates partial \((m, \ell, \tilde O)\) states and merges them with the exact online-softmax rule, which is associative and commutative. Limits: total compute is still quadratic; each hop must transfer a KV block fast enough to overlap with the block's attention compute (so blocks must be large enough); and causal masking makes work unbalanced across devices unless blocks are permuted.

Go deeper

Papers

Videos and lectures

Articles and blog posts

Courses and books

Code

Where this leads