Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.Remembering what was already read
When a model writes the 100th word, it looks back at the 99 before. Recomputing everything about those words each time would be wasteful, so the model keeps a memory of them, the KV cache. That memory takes a lot of GPU space, and how it is packed decides how many users one GPU can serve at once. PagedAttention packs it in small pages, like a computer’s virtual memory, so little space is wasted. The demo shows how the cache grows with model size and text length.
KV-cache memory, not compute, usually limits how many users a deployment can serve; paging and grouped-query attention are what make serving long contexts affordable.
- 1. The KV cache stores…
- 2. Without the cache, each step must…
- 3. PagedAttention stores the cache in…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.By hand
- Size: 2 × layers × KV heads × head dim × bytes per value, per token. Llama-3-8B (32 layers, 8 KV heads, dim 128, fp16): 128 KiB per token.
- Grouped-query attention (GQA) shares each K/V head among several query heads (8 instead of 32 → 4× smaller cache); multi-query attention (MQA) uses one.
- Prefill vs decode: the prompt is processed in parallel (compute-bound); then one token per step reads the whole cache and weights (memory-bound), so larger batches are nearly free per step.
- Static allocation: reserving prompt + maximum output contiguously per request wastes most memory, because most outputs are far shorter than the maximum.
- PagedAttention: blocks of e.g. 16 tokens allocated on demand; a block table maps logical to physical blocks; waste is under one block per sequence. Enables copy-on-write prefix sharing (system prompts, parallel samples).
- Pre-emption: when blocks run out, a request is paused and its KV is swapped to CPU or recomputed later.
- 1. GQA with 8 KV heads instead of 32 shrinks the cache…
- 2. Decode steps are mostly…
- 3. Paging limits waste to under…
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.KV caching in practice
Exercise 1.
- Compute the KV-cache size of a model configuration.
- Count the blocks a sequence needs.
- Compute the unused slots in its last block.
Practice.
- vLLM uses PagedAttention by default;
gpu_memory_utilizationsets how much memory goes to weights plus cache, and--enable-prefix-cachingreuses shared prefixes. - Hugging Face
generateuses a cache automatically (use_cache=True); static caches enabletorch.compile. - Quantised KV caches (fp8) halve memory with small quality loss.
- Long-context serving: estimate cache size per request before choosing hardware.
from vllm import LLM, SamplingParams
llm = LLM("meta-llama/Llama-3.1-8B-Instruct", gpu_memory_utilization=0.9,
enable_prefix_caching=True, kv_cache_dtype="fp8", block_size=16)
outs = llm.generate(prompts, SamplingParams(temperature=0.7, max_tokens=512))- 1. vLLM option for reusing shared prompts:
- 2. A way to halve KV memory:
- 3. Hugging Face caching flag:
Level 3: Advanced
★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.Theory
Cost with and without a cache. Without a cache, step t recomputes keys and values for all t previous tokens, so generating T tokens costs O(T²) projections (and O(T²·L) layer work overall). With a cache each step adds one key and value: O(T) projections, while attention itself still reads all t cached entries (O(t·d) per step).
Why memory sets throughput. Decoding one token for a batch of B sequences reads the weights once and each sequence’s cache. When B is small, the weight reads dominate and the GPU is idle most of the time, so throughput rises almost linearly with B until compute saturates. The maximum B is the cache memory divided by memory per request, so allocation efficiency translates directly into throughput.
Paging trade-offs. Small blocks waste less but need bigger block tables and less contiguous memory access; 16 tokens is a common compromise. Admitting requests optimistically, without reserving their maximum output, packs memory tightly but requires pre-emption when it runs out.
- 1. Generating T tokens without a cache costs ___ projections:
- 2. Small-batch decoding is limited by…
- 3. Optimistic admission requires…
Level 4: Expert
★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.How much do KV caching and paged allocation save?
History.
- The KV cache is as old as autoregressive Transformer decoding (2017).
- N. Shazeer, “Fast transformer decoding: one write-head is all you need” (MQA, 2019); J. Ainslie et al., “GQA” (2023).
- W. Kwon et al., “Efficient memory management for large language model serving with PagedAttention” (SOSP 2023).
Exercise 2.
- Caching: single-head attention decoding of 256 tokens, with and without a cache.
- Serving simulation: 400 chat requests (prompts 20–300 tokens, outputs geometric with mean 150, maximum 1024) on a cache of 16 384 tokens. Each step every running request decodes one token; the step cost is taken as constant (memory-bound regime).
- Static: reserve prompt + 1024 slots at admission.
- Paged: 16-token blocks on demand; pre-empt the newest request (and recompute it later) if blocks run out.
| static reservation | paged (16-token blocks) | |
|---|---|---|
| decode steps to finish | 5051 | 1706 |
| mean batch size | 12.2 | 36.6 |
| reserved memory holding tokens | 28% | 98% |
| pre-emptions | 0 | 330 |
- Caching: identical outputs, 512 key/value projections instead of 65 792 (128× fewer).
- Paging tripled throughput: static reservation wasted 72% of the cache on space for outputs that never came, so only about 12 requests ran at once.
- Pre-emption is the price: optimistic admission forced 330 pause-and-recompute events, whose wasted work is included in the step count.
- Seeds 1 and 2: gains 2.70× and 3.13×; utilisation 27% vs 98% in both.
- Caveat: real step time grows with batch size once compute saturates, so real gains are smaller than this step count suggests; vLLM reported 2–4× throughput over earlier systems.
KV caching in AI, robotics and aerospace
- LLM serving: vLLM, SGLang, TensorRT-LLM and TGI all use paged or block-based KV caches.
- Long-context agents: prefix caching of long system prompts and documents cuts cost and latency across turns.
- Onboard models: small KV caches (GQA, quantisation, short windows) are needed to fit generation in constrained memory.
References
- W. Kwon et al. (2023). “Efficient memory management for large language model serving with PagedAttention.” SOSP.
- N. Shazeer (2019). “Fast transformer decoding: one write-head is all you need.” arXiv:1911.02150.
- J. Ainslie et al. (2023). “GQA: training generalized multi-query Transformer models from multi-head checkpoints.” EMNLP.
- L. Zheng et al. (2024). “SGLang: efficient execution of structured language model programs.” NeurIPS (RadixAttention prefix caching).