Contents
Key concepts
Why position must be injected
Self-attention is permutation-equivariant: shuffle the tokens and each output is shuffled the same way, so without positional information the model sees a bag of tokens. Early transformers added absolute learned or sinusoidal vectors to the embeddings; these generalise poorly beyond the trained length because unseen positions have never been trained on.
RoPE (rotary position embedding)
RoPE splits each query and key vector into 2-D pairs and rotates pair i by angle m·θᵢ for position m, with θᵢ = base^(−2i/d) (base 10,000 originally; Llama 3 raised it to 500,000). Because rotations compose, the query–key dot product depends only on the offset m − n, giving relative position for free. High-frequency pairs encode local order; low-frequency pairs encode long-range position and are the ones that break when you exceed the trained length.
Flow · 3 stepsHow RoPE gives relative position
- Split and rotate Query and key vectors are split into 2-D pairs; pair i is rotated by m·θᵢ for position m, θᵢ = base^(−2i/d) (base 10,000; Llama 3 raised it to 500,000).
- Relative position for free Because rotations compose, the query–key dot product depends only on the offset m − n, giving relative position for free.
- Frequency bands High-frequency pairs encode local order; low-frequency pairs encode long-range position and are the ones that break when you exceed the trained length.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Split and rotate | Query and key vectors are split into 2-D pairs; pair i is rotated by m·θᵢ for position m, θᵢ = base^(−2i/d) (base 10,000; Llama 3 raised it to 500,000). |
| 2 | Relative position for free | Because rotations compose, the query–key dot product depends only on the offset m − n, giving relative position for free. |
| 3 | Frequency bands | High-frequency pairs encode local order; low-frequency pairs encode long-range position and are the ones that break when you exceed the trained length. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| Query and key vectors | Rotate | split into 2-D pairs |
| Rotate pair i | Rotate | angle m·θᵢ, θᵢ = base^(−2i/d) |
| Query–key dot product | Score | rotations compose |
| Relative position | Score | depends only on m − n |
| High-frequency pairs | Bands | encode local order |
| Low-frequency pairs | Bands | long-range position; break past trained length |
Source: This page's text
ALiBi and other length-extrapolating schemes
ALiBi drops positional embeddings and adds a head-specific penalty proportional to query–key distance to the attention logits, biasing heads towards recent tokens. It extrapolates somewhat beyond the training length (‘train short, test long’) but the recency bias limits genuine long-range retrieval, which is why most current open models use RoPE plus an extension method instead. Some recent models also interleave layers with no positional encoding at all: Llama 4’s iRoPE mixes such layers with RoPE layers and scales attention temperature at inference, which Meta credits for Scout’s 10M-token claim despite training at 256k.
Context extension: PI, NTK-aware scaling and YaRN
Position interpolation (PI) rescales positions by L_train/L_target so a 16× longer input maps back into the trained range; it needs a short fine-tune (the paper used about 1,000 steps to reach 32k). NTK-aware scaling instead raises the RoPE base so high-frequency dimensions are barely touched. YaRN interpolates per frequency band and adds an attention-temperature correction, reporting about 10× fewer tokens and 2.5× fewer steps than earlier methods. All of them still need long-document training data and evaluation.
Cost of long context: KV cache and quadratic attention
KV memory per token is 2 × layers × kv_heads × head_dim × bytes, so it grows linearly with context and concurrency; GQA, MLA and KV quantisation shrink it. Attention score computation in prefill grows with n²: at 8k it is a small fraction of total FLOPs, at 128k it dominates. FlashAttention removes the n² memory for the score matrix but not the n² compute; decode is memory-bandwidth-bound and slows as the cache grows. Since 2025 architectures attack the n² term itself: learned sparse attention (NSA; DeepSeek Sparse Attention, where a cheap FP8 indexer picks 2,048 keys per query so core attention costs O(n·k)), sequence-compressed KV (DeepSeek-V4 needs about 10% of V3.2’s cache at 1M tokens) and hybrids that keep full attention in only one layer in four (Qwen3.5).
Effective versus advertised context
Needle-in-a-haystack tests are nearly saturated but say little about real use: GPT-4.1 found a single needle at every position up to 1M tokens yet scored 46% on OpenAI-MRCR’s 2-needle task at 1M, and DeepSeek-V4-Pro falls from above 0.82 on 8-needle MRCR at 256k to 0.59 at 1M. ‘Lost in the Middle’ showed a U-shaped accuracy curve: facts at the start or end are used better than those in the middle. RULER found only about half of 17 models claiming 32k+ stayed satisfactory at 32k on harder tasks (multi-hop tracing, aggregation); NoLiMa (2025) found 11 of 13 models below half their short-context score at 32k once the needle shared no words with the question; and Chroma’s 2025 ‘context rot’ study saw degradation with length across 18 models even on simple tasks, worse with semantically similar distractors.
Context engineering for agents and long chats
For long-running agents the problem is curation, not capacity: compaction (summarising history while keeping goals, decisions and identifiers), clearing stale tool results, structured notes written outside the window, just-in-time retrieval by reference (file paths, IDs) and sub-agents with clean windows that return condensed results. Keep history append-only and the prefix stable so prompt caching keeps hitting. Much of this is now an API feature: Anthropic’s context editing clears stale tool results automatically (84% fewer tokens in a 100-turn search eval), a memory tool stores notes in files, and server-side compaction summarises older turns.
Long context versus retrieval
Stuffing is simpler, has no retrieval misses and allows whole-document reasoning, so it suits bounded, one-off analyses (a contract, a codebase snapshot). Retrieval wins for large or changing corpora, per-user permissions, citations and cost control. The common production answer is a hybrid: retrieve fewer, larger chunks into a generous window, and cache stable prefixes.
Flow · 6 stepsChoosing stuffing, retrieval or a hybrid
- Compare cost and eval Caching narrows the gap from about 22x to about 2.4x; check accuracy, latency, freshness and per-user permissions.
- Check freshness and permissions Ask whether the handbook changes daily or users may only see parts of it.
- Retrieve If yes, retrieve chunks; retrieval wins regardless.
- Check bounded one-off If no, ask whether this is a bounded one-off analysis.
- Stuff If bounded one-off, stuff the whole context and cache the stable prefix.
- Hybrid Otherwise use fewer, larger chunks with a cached prefix, the common production answer.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Compare cost and eval | Caching narrows the gap from about 22x to about 2.4x; check accuracy, latency, freshness and per-user permissions. |
| 2 | Check freshness and permissions | Ask whether the handbook changes daily or users may only see parts of it. |
| 3 | Retrieve | If yes, retrieve chunks; retrieval wins regardless. |
| 4 | Check bounded one-off | If no, ask whether this is a bounded one-off analysis. |
| 5 | Stuff | If bounded one-off, stuff the whole context and cache the stable prefix. |
| 6 | Hybrid | Otherwise use fewer, larger chunks with a cached prefix, the common production answer. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| 180k-token policy handbook | Input | plus a 2k-token question |
| Compare the paths | Decide | $10,920/day vs $1,200/day vs $504/day |
| Changes daily or split? | Decide | retrieval wins regardless |
| Bounded one-off analysis? | Decide | contract, codebase snapshot |
| Retrieve chunks | Choose | 8 chunks x 800 tokens + question; $504/day |
| Stuff whole context | Choose | 182,000 tokens; $1,200/day cached |
| Hybrid | Choose | fewer, larger chunks + cached prefix |
Source: This page's text
Worked examples
KV-cache memory for a 128k context
Estimate BF16 KV-cache memory for one 128k-token (131,072) sequence on Llama 3.1 8B (32 layers, 8 KV heads, head_dim 128) and Llama 3.1 70B (80 layers, 8 KV heads, head_dim 128). How many concurrent 128k sequences fit in 60 GiB of free memory on the 8B?
Per-token KV bytes = 2 (K and V) × layers × kv_heads × head_dim × 2 bytes (BF16).
- 8B: 2 × 32 × 8 × 128 × 2 = 131,072 B = 128 KiB per token
- 70B: 2 × 80 × 8 × 128 × 2 = 327,680 B = 320 KiB per token
Per 128k sequence (× 131,072 tokens):
- 8B: 128 KiB × 131,072 = 16 GiB
- 70B: 320 KiB × 131,072 = 40 GiB
Concurrency on the 8B with 60 GiB free after weights: 60 / 16 ≈ 3 full-length sequences.
Sanity checks an interviewer likes:
- Without GQA (32 KV heads instead of 8) the 8B would need 4× more: 64 GiB per sequence.
- FP8 KV halves it to 8 GiB; paged attention avoids reserving the full 128k up front, so real concurrency depends on the length distribution, not the maximum.
CalculatorKV-cache memory for a 128k context
- Per-token KV bytes
- 128 KiB
- 131,072 bytes
- Per-sequence KV bytes
- 16 GiB
- 17,179,869,184 bytes
- Sequences that fit
- 3
Per-token KV bytes = 2 × Layers × KV heads × Head dim × Bytes per element = 128 KiB
Per-sequence KV bytes = Per-token KV bytes × Tokens = 16 GiB
Sequences that fit = floor(Free memory × 1073741824 ÷ Per-sequence KV bytes) = 3
| Case | Layers | KV heads | Head dim | Tokens | Bytes per element | Free memory (GiB) | Per-token KV bytes | Per-sequence KV bytes | Sequences that fit |
|---|---|---|---|---|---|---|---|---|---|
| Llama 3.1 8B | 32 | 8 | 128 | 131,072 | 2 | 60 | 128 KiB | 16 GiB | 3 |
| Llama 3.1 70B | 80 | 8 | 128 | 131,072 | 2 | 60 | 320 KiB | 40 GiB | 1 |
Why a 16× longer prompt costs about 44× more prefill compute
For an 8B dense model (32 layers, d_model 4,096) compare prefill FLOPs at 8,192 and 131,072 tokens. Use 2 × params × n for the weight matmuls and 2 × layers × n² × d_model for causal attention (QKᵀ and AV, halved for the causal mask).
Weight matmuls (linear in n):
- 8k: 2 × 8e9 × 8,192 ≈ 1.31e14 FLOPs
- 128k: 2 × 8e9 × 131,072 ≈ 2.10e15 FLOPs
Causal attention (quadratic in n):
- 8k: 2 × 32 × 8,192² × 4,096 ≈ 1.76e13 FLOPs (about 13% of the matmul cost)
- 128k: 2 × 32 × 131,072² × 4,096 ≈ 4.50e15 FLOPs (about 2.1× the matmul cost)
Totals: 8k ≈ 1.49e14; 128k ≈ 6.60e15, a ratio of about 44× for 16× the tokens.
Implications: time-to-first-token grows super-linearly; chunked prefill keeps decode latency stable for other users; and prefix caching matters far more at long lengths because a cache hit skips the expensive quadratic part.
Flow · 5 stepsHow prefill compute grows with prompt length
- Prompt enters A prompt of length n is split into two cost terms.
- Linear term Weight matmuls scale linearly with n: 2 × params × n.
- Quadratic term Causal attention scales with n²: 2 × layers × n² × d_model.
- Totals 8k is about 1.49e14 FLOPs and 128k about 6.60e15, roughly 44× for 16× the tokens.
- Implications First-token time grows super-linearly; chunked prefill and prefix caching help.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Prompt enters | A prompt of length n is split into two cost terms. |
| 2 | Linear term | Weight matmuls scale linearly with n: 2 × params × n. |
| 3 | Quadratic term | Causal attention scales with n²: 2 × layers × n² × d_model. |
| 4 | Totals | 8k is about 1.49e14 FLOPs and 128k about 6.60e15, roughly 44× for 16× the tokens. |
| 5 | Implications | First-token time grows super-linearly; chunked prefill and prefix caching help. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| prompt length n | Input | 8k vs 128k |
| weight matmuls | Compute | 2 × params × n |
| causal attention | Compute | 2 × layers × n² × d_model |
| total prefill FLOPs | Compute | 8k ≈ 1.49e14; 128k ≈ 6.60e15 |
| first token | Output | grows super-linearly |
| chunked prefill | Output | keeps decode latency stable |
| prefix caching | Output | cache hit skips quadratic part |
Source: This page's text
Long-context stuffing versus retrieval: per-query cost
An assistant answers questions over a 180k-token policy handbook. Option A sends the whole handbook plus a 2k-token question each time. Option B retrieves 8 chunks of 800 tokens plus the question. Assume an illustrative price of $3 per million input tokens, cache reads billed at 10% of that, and 20,000 queries a day. Compare daily input cost, with and without prefix caching for option A.
Option A, no caching: 182,000 tokens × $3/1e6 = $0.546 per query → × 20,000 = $10,920/day.
Option A, cached handbook (assume nearly every query hits the cache):
- cached 180,000 × $0.30/1e6 = $0.054; uncached 2,000 × $3/1e6 = $0.006 → $0.060 per query
- × 20,000 = $1,200/day (plus occasional cache writes, ignored here)
Option B, retrieval: (8 × 800 + 2,000) = 8,400 tokens × $3/1e6 = $0.0252 → $504/day plus embedding and search costs, which are small.
Decision: caching narrows the gap from about 22× to about 2.4×, so the choice is no longer purely about cost. Then compare on your own eval: answer accuracy for mid-document facts, latency (a 180k prefill is slow even when cached), freshness and per-user permissions. If the handbook changes daily or users may only see parts of it, retrieval wins regardless.
What changed recently
DeepSeek-V4 ships 1M tokens with compressed sparse attention
DeepSeek-V4 offers a 1M-token window by interleaving Compressed Sparse Attention (KV compressed 4× along the sequence, an FP4 indexer choosing the top-k compressed blocks, plus a sliding window of recent tokens) with Heavily Compressed Attention (128× compression, attended densely). At 1M tokens V4-Pro needs about 10% of V3.2’s KV cache and 27% of its per-token FLOPs, yet its 8-needle MRCR score still falls from above 0.82 at 256k to 0.59 at 1M, a clean example of capacity outrunning usable context.
Context editing, memory and compaction become API features
Anthropic added context editing, which clears stale tool calls and results as an agent nears its limit, and a client-side memory tool that keeps notes in files outside the window; together they improved an internal agentic-search eval by 39%, and context editing cut token use by 84% in a 100-turn task while letting runs finish that would otherwise exhaust the window. Server-side compaction followed, so interviewers now expect context management to be designed into an agent rather than bolted on.
DeepSeek Sparse Attention reaches a production API
DeepSeek-V3.2-Exp added DeepSeek Sparse Attention to V3.1-Terminus through continued training: a light indexer scores earlier tokens and each query attends to only the top 2,048, so core attention drops from O(L²) to O(L·k). DeepSeek reported benchmark parity with the dense model and cut API prices by more than half, the clearest case of learned sparsity paying for long context in a deployed model.
Native Sparse Attention wins an ACL 2025 best paper award
NSA, from DeepSeek, Peking University and the University of Washington, combines compressed blocks, selected fine-grained blocks and a sliding window through learned gates, with kernels designed around GPU memory access, and trains sparsely from the start. On a 27B MoE it matched or beat full attention while reporting up to 9× faster forward and 6× faster backward passes at 64k. Interviewers use it to ask why sparsifying a dense model after training often fails and what ‘hardware-aligned’ means.
GPT-4.1 brings 1M tokens and a harder retrieval benchmark
OpenAI’s GPT-4.1 family accepts up to 1M tokens, up from 128k, and finds a single needle at every position and length, yet GPT-4.1 scores 46.3% on the new OpenAI-MRCR 2-needle task at 1M and its first token takes about a minute at that length. With Anthropic and others also offering 1M windows, the interview question shifted from how long the window is to how much of it is reliably usable, at what latency and cost.
Pitfalls
- Treating the advertised window as the usable window; effective context on hard tasks is often far shorter.
- Citing needle-in-a-haystack results as proof of long-context reasoning; single-needle lexical lookup is the easiest case, and models that ace it at 1M tokens can still score below 50% on multi-needle tasks such as MRCR.
- Saying FlashAttention makes attention linear; it removes the n² memory for scores, not the n² compute.
- Assuming bigger models always need more KV memory; KV depends on layers × kv_heads × head_dim, so GQA/MLA matter more than parameter count.
- Fixing instruction drift in long chats by repeating the whole system prompt; check first whether truncation silently dropped it.
- Extending RoPE by changing the base or scale without any long-context fine-tuning or long-document evaluation.
How interviewers probe it
- Derive why RoPE gives relative position, then explain which frequency bands break past the trained length and how PI/YaRN fix them.
- Back-of-envelope: KV memory and concurrency for a given model and context; follow-up on GQA, FP8 KV and paged attention.
- Design question: 500-page document Q&A; justify stuffing, retrieval or a hybrid with cost, latency and accuracy numbers.
- Debugging: an agent degrades after ~100 steps or a chat stops following the system prompt; what do you measure and change?
- Evaluation: how would you measure effective context for your own task (position sweeps, distractors, multi-hop, realistic lengths)?
- Architecture: how do learned sparse attention (NSA, DSA), DeepSeek-V4’s compressed KV or a 3:1 linear-attention hybrid change KV memory, prefill cost and recall at 1M tokens, and what would you test before trusting one?
Quiz
Three questions from this guide. Answer each in your head or out loud, show the model answer, then rate yourself. The cards join your practice deck and come back when they are due.
How does a transformer know token order? Compare learned/sinusoidal embeddings, RoPE and ALiBi, and explain how a model trained at 8k context can be stretched to 128k.
Model answer, written in a candidate's voice
- Attention alone is permutation-invariant, so position must be injected
- Absolute learned/sinusoidal embeddings add position vectors; sinusoidal is fixed, learned is trained but length-limited
- RoPE rotates query/key pairs by position-dependent angles so dot products depend on relative offset; ALiBi adds a distance-proportional logit bias
- Stretch 8k to 128k via position interpolation or NTK/YaRN-style frequency rescaling, then long-context fine-tuning
- Validate with needle-style retrieval and realistic long-document tasks; effective context is often shorter than advertised
- Cost: KV cache grows with context and full attention compute grows roughly quadratically
Models now accept hundreds of thousands of tokens. When would you put everything in the context window instead of building retrieval, and what failure modes would you watch for?
Model answer, written in a candidate's voice
- Use long context for bounded, one-off analyses over a fixed, small-enough set where whole-document reasoning matters.
- It simplifies the pipeline and avoids retrieval misses, but every call pays for every token, latency rises, mid-context recall degrades, distractors hurt, and access control must be enforced before sending.
- Retrieval wins for large or changing corpora, citations, permissions, and cost control; hybrids retrieve large chunks into a long window.
- Decide by measuring on the team’s own tasks at realistic lengths, including distractors and permission cases.
In long chats, the assistant starts ignoring formatting and safety instructions from the system prompt. Why, and how do you fix it?
Model answer, written in a candidate's voice
- Early system rules get diluted as context grows; recent turns and history dominate attention
- Truncation or summarisation can silently drop the system prompt or constraints
- Verify token counts, truncation policy, and that the system prompt is sent every turn
- Re-inject key rules near the end and compact history while preserving constraints
- Enforce format with structured outputs and validation; test with long-conversation fixtures
You have finished this topic.
Reading
- Effective context engineering for AI agentsPractical vocabulary for compaction, note-taking, just-in-time retrieval and sub-agents.
- Context Rot: How Increasing Input Tokens Impacts LLM PerformanceRecent 18-model study showing degradation with length, distractors and needle–question similarity.
- Lost in the Middle: How Language Models Use Long ContextsThe canonical position-bias result; source of the U-shaped accuracy curve interviewers expect.
- RoFormer: Enhanced Transformer with Rotary Position EmbeddingOriginal RoPE derivation; read the rotation-matrix section until you can reproduce it on a whiteboard.
- RULER: What's the Real Context Size of Your Long-Context Language Models?Shows why needle tests mislead and how to probe effective context with harder synthetic tasks.
- DeepSeek-V4: a million-token context that agents can actually use (Hugging Face)Clear walkthrough of compressed sparse and heavily compressed attention, the KV savings at 1M tokens and the MRCR drop that remains.
- YaRN: Efficient Context Window Extension of Large Language ModelsFrequency-aware interpolation plus attention temperature; widely used in open-weight long-context releases.
- Native Sparse Attention: Hardware-Aligned and Natively Trainable Sparse AttentionACL 2025 best paper: compression, selection and sliding-window branches trained sparse from the start, with large speedups at 64k.
Practise this topic
- How does a transformer know token order? Compare learned/sinusoidal embeddings, RoPE and ALiBi, and explain how a model trained at 8k context can be stretched to 128k.
- Models now accept hundreds of thousands of tokens. When would you put everything in the context window instead of building retrieval, and what failure modes would you watch for?
- In long chats, the assistant starts ignoring formatting and safety instructions from the system prompt. Why, and how do you fix it?
- A long-running agent degrades after about 100 steps as its context fills. How do you manage context and memory?
- Describe the prefill and decode phases of inference. Which is compute-bound and which is memory-bandwidth-bound, and how does that show up in time-to-first-token and inter-token latency?
- Compare multi-head, multi-query and grouped-query attention, and latent attention if you know it. Why did most recent open-weight models adopt GQA, and what does it change when you serve the model?
- A vendor advertises a 1M-token window and your team wants to drop retrieval for a 600k-token contract corpus. Using what GPT-4.1 and DeepSeek-V4 report about single-needle versus multi-needle retrieval at 1M tokens, how would you make the call and what would you measure?
- Compare Native Sparse Attention, DeepSeek Sparse Attention and DeepSeek-V4’s compressed attention. What does each select or compress, what does it cost, how is it trained, and why do these methods train sparsity in rather than applying it to a finished dense model?
- Your coding agent runs for 300 turns and its context fills with tool output. Design a context-management strategy using what model APIs now offer (context editing, compaction, memory files), and explain how you keep prompt-cache hits high and check that nothing important is lost.
- Qwen3-Next and Qwen3.5 follow every three Gated DeltaNet (linear-attention) layers with one gated full-attention layer. What does a linear-attention layer keep instead of a KV cache, what is it bad at, and why ship a 3:1 hybrid rather than a fully linear model?