Foundations to Frontier
Tests
F. NLP and Large Language Models › F4 Transformer Language Models

Long-Context Techniques: RoPE Scaling, Sliding-Window and Ring Attention

Using an LLM on documents longer than its training sequences runs into two problems. Positions beyond the trained range behave unpredictably, and attention cost and memory grow with the square of length. Position fixes rescale RoPE: position interpolation squeezes new positions into the trained range; NTK-aware and YaRN scaling stretch only the low frequencies. These are usually followed by a short fine-tune at the target length. Efficiency fixes restrict or distribute attention: sliding-window attention lets each token see only the last w tokens (Mistral); FlashAttention avoids materialising the attention matrix; ring attention splits a long sequence across devices and passes key/value blocks around a ring. This page covers these methods and their trade-offs. In the exercises you implement sliding-window masks, position interpolation, NTK-aware scaling and ring scheduling, then test strategies on positions 17–48 for a RoPE model trained on 16 tokens. As-is, it failed (loss 2.13, floor 0.50). A 16-token sliding window fixed it with no retraining (0.61). Interpolation without fine-tuning made things worse (2.80). A 100-step fine-tune at length 48 worked best (0.54), while interpolation plus the same fine-tune reached only 1.59 on this exact-offset task.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Reading documents longer than the training texts

A model trained on short passages can get confused by very long ones: it has never seen words that far apart. One fix is to let each word look only at a recent window of words, so distances never exceed what it was trained on (information can still travel further through many layers). Another is to stretch the position code so long documents look short, then practise briefly on long texts. And to fit very long texts at all, the work can be split across many GPUs passing pieces around in a ring. The demo shows how memory grows with context length.

LLM lab
7B-class model (32 layers, 32 query heads of 128 dims, fp16) at 8192 tokens: full multi-head KV cache 4.00 GiB; with 8 KV heads (grouped-query attention) 1.00 GiB per sequence.
Why engineers care

Whole maintenance manuals, long telemetry logs and multi-hour transcripts exceed short context windows. Knowing how long-context models are built tells you when they can be trusted at full length.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Sliding-window attention lets each token see…
  2. 2. Position interpolation makes long sequences…
  3. 3. Ring attention spreads a long sequence across…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • The two problems: unseen positions (F4-4 showed RoPE fails beyond its training length) and quadratic cost: a materialised 128k × 128k attention matrix is 32 GiB per head in fp16.
  • Position interpolation (PI): use positions m · T_train/T_target (factor 1/8 to extend 4k to 32k), so all angles stay in range; it needs fine-tuning.
  • NTK-aware / YaRN scaling: enlarge the RoPE base, base’ = base · s^(d/(d−2)), so low frequencies stretch while high frequencies (local order) stay intact. YaRN also tempers the attention logits. These need little or no fine-tuning.
  • Sliding-window attention: each token attends to the last w tokens. Cost becomes linear in length, and with L layers information can still travel about L(w − 1) positions (32 layers × 4096 ≈ 131k for Mistral 7B). Often mixed with global or sink tokens (StreamingLLM keeps the first tokens).
  • FlashAttention: exact attention computed block by block in fast on-chip memory, never storing T × T.
  • Ring attention / sequence parallelism: split the sequence across N devices (1M tokens / 64 devices = 16k each); KV blocks rotate around the ring, so after N steps every query block has seen every KV block.
📝 Quick check (Level 1)
0/3 answered
  1. 1. PI factor to extend 4k to 32k:
  2. 2. Reach of 32 layers with window 4096:
  3. 3. Tokens per device for 1M tokens over 64 devices:

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Long context in code

Exercise 1.

  • Build a sliding-window causal mask.
  • Compute interpolated positions and an NTK-aware RoPE base.
  • Count ring-attention steps.

Practice.

  • Hugging Face models accept rope_scaling={"type": "linear" or "dynamic" or "yarn", "factor": s}; Mistral-style models expose sliding_window.
  • Use FlashAttention (attn_implementation="flash_attention_2") for long sequences; it is exact and memory-linear.
  • After changing position scaling, fine-tune briefly on long documents and evaluate with long-range tests (needle-in-a-haystack, RULER), not just perplexity.
  • Long contexts are expensive in KV-cache memory (F8-2); retrieval (F10) is often the cheaper way to use long documents.
from transformers import AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf",
            rope_scaling={"type": "linear", "factor": 4.0},        # 4k -> 16k by position interpolation
            attn_implementation="flash_attention_2", torch_dtype="bfloat16")
# then fine-tune briefly on 16k-token documents before trusting long-range answers
🐍 Exercise 1: windows, interpolation and rings
Implement a sliding-window mask, interpolated positions, the NTK-aware RoPE base and ring-attention step counting.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Hugging Face option for RoPE scaling:
  2. 2. A long-range evaluation:
  3. 3. FlashAttention is…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Why a sliding window extrapolates. With a window no larger than the training length, every query–key offset the model ever sees at inference was seen in training. The model’s learned behaviour is therefore valid at any sequence length. The price is that direct attention cannot reach beyond w; long-range information must hop through layers or be lost.

Why interpolation needs fine-tuning. Interpolation keeps angles in range but changes their meaning: offset 8 now produces the angles that offset 8·s used to. Unless the model is retrained, a learned lookup at a specific offset breaks. Interpolation also reduces the angular gap between neighbouring positions, making exact offsets harder to resolve. That hurt the exact copy task here, while for natural language, where precise long offsets matter less, it works well after fine-tuning.

Exactness vs approximation. FlashAttention and ring attention compute exact attention more efficiently. Sliding windows, sparse and linear attention change the model’s function. Which one to use depends on whether the task needs exact long-range retrieval.

📝 Quick check (Level 3)
0/3 answered
  1. 1. A window no larger than the training length means…
  2. 2. Interpolation changes…
  3. 3. Ring attention computes…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Which long-context strategy rescues a model beyond its training length?

History.

  • S. Chen, S. Wong, L. Chen and Y. Tian, “Extending context window of large language models via positional interpolation” (2023).
  • B. Peng, J. Quesnelle, H. Fan and E. Shippole, “YaRN: efficient context window extension of large language models” (ICLR 2024).
  • A. Q. Jiang et al., “Mistral 7B” (2023), sliding-window attention.
  • H. Liu, M. Zaharia and P. Abbeel, “Ring attention with blockwise transformers for near-infinite context” (ICLR 2024).
  • T. Dao et al., “FlashAttention” (NeurIPS 2022).

Exercise 2.

  • Base model: the one-layer RoPE GPT from F4-4, trained on 16-token copy-8-back sequences. Evaluated on positions 17–48 of 48-token sequences (floor 0.50 nats).
  • Strategies:
    • as is;
    • a 16-token sliding window at inference;
    • position interpolation (positions × 16/48) without fine-tuning;
    • 100 fine-tuning steps on 48-token data, with or without interpolation.
strategy loss on positions 17–48
RoPE as is 2.130
sliding window of 16, no retraining 0.611
position interpolation, no fine-tune 2.804
fine-tune 100 steps at length 48 0.540
interpolation + fine-tune 100 steps 1.594
  • Sliding windows rescue the model for free: all offsets at inference are ones it was trained on, and the task only needs offset 7.
  • Interpolation without fine-tuning is harmful: it changes what every offset looks like, so the learned “8 back” lookup misfires (worse than doing nothing).
  • A short fine-tune at the target length works best here.
  • Interpolation slows adaptation on this task: squeezing positions 3× reduces the angular separation between neighbouring offsets, which this exact-offset task depends on. For natural language, where interpolation is the standard recipe, results differ; this toy isolates the failure mode.
  • Seed 1: window 0.636, interpolation 2.790, fine-tune 0.553, interpolation + fine-tune 1.598.
🐍 Exercise 2 (research): which long-context strategy rescues a model beyond its training length?
Train a RoPE GPT on short sequences and compare sliding windows, position interpolation and brief fine-tuning for positions beyond the training length.

Long context in AI, robotics and aerospace

  • Manuals and logs: long-context models (or retrieval) for questions spanning whole documents.
  • Streaming telemetry: sliding-window attention suits unbounded streams where only recent history matters.
  • Design lesson: test at the deployment length with tasks that need the long range; nominal context windows can mislead.

References

  1. S. Chen, S. Wong, L. Chen and Y. Tian (2023). “Extending context window of large language models via positional interpolation.” arXiv:2306.15595.
  2. B. Peng, J. Quesnelle, H. Fan and E. Shippole (2024). “YaRN: efficient context window extension of large language models.” Proc. ICLR.
  3. A. Q. Jiang et al. (2023). “Mistral 7B.” arXiv:2310.06825.
  4. H. Liu, M. Zaharia and P. Abbeel (2024). “Ring attention with blockwise transformers for near-infinite context.” Proc. ICLR.
  5. T. Dao, D. Fu, S. Ermon, A. Rudra and C. Ré (2022). “FlashAttention: fast and memory-efficient exact attention with IO-awareness.” NeurIPS.