Pidoku

Long-Context Inference

Module 14 Lesson 14.i 1h 30m Difficulty 4/5

Prerequisites 12.h, 12.g, 14.f, 12.k

12.h owns the four costs of long context and how they scale; 12.g owns the attention designs that shrink them; 13.i owns KV compression and eviction. This lesson is about serving 128k to 1M-token requests across GPUs: what fits, how prefill and decode are spread, and how a fleet is organised around them.


Before you start: words you need#

WordPlain meaning
Long contextHere: prompts or conversations of roughly 128k tokens and up. 1M tokens is about 3,000 pages of text, or a large codebase.
Per-token cacheThe bytes of KV cache (or similar state) a model stores for each token it has seen, across all layers (12.f).
Sparse attentionAttention that, for each new token, reads only the most relevant few thousand past tokens instead of all of them (DeepSeek Sparse Attention, DSA; 12.g).
Hybrid modelA model where most layers use linear attention with a fixed-size state, and only some layers keep a full KV cache (12.g).
TTFTTime to first token: for a 1M-token prompt, mostly prefill time.
Long-context poolA separate group of replicas reserved for long requests, so they do not crowd out ordinary traffic.
SessionA multi-turn conversation or agent run whose context is reused, and grown, on every turn.

1. What is it?#

Long-context inference is serving requests whose context is so large that one request changes the shape of the deployment: its prefill takes tens of seconds to minutes, its cache takes gigabytes to tens of gigabytes, and it may need several GPUs of its own.

In November 2026, 1M-token context windows are standard on frontier open models: DeepSeek-V4 and V4.1-Flash, Kimi K3 and GLM-5.3 all advertise 1,048,576 positions, and Qwen3.6 extends to about 1M. Agent sessions and coding tools fill them: whole repositories, long tool-call histories and reasoning traces that are themselves context.

Facts checked on 12 November 2026.


2. Why does it matter?#

WHAT CHANGES AT 1M TOKENS
  memory    one request's cache can exceed a GPU's free HBM (architecture-dependent: 1-170 GB)
  prefill   minutes on one GPU group; it must be split across GPUs and across time
  decode    every step reads the whole cache, unless attention is sparse
  failure   losing a 1M-token cache means minutes of recompute, not milliseconds
  money     one request can cost as much as thousands of ordinary ones

The engineering answer is not one technique but a layout: the right architecture, prefill spread over many GPUs, decode with a sharded or offloaded cache, a dedicated pool, and caching so the same million tokens are not prefilled twice.


3. Simple analogy#

Oversized freight on a motorway.

Most lorries fit in one lane and travel together (ordinary requests batched on one replica). An oversized load (a 1M-token request) needs an escort, a reserved slot and sometimes two lanes (several GPUs). You schedule it separately, you do not let it block the normal traffic, and you keep it parked near where it will be needed next (cached), because loading it again takes hours.


4. Tiny example: one 1M-token request on GLM-5.3#

cache:     ~47.5 KB per token (MLA latent + sparse-attention index, FP8) × 1,048,576 ≈ 50 GB
prefill:   linear part alone ≈ 2 × 40B active × 1M tokens ≈ 80 PFLOP
           at ~1 PFLOP/s achieved FP8 per Blackwell GPU   ≈ 80 GPU-seconds
           + attention and indexer work, which grows faster than linearly
decode:    each step reads the cache index plus ~2,048 selected tokens per layer,
           not all 1M (sparse attention)

So one such request needs roughly a minute or more of a GPU’s time to prefill and tens of GB of cache, while an 8k-token chat request needs well under a second and well under a GB. Without sparse attention or a hybrid design, the same request on a dense GQA model would need about 170 GB of cache: more than one GPU’s free memory (section 6).


5. Technical explanation#

Architecture decides first#

The cache per token now varies by more than 100x between 2026 models (section 6 computes it from their configs):

DesignExampleWhat it does to a 1M-token request
Dense GQA, every layer70B-class dense models~170 GB of cache at FP8: needs context parallelism or offload
MLA + sparse attentionGLM-5.3 (DSA)~50 GB; each decode step reads only the top 2,048 tokens per layer
Hybrid linear + MLAKimi K3 (KDA, 1 in 4 layers full)~15 GB plus a fixed state per sequence
Compressed sparse attentionDeepSeek-V4 / V4.1-Flashabout 1 GB of global cache (V4.1-Flash card: ~890 bytes per token)

If long context is the product, model choice is the biggest serving decision you make. Lesson 12.g explains how each design works.

Spreading prefill#

A 1M-token prefill must be split, or it occupies a replica for minutes:

  • Chunked prefill (12.k) cuts the prompt into pieces so decode steps can run in between. It bounds the damage to other users but does not shorten this request’s TTFT.
  • Context parallelism (14.f) splits the prompt’s tokens across GPUs. Meta reports 1M-token prefill of Llama 3 405B in 77 s on 128 H100s at 93% parallel efficiency (paper’s own result).
  • Chunked pipeline parallelism (14.d) sends chunks down a pipeline of servers. SGLang reports Qwen3-235B TTFT on 32 H20s (PP8 × TP4) of about 10.5 s at 128k and 421 s at 1M (project’s own benchmark).
  • A separate prefill pool (14.j) keeps those minutes of compute off the decode GPUs entirely.

Spreading decode#

At long context, a decode step is dominated by reading the cache (12.h). Options:

  • Sparse attention cuts the read itself to a fixed top-k per layer. The cache must still be stored.
  • Decode context parallelism (14.f) shards one sequence’s cache by token over the TP group’s GPUs, removing duplicates and splitting the read.
  • Wide attention DP + EP for MoE models (14.e) gives each GPU fewer expert weights, leaving more HBM for cache. LMSYS reports DeepSeek-R1 at 128k in / 8k out reaching up to 226 output tokens/s per GPU on GB300 NVL72, 1.53x GB200, using wide EP for decode (project’s own benchmark).
  • Small batches. Each long sequence takes so much cache that a GPU holds only a handful; plan for low batch and high cost per token.

The cache is now an asset to keep#

Recomputing a 1M-token prefill costs a minute or more of GPU time. Losing that cache (on preemption, eviction or a follow-up turn routed elsewhere) is expensive:

  • Prefer offload over recompute for long sequences: moving 50 GB over NVLink-C2C or PCIe takes seconds or less; recomputing takes far longer (14.k).
  • Keep session caches warm in CPU memory or on SSD between turns, and route follow-up turns to the replica, or the shared store, that holds them (14.l, 21.h). DeepSeek’s V4.1-Flash card describes persisting KV to SSD and replaying only the most recent sliding-window tokens instead of storing them, which shows that SSD-backed session caches are part of large-scale serving practice, not an experiment.
  • Preempt long requests last. A scheduler that preempts the largest request to free space throws away the most expensive work (17.c).

Organising the fleet#

ROUTER
  ├── normal pool:        context ≤ 32k, large batches, chunked prefill
  └── long-context pool:  context > 32k (or > 128k), CP / DCP enabled, KV offload tiers,
                          admission by cache tokens, its own SLOs and price
  • Admit by tokens, not requests. One 1M-token request is equivalent in memory to hundreds of ordinary ones. Admission control (20.c) should count cache tokens.
  • Separate SLOs. TTFT targets of a few seconds are not achievable at 1M tokens; publish realistic ones, and stream progress for agents.
  • Price by context. Long-context and cached-input pricing exist because the cost is real (23.c).
  • Measure quality before promising length. Many models degrade well before their advertised limit (12.h’s “effective context”). Eviction-based compression can fail silently (13.i).

Long context or retrieval?#

12.h gives the cost argument: retrieving a few thousand relevant tokens is often 20x cheaper per question than putting a large document in context. Two 2026 changes narrow the gap: sparse and compressed attention make long prompts much cheaper to decode, and prefix caching turns the second and later questions about the same document into near-free cache hits. The rule still holds: measure both on your task.


6. Under the hood#

Per-sequence cache for five designs, from their configs (FP8 cache unless stated), and how many 1M-token sequences fit in 100 GB of free HBM:

Go
// longctx.go — how big one long conversation's cache is, for 2026 architectures.
package main

import "fmt"

type arch struct {
	name       string
	perToken   float64 // bytes of cache added per token, all layers
	fixed      float64 // bytes per sequence that do not grow (linear-attention state, windows)
	maxContext float64 // tokens the model supports
	note       string
}

func main() {
	const free = 100e9 // HBM left for cache on one GPU after weights, bytes
	archs := []arch{
		// 80 layers x 8 KV heads x 128 dims x (K and V) x 1 byte (FP8)
		{"70B dense, GQA-8, FP8", 80 * 8 * 128 * 2 * 1, 0, 131072, "every layer, every token"},
		// 18 full layers x 8 KV heads x 64 x 2 x BF16; 18 sliding layers keep 128 tokens
		{"gpt-oss-120b, BF16", 18 * 8 * 64 * 2 * 2, 18 * 128 * 8 * 64 * 2 * 2, 131072, "half the layers windowed"},
		// MLA latent 576 values x 78 layers at FP8, plus 20 DSA indexer layers x 128 at FP8
		{"GLM-5.3, MLA+DSA, FP8", 576*78 + 20*128, 0, 1048576, "sparse: reads top-2048 per step"},
		// 24 full MLA layers x 576 at FP8; 69 KDA layers keep 96 heads x 128x128 state (BF16)
		{"Kimi K3, hybrid, FP8", 24 * 576, 69 * 96 * 128 * 128 * 2, 1048576, "3 of 4 layers linear"},
		// model card: ~890 bytes per token of global KV with FP4 main KV
		{"DeepSeek-V4.1-Flash", 890, 0, 1048576, "compressed sparse attention"},
	}
	fmt.Printf("%-24s %9s %9s %9s %12s\n", "architecture", "KB/token", "128k", "1M", "1M seqs/GPU")
	for _, a := range archs {
		at := func(n float64) string {
			if n > a.maxContext {
				return "-"
			}
			return fmt.Sprintf("%.1fGB", (a.perToken*n+a.fixed)/1e9)
		}
		seqs := "-"
		if a.maxContext >= 1e6 {
			seqs = fmt.Sprintf("%.0f", free/(a.perToken*1048576+a.fixed))
		}
		fmt.Printf("%-24s %9.1f %9s %9s %12s   %s\n", a.name, a.perToken/1e3, at(131072), at(1048576), seqs, a.note)
	}
}

Output:

architecture              KB/token      128k        1M  1M seqs/GPU
70B dense, GQA-8, FP8        163.8    21.5GB         -            -   every layer, every token
gpt-oss-120b, BF16            36.9     4.8GB         -            -   half the layers windowed
GLM-5.3, MLA+DSA, FP8         47.5     6.2GB    49.8GB            2   sparse: reads top-2048 per step
Kimi K3, hybrid, FP8          13.8     2.0GB    14.7GB            7   3 of 4 layers linear
DeepSeek-V4.1-Flash            0.9     0.1GB     0.9GB          107   compressed sparse attention

How to read it:

  • A dense GQA 70B model stops at its 128k limit here; at 1M it would need about 170 GB per sequence.
  • Architecture moves the answer by over 100x. The same 100 GB holds 2 one-million-token GLM-5.3 sessions, 7 Kimi K3 sessions or about 100 DeepSeek-V4.1-Flash sessions.
  • Storage is not reading. GLM-5.3 stores 50 GB but reads only its top-2,048 tokens per layer per step; a dense model reads everything it stores.
  • The numbers are approximate: engines add block padding, scales and metadata, and the Kimi K3 linear-attention state may be kept in FP32 (double the fixed part). Check the cache size the engine reports at start-up.

7. Performance implications#

  • TTFT for 1M-token prompts is tens of seconds to minutes even when spread over 32–128 GPUs. Products must be designed around it (streaming progress, background jobs, caching).
  • ITL at long context depends mostly on the attention design: dense attention gets slower with every token of context; sparse and hybrid designs much less so.
  • Throughput per GPU falls as context grows: fewer sequences fit, and each step reads more.
  • Cache hit rate dominates cost for sessions: a follow-up turn that hits a cached 500k-token prefix costs a tiny fraction of one that misses.

8. Production implications#

  • Choose the model for its cache size if long context is the product.
  • Run a separate long-context pool with its own parallelism (CP/DCP), admission, SLOs and pricing.
  • Enable chunked prefill everywhere and context parallelism only in the long pool.
  • Tier the cache (HBM → CPU → SSD → shared store) and route sessions back to their cache (14.k, 14.l, 21.h).
  • Never treat a long cache as disposable. Offload rather than recompute; preempt short requests first.
  • Test quality at length on your own task before advertising 1M tokens (12.h).

9. Common mistakes#

  1. Mixing 1M-token requests into the normal pool. One request takes the memory of hundreds and stalls everyone’s steps.
  2. Sizing from a dense-attention formula for a sparse or hybrid model (or the reverse). The difference is 10–100x.
  3. Recomputing long prefixes after preemption or on a follow-up turn routed elsewhere.
  4. Promising TTFT targets that physics does not allow at 1M tokens.
  5. Counting requests, not tokens, in admission control and pricing.
  6. Assuming the model uses the whole window well. Measure (12.h).

10. Hands-on exercise#

  1. Run longctx.go. Add Qwen3.6-35B-A3B from its config.json (10 full-attention layers of 40, 2 KV heads, head dimension 256, plus a fixed linear-attention state). How many 1M-token sessions fit in 100 GB?
  2. For a model you can run, measure TTFT at 8k, 32k and 128k tokens with chunked prefill on. Fit a curve: how much is linear, how much quadratic?
  3. Design a router rule that sends requests over 64k tokens to a long-context pool. What happens to a conversation that crosses 64k in its tenth turn?
  4. A 500k-token agent session takes 45 s to prefill and its cache is 25 GB. Compare (a) keeping it in CPU memory between turns over PCIe Gen5 (~50 GB/s) and (b) recomputing it each turn, for an agent that makes a turn every 30 s.
  5. Price it: if a GPU-hour costs $8, what is the GPU cost of one 1M-token prefill that takes 80 GPU-seconds, versus one 2k-token chat request?

11. Interview questions#

  1. Why does a 1M-token request change the shape of a deployment, not just its cost?
  2. Compare the cache per token of dense GQA, MLA with sparse attention, and hybrid linear models.
  3. Which techniques shorten TTFT for one huge prompt, and which only protect other users?
  4. Why should long caches be offloaded rather than recomputed?
  5. How would you organise a fleet that serves both 4k chats and 1M-token agent sessions?
  6. When does long context beat retrieval, and what changed in 2026?

12. Further reading#

Checked on 12 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in