---
title: Long context and context management
url: https://gurkanozkan.ai/learn/topics/long-context/
markdown: https://gurkanozkan.ai/learn/topics/long-context.md
kind: topic
tracks:
  - Applied LLM
  - Research
  - ML engineering
json: https://gurkanozkan.ai/api/learn/topics/long-context.json
---

# Long context and context management

Long context covers how transformers represent position, how a model trained at a few thousand tokens is stretched to 128k or more, what that costs in memory and compute, and how well models actually use what is in the window. Million-token windows are now common (GPT-4.1, current Claude models and DeepSeek-V4 all offer 1M tokens), and new architectures attack the quadratic cost with sparse, compressed or linear attention, but effective context is still shorter than advertised: recall drops for facts buried mid-window or needing more than literal matching, distractors hurt more as inputs grow, and every token is paid for on every call. Interviewers use the topic to test whether you can reason from first principles (RoPE, KV-cache arithmetic, quadratic attention) and make an engineering call between stuffing the window, retrieval and context engineering for agents.

## 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.

### 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.

## 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?

**Solution**

**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.


### 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).

**Solution**

**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.


### 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.

**Solution**

**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

- **Apr 2026: 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. [Source](https://huggingface.co/blog/deepseekv4)
- **Sep 2025: 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. [Source](https://claude.com/blog/context-management)
- **Sep 2025: 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. [Source](https://api-docs.deepseek.com/news/news250929)
- **Jul 2025: 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. [Source](https://2025.aclweb.org/program/awards/)
- **Apr 2025: 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. [Source](https://openai.com/index/gpt-4-1/)

## 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?

## Reading

- [Effective context engineering for AI agents](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents) (Blog, 20 min, Intro): Practical vocabulary for compaction, note-taking, just-in-time retrieval and sub-agents.
- [Context Rot: How Increasing Input Tokens Impacts LLM Performance](https://www.trychroma.com/research/context-rot) (Blog, 25 min, Intro): Recent 18-model study showing degradation with length, distractors and needle–question similarity.
- [Lost in the Middle: How Language Models Use Long Contexts](https://arxiv.org/abs/2307.03172) (Paper, 40 min, Core): The canonical position-bias result; source of the U-shaped accuracy curve interviewers expect.
- [RoFormer: Enhanced Transformer with Rotary Position Embedding](https://arxiv.org/abs/2104.09864) (Paper, 45 min, Core): Original 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?](https://arxiv.org/abs/2404.06654) (Paper, 35 min, Core): 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)](https://huggingface.co/blog/deepseekv4) (Blog, 25 min, Core): 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 Models](https://arxiv.org/abs/2309.00071) (Paper, 45 min, Deep): Frequency-aware interpolation plus attention temperature; widely used in open-weight long-context releases.
- [Native Sparse Attention: Hardware-Aligned and Natively Trainable Sparse Attention](https://arxiv.org/abs/2502.11089) (Paper, 40 min, Deep): ACL 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…](https://gurkanozkan.ai/learn/questions/applied-llm-fnd-06.md)
- [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…](https://gurkanozkan.ai/learn/questions/applied-llm-fnd-11.md)
- [In long chats, the assistant starts ignoring formatting and safety instructions from the system prompt. Why, and how do you fix it?](https://gurkanozkan.ai/learn/questions/applied-llm-dbg-03.md)
- [A long-running agent degrades after about 100 steps as its context fills. How do you manage context and memory?](https://gurkanozkan.ai/learn/questions/applied-llm-agt-05.md)
- [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…](https://gurkanozkan.ai/learn/questions/applied-llm-fnd-10.md)
- [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…](https://gurkanozkan.ai/learn/questions/applied-llm-fnd-04.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-b-long-context-01.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-b-long-context-02.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-b-long-context-03.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-b-transformers-01.md)
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
