PagedAttention & vLLM
Store the KV cache in small fixed-size blocks allocated on demand, like OS memory pages, so almost no GPU memory is wasted; the freed memory becomes bigger batches and 2–4× throughput.
Analogy: Instead of holding a 12-seat table for every party in case everyone shows up, seat guests at any free 2-seat table as they arrive and keep a list of which tables belong to whom.
How it works
- Older servers reserved one contiguous KV slab per request, sized for the maximum output length.
- Most of each slab stayed empty: only 20–38% of KV memory held real tokens.
- A per-request block table maps logical blocks to physical ones; memory grows one 16-token block at a time.
- Waste drops to the half-empty last block, under 4%, and freed memory becomes bigger batches.
- Shared prefixes and parallel samples point to the same blocks, copied only when one sequence writes (copy-on-write).
Check yourself
Answer to mark it learned; your answers aren't scored.
You turned on enable_prefix_caching in vLLM for a support bot whose prompts all share a long policy text, yet the prefix-cache hit rate is near 0%. Every prompt starts with Current time: {now}, then the policy. Most likely cause?
Go deeper
Full explanation
PagedAttention stores each request's KV cache in small fixed-size blocks (16 tokens by default in vLLM) that can live anywhere in GPU memory, the way an OS maps virtual pages to physical frames. A per-request block table maps logical blocks to physical ones, and the attention kernel reads through it.
Before it, servers reserved one contiguous KV slab per request, sized for the maximum output length. Most of it was never filled, and the gaps between slabs could not be reused: Kwon et al. (SOSP 2023) measured only 20–38% of KV memory holding real tokens, i.e. ~60–80% wasted. With paging, memory grows one block at a time as tokens arrive, so the only waste is the half-empty last block: under 4%.
Two consequences:
- More sequences per GPU. Freed memory becomes batch size, which Continuous batching turns into throughput: 2–4× over FasterTransformer and Orca at the same latency.
- Sharing. Blocks are reference-counted, so parallel samples, beam-search branches and requests with a common prefix point to the same physical blocks. A block is copied only when one sequence writes to it (copy-on-write). Automatic prefix caching reuses full blocks across requests the same way.
vLLM is the server built around it; SGLang, TensorRT-LLM and TGI also use a paged KV cache.
Code Offline batch generation with vLLM
from vllm import LLM, SamplingParams
MODEL = "meta-llama/Llama-3.1-8B-Instruct" # any HF causal LM
llm = LLM(
model=MODEL,
gpu_memory_utilization=0.90, # VRAM vLLM claims; what's left after weights becomes KV blocks
max_model_len=8192, # longest sequence allowed; blocks are still allocated lazily
block_size=16, # tokens per KV block (the default)
enable_prefix_caching=True, # identical prompt prefixes share physical blocks
)
# Startup log reports the KV cache size in tokens and the max concurrency it allows
SYSTEM = "You are ACME's support assistant. Policy: ..." # static part FIRST so it caches
prompts = [f"{SYSTEM}\nUser: {q}\nAssistant:" for q in questions]
# n=4 samples per prompt share the prompt's blocks (copy-on-write)
params = SamplingParams(n=4, temperature=0.8, max_tokens=256)
for out in llm.generate(prompts, params): # continuous batching + paged KV inside
print([o.text for o in out.outputs]) # 4 candidates per promptReal example
A team serves Llama-3-8B on one 80 GB H100. After ~16 GB of weights, ~55 GiB remains for KV; at 128 KiB per token that is ~450k tokens. Reserving a full 8k-token slab per request caps them at **~55 concurrent sequences**, even though the average conversation uses ~1.5k tokens. With 16-token blocks allocated on demand, the same memory holds **~300 sequences** at their real length, so each decode step batches far more requests. Their shared system prompt is now stored once instead of 300 times.
Trade-offs +4 · −3
+ You gain
- KV waste drops from ~60–80% to under 4%: 2–4× throughput on the same GPUs.
- Cheap sharing for parallel sampling, beam search and common prefixes via copy-on-write.
- Block-level allocation makes preemption, swapping and prefix caching simple to implement.
- Free: it's the default in vLLM, SGLang and TensorRT-LLM.
− You pay
- The block-table indirection makes the attention kernel itself ~20–26% slower in the paper; bigger batches repay it.
- It removes waste, not size: a 128k-token request still needs ~16 GiB of KV on Llama-3-8B.
- Little to gain at batch size 1 or for single-user local inference.
Use it when
Any self-hosted LLM serving with concurrent requests: pick an engine with a paged KV cache (vLLM, SGLang, TensorRT-LLM) instead of a plain transformers.generate loop.
Avoid it when
You never build it yourself. It matters little for batch-1 local use (llama.cpp on a laptop) or when you consume a hosted API, where the provider already does it.
Numbers to know 4
- Pre-vLLM servers used only 20–38% of KV memory for real tokens; vLLM wastes under 4%.
- 2–4× throughput vs FasterTransformer/Orca at equal latency (paper); up to 24× vs plain HF Transformers (vLLM launch blog).
- Sharing cuts the memory of parallel sampling and beam search by up to 55% (vLLM blog).
- Defaults: 16 tokens per block;
gpu_memory_utilization=0.9.
Common pitfalls 3
- Running two vLLM instances on one GPU: each pre-claims 90% of VRAM at startup and the second one OOMs. Lower
gpu_memory_utilization. - Ignoring preemption logs: when blocks run out, vLLM evicts and recomputes sequences, and latency spikes. Add KV memory, cap
max_num_seqsor shorten contexts. - Breaking prefix caching with a timestamp or user ID at the top of the prompt: every block after it misses.
Interview questions 2
Answer out loud first, then reveal.
Why does PagedAttention raise throughput if it doesn't make attention faster?Show answer
Because decode throughput comes from batch size, and batch size is capped by KV memory. Contiguous per-request reservations wasted 60–80% of that memory on worst-case slots and fragmentation. Allocating 16-token blocks on demand drops waste under 4%, and that memory becomes 2–4× more concurrent sequences. The kernel is actually slightly slower because of the block-table lookup; the batch gain dwarfs it. What I'd watch in production is preemption when the block pool fills.
How does vLLM share KV memory across sequences, and when does sharing break?Show answer
Blocks are reference-counted. The n samples of one prompt point to the prompt's blocks, beam branches share their history, and automatic prefix caching reuses full blocks across requests by hashing their tokens plus everything before them. A shared block is copied only when someone writes to it. It breaks when prefixes are not token-identical: a timestamp at the top changes every block after it. So I put static instructions and documents first and per-user content last, and I track the prefix-cache hit rate.