6.13 — Long-context attention: sliding window, ALiBi, and RoPE scaling
Goal: Survey three families of long-context mechanisms — sliding-window attention (Mistral), ALiBi bias-based positions (Press et al., 2021), and RoPE scaling techniques (linear, NTK-aware, YaRN) — that let a model trained on a few-k context handle 32k, 128k, or 1M tokens.
1. Why this session exists
6.12 made the cost of long-context attention precise: the score-and-mix term dominates for , and the KV cache grows linearly in . A 128k-token prompt for a model costs roughly more attention FLOPs than a 2k prompt, and 64 more KV-cache memory.
This session surveys three families of techniques that bend the cost curve back. Each attacks a different piece:
- Sliding-window attention (Mistral, Longformer). Restrict each token to a local window of width . Per-token cost drops from to , total to . Global reach is recovered through layer-by-layer "information bubbling".
- ALiBi (Press et al., 2021)[1]. Drop explicit positional encodings; add a linear bias inside the softmax. Trains at one length and extrapolates to longer contexts at inference time, without retraining.
- RoPE scaling (linear, NTK-aware, YaRN). Reuse a RoPE-trained model at much longer context by rescaling its rotational frequencies. The dominant approach in 2024–2026 LLMs that ship with 128k+ context windows.
By session end you should be able to read the long-context section of any 2024–2026 model card (LLaMA-3, Mistral, Gemini, Claude) and identify which combination they use.
2. Sliding-window attention
The simplest idea: cap the attention range. Pick a window size (Mistral 7B uses ) and let each token attend only to the previous tokens, i.e. positions in . The mask becomes a band rather than a lower-triangle:
The score matrix has the same shape as before, but only a band of width contributes after softmax. Per-token attention cost drops from to ; total attention cost is instead of — linear in .
2.1 Why local attention does not blind the model to distant content
A natural concern: if every token only sees the past tokens, how does information at position reach position ? Answer: through the layer stack.
Each layer is a sliding window of size . After layers stacked, an output token has an effective receptive field of . The Longformer paper (Beltagy et al., 2020, arXiv:2004.05150)[4] calls this the "Transformer's CNN-like receptive field" — each layer extends the local view, and the composition reaches arbitrary distances given enough layers.
For Mistral 7B: . Effective receptive field — comfortably enough to cover the 32k context the model trains on.
2.2 Variants: dilated, global tokens, attention sinks
Three commonly-paired ideas:
- Dilated windows (Beltagy et al.): at layer , use a stride- window so that the receptive field grows multiplicatively with depth.
- Global tokens. A small set of "always-attended" positions (e.g., [CLS], the first tokens) that every layer attends to in full. Resolves the early-token bottleneck.
- Attention sinks (Xiao et al., 2023, arXiv:2309.17453)[6]. Always include the first 4 tokens in the window. Empirically, language models concentrate disproportionate attention on these "sink" tokens; including them in any local window prevents the softmax from being starved of well-positioned mass. StreamingLLM uses this to extend context indefinitely with constant memory.
Mistral 7B uses plain sliding window + a few attention sinks. The combination matches full attention on standard benchmarks at significantly lower cost.
2.3 Compute and memory savings
Per block:
The score-mix is now linear in (with as the multiplicative constant). For :
an 8× reduction. Memory follows: KV-cache can be capped at tokens (rolling buffer), making constant-memory streaming generation possible.[5]
3. ALiBi: Attention with Linear Biases
ALiBi (Press, Smith, Lewis, 2021, arXiv:2108.12409) takes a different angle: keep full attention, but drop explicit positional encodings entirely. Replace them with a fixed bias added to the attention scores that depends only on relative position:
(For causal attention , so the bias is non-negative inside softmax-pre-image.) Here is a fixed (not learned) per-head slope; ALiBi recommends for head , giving a geometric progression of slopes across heads.
3.1 Why this is "positional information"
The bias is a monotonically decreasing function of distance. Closer keys score higher (less penalty); distant keys score lower (more penalty). The model still uses softmax to choose where to look, but the prior over relative positions is encoded directly in the bias.
Different heads have different slopes :
- Steep slopes ( large) → head attends mostly to nearby tokens.
- Shallow slopes ( small) → head attends to a wider range, including distant tokens.
The geometric schedule ensures coverage of multiple timescales — analogous to RoPE's per-pair frequency schedule (6.7 §4), but simpler.
3.2 The headline property: length extrapolation
ALiBi's pitch is train at length , infer at length , without finetuning. Because the bias is just , it is well-defined at any distance — there is no learned-PE table that runs out of rows, no rotation frequency tuned to a specific window. Press et al. demonstrated training at and using the same model at with no quality degradation; the equivalent learned-PE model collapses past its training length.
This is what "length extrapolation" means and ALiBi is the cleanest example. It buys universally-defined positional information by giving up learned position-conditioning entirely — the function is fixed for ever.
3.3 Trade-offs vs RoPE
ALiBi is simple and extrapolates cleanly, but it has a structural ceiling: every head's bias is monotonic in distance. There is no way to express "this token at distance 5 is special" except via the content-dependent term — which is also doing the heavy lifting in any attention model. RoPE, in contrast, lets the dot product have arbitrary dependence on (modulated by content), at the cost of being defined only up to the trained-frequency range.
In practice: ALiBi is used by BLOOM, MPT-7B, and a few smaller research models. Most frontier LLMs use RoPE + scaling techniques (§4 below) for long context, because RoPE's flexibility outweighs its training-length issue when you can fix the latter.
4. RoPE scaling
Modern frontier LLMs are RoPE-trained (6.7). The challenge: RoPE's rotation rate for pair is , which is chosen so that the full set of frequencies covers wavelengths from ~ token (high frequency) to ~ tokens (low frequency). Train on — every position is within the low-frequency wavelength, and the model learns to use them. At inference with , positions wrap multiple times in the low-frequency pairs and the model has never been exposed to those wrap-points.
The fix is to rescale the rotation frequencies so that the model "sees" the longer context as if it were shorter. Three flavours.
4.1 Position interpolation (linear scaling)
Chen et al., 2023[2], Extending Context Window of Large Language Models via Positional Interpolation (arXiv:2306.15595). Idea: instead of rotating by angle at position , rotate by with . Equivalently, map positions linearly into the training range:
At , every rotation angle is scaled by . The model never sees a rotation angle it was not trained on. A short fine-tune (~1000 steps) lets the model adapt to the new effective resolution.
Linear interpolation is the simplest scaling and works well up to about extension. Past that, the lowest frequencies become so squashed that they lose discriminating power between nearby positions.
4.2 NTK-aware scaling
The Neural Tangent Kernel observation (anonymous community post on r/LocalLLaMA, June 2023; later formalised in the YaRN paper): linear interpolation squashes all frequencies, including the high-frequency ones that the model uses for local order. Better idea — scale the base of the frequency schedule rather than the rotation rate directly. Set
The exponent for large , so . The effect: high-frequency pairs (small , near ) are barely changed; low-frequency pairs (large , near ) are stretched. Local order is preserved; global position information is rescaled.
NTK-aware extends up to about training length with no fine-tuning at all.
4.3 YaRN
Peng, Quesnelle, Fan, Shippole, 2023[3], YaRN: Efficient Context Window Extension of Large Language Models (arXiv:2309.00071). Refines NTK-aware: instead of one global , apply different scalings to different frequency bands. Three regions:
- High-frequency pairs. Already wrap many times within ; the model treats them as essentially uniform over . Don't rescale.
- Mid-frequency pairs. Partially wrapped. Use NTK-aware scaling.
- Low-frequency pairs. Less than one full period in . Linear-interpolate (gentlest scaling).
The piecewise schedule is parameterised by two cut-off frequencies and chosen by inspection. YaRN also includes a small fine-tune step (~ of pretraining tokens) that adapts the model to the new effective frequencies. Together, YaRN extends 4k-trained models to 64k or 128k with near-zero loss in quality.
YaRN is the de facto context-extension method in 2024–2026 LLM releases. LLaMA-3 long-context variants, DeepSeek-V2, Qwen-2 long-context — all use YaRN or close variants.
5. The 2026 long-context recipe
What a frontier LLM does to ship a 128k+ context window:
- Pretrain at a moderate context (e.g., LLaMA-3 trains at 8k).
- Continue training at longer context (e.g., 32k–128k) using RoPE scaling (linear or NTK-aware as a warm start, YaRN for final).
- Add long-context-targeted data: long documents, books, code repos, technical papers.
- (Optional) Sliding-window attention as an additional cost-cutter at inference, paired with attention sinks.
- Evaluate on long-context benchmarks: Needle-in-a-Haystack, RULER, LongBench, BABILong.
The total compute for long-context extension is typically – of the pretraining compute. The model emerges with a 4k–8k "native" base and a 32k–1M-capable inference window after RoPE scaling + a brief continued training run.
Three frontier examples (rough sketches; exact recipes vary):
- LLaMA-3-8B-Instruct-128k. Trained at 8k, extended to 128k via RoPE scaling + 800B tokens of long-context training.
- Mistral Large 2. RoPE + sliding-window attention; 128k context.
- Gemini 1.5 Pro. 1M context via a combination of long-context training, sliding-window-and-cross-attention, and Ring Attention (sequence parallelism, beyond this chapter).
6. What we keep going forward
Three different ways to make attention long-context-capable, each addressing a different cost:
Modern frontier LLMs combine RoPE scaling (the dominant choice) with sliding-window attention (for inference cost). ALiBi is used by a few smaller models and remains the cleanest theoretical answer to the length-extrapolation problem. The KV cache itself (next session, 6.14) is the other big inference-side optimisation, and lands properly there.
(a) Compute the per-block FLOP saving of sliding-window attention with versus full attention at , given . Now compute the same ratio at .
(b) Argue why, in a sliding-window Transformer with layers and window , information from position can reach position within the same forward pass. Is the path linear or non-linear in ?
(c) Write the ALiBi attention score for a head with slope at positions , given . Recompute for . Argue that the model still has full freedom to attend to if is large enough.
(d) RoPE linear interpolation at rescales each rotation angle by . State what happens to (i) the wavelength of the highest-frequency RoPE pair, (ii) the wavelength of the lowest-frequency RoPE pair, under this rescaling. Why does this break "local order" for very large ?
(e) YaRN applies different scalings to different RoPE frequency bands. Explain why, intuitively, high-frequency pairs are safe to leave alone, while low-frequency pairs must be rescaled.
References
- [1]
Press, O., Smith, N. A., & Lewis, M. (2021). "Train short, test long: Attention with linear biases enables input length extrapolation" (ALiBi). arXiv:2108.12409 — Linear-distance bias inside softmax; length extrapolation (6.13 §3).
↩ - [2]
Chen, S., Wong, S., Chen, L., & Tian, Y. (2023). "Extending context window of large language models via positional interpolation". arXiv:2306.15595 — Linear interpolation of RoPE frequencies for context extension (6.13 §4.1).
↩ - [3]
Peng, B., Quesnelle, J., Fan, H., & Shippole, E. (2023). "YaRN: Efficient context window extension of large language models". arXiv:2309.00071 — Piecewise RoPE scaling (NTK-aware + linear-interpolation hybrid) (6.13 §4.3).
↩ - [4]
Beltagy, I., Peters, M. E., & Cohan, A. (2020). "Longformer: The long-document transformer". arXiv:2004.05150 — Sliding-window + global attention with dilations (6.13 §2).
↩ - [5]
Jiang, A. Q., Sablayrolles, A., Mensch, A., et al. (2023). "Mistral 7B". arXiv:2310.06825 — Sliding-window attention at scale; pairs with attention sinks (6.13 §2).
↩ - [6]
Xiao, G., Tian, Y., Chen, B., Han, S., & Lewis, M. (2023). "Efficient streaming language models with attention sinks" (StreamingLLM). arXiv:2309.17453 — Attention sinks for constant-memory streaming (6.13 §2.2).
↩