Foundations to Frontier
Tests
F. NLP and Large Language Models › F8 Inference and Serving

KV cache, PagedAttention

During generation each new token attends to all previous ones. Their keys and values never change, so they are stored in a KV cache instead of being recomputed every step. This turns the quadratic cost of re-encoding the prefix into linear work per token. The cache is large, though: for an 8B model about 128 KiB per token, 0.5 GiB per 4096-token sequence. How it is allocated decides how many requests fit on a GPU, and hence throughput. PagedAttention (vLLM) stores the cache in fixed-size blocks mapped through a block table, like virtual memory. This removes the waste of reserving space for the maximum possible output and enables prefix sharing. This page covers KV-cache sizing, grouped-query attention, paging, prefix caching and pre-emption. In the exercises you compute cache sizes and block counts and implement the block-table lookup. You then verify that caching gives identical outputs with 128× fewer key/value projections over 256 steps, and simulate 400 chat requests on a 16 384-token cache. Static reservation used only 28% of the reserved memory; paging used 98%. That tripled the mean batch (12.2 → 36.6) and cut decode steps 2.96×, despite 330 pre-emptions.

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.

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

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.

📝 Quick check (Level 0)
0/3 answered
  1. 1. The KV cache stores…
  2. 2. Without the cache, each step must…
  3. 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.
📝 Quick check (Level 1)
0/3 answered
  1. 1. GQA with 8 KV heads instead of 32 shrinks the cache…
  2. 2. Decode steps are mostly…
  3. 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_utilization sets how much memory goes to weights plus cache, and --enable-prefix-caching reuses shared prefixes.
  • Hugging Face generate uses a cache automatically (use_cache=True); static caches enable torch.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))
🐍 Exercise 1: sizing the KV cache
Implement the KV-cache size formula, the blocks a sequence needs and the internal waste.
📝 Quick check (Level 2)
0/3 answered
  1. 1. vLLM option for reusing shared prompts:
  2. 2. A way to halve KV memory:
  3. 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.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Generating T tokens without a cache costs ___ projections:
  2. 2. Small-batch decoding is limited by…
  3. 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.
🐍 Exercise 2 (research): how much do KV caching and paged allocation save?
Verify that the KV cache preserves outputs while saving work, then simulate static vs paged KV allocation for chat requests.

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

  1. W. Kwon et al. (2023). “Efficient memory management for large language model serving with PagedAttention.” SOSP.
  2. N. Shazeer (2019). “Fast transformer decoding: one write-head is all you need.” arXiv:1911.02150.
  3. J. Ainslie et al. (2023). “GQA: training generalized multi-query Transformer models from multi-head checkpoints.” EMNLP.
  4. L. Zheng et al. (2024). “SGLang: efficient execution of structured language model programs.” NeurIPS (RadixAttention prefix caching).