PagedAttention
OS-inspired paging for KV cache that reduces fragmentation and boosts concurrency.
In plain words
The server stores each conversation's memory in small standard pieces that can sit anywhere, so nothing is wasted and many more conversations fit on the same GPU.
Think of it like…
Virtual memory pages: instead of demanding one huge contiguous parking lot for every customer, the garage hands out individual spaces as cars arrive and keeps a ledger of which spaces belong to whom, so no space is stranded.
Where you’ve seen it
A 70B model with grouped-query attention needs 327,680 bytes (320 KiB) of KV cache per token in FP16. A server with a 64 GB KV pool that reserves contiguous space for the 4,096-token maximum per request needs 4,096 × 327,680 = 1.25 GiB per sequence, so it holds only 64 × 10⁹ ÷ 1,342,177,280 ≈ 47 sequences, even though the typical request uses just 700 tokens (17% of the reservation). With paging and 16-token blocks, a 700-token sequence occupies 44 blocks (704 tokens, 4 tokens wasted, 0.6%), costing 230,686,720 bytes, so the same pool holds about 277 sequences, almost 6 times as many. For a request that samples n = 4 completions from a 2,000-token prompt (300 new tokens each), sharing the prompt blocks stores 2,000 + 4 × 300 = 3,200 tokens instead of 9,200, a 65% saving.
Words you’ll hear
- KV block
- A fixed-size chunk of a sequence's keys and values (such as 16 tokens) stored in a shared pool.
- Block table
- A per-sequence map from logical block index to physical block location.
- Fragmentation
- Wasted memory from over-reservation (internal) or gaps between allocations (external).
- Copy-on-write
- Sharing blocks until a sequence needs to modify one, then copying only that block.
Visual diagram
Theory & deep dive
The problem and the mechanism
During generation each sequence's KV cache grows by one token's worth per step, and nobody knows in advance how long it will get. Systems that need a contiguous tensor per sequence must reserve for the maximum length, which causes internal fragmentation (reserved but unused slots), and as sequences of different lengths start and finish they leave external fragmentation (free memory in pieces too small to reuse). Measurements in the vLLM paper found only about 20% to 40% of reserved KV memory held actual token states. Since every gigabyte lost reduces batch size, and batch size drives throughput, the waste translates directly into cost.
PagedAttention borrows from OS virtual memory. Physical KV memory is divided into equal blocks; each sequence has a block table mapping its logical blocks (token positions 0 to 15, 16 to 31, ...) to physical blocks, allocated one at a time as the sequence grows. Waste is limited to the unfilled part of the last block (at most block size minus 1 tokens, about 8 on average for 16-token blocks). The attention kernel is rewritten to gather keys and values from the scattered blocks through the table, which costs a small indirection overhead but is far outweighed by the capacity gain. Freed blocks go back to a pool instantly when a sequence ends.
KV per token 327,680 bytes. Contiguous 4,096-token reservation: 1,342,177,280 bytes (1.25 GiB); 64e9 ÷ 1.34e9 ≈ 47 sequences. Paged 704-token footprint: 230,686,720 bytes; 64e9 ÷ 2.31e8 ≈ 277 sequences, about 5.9 times more.
Sharing, preemption and design trade-offs
Because blocks are addressed indirectly, different sequences can point to the same physical block. Reference counts track sharers. For parallel sampling or beam search, all samples share the prompt's blocks and diverge only in new blocks; when a sequence must write into a shared block (the partially filled last prompt block), copy-on-write copies just that block. Hash-based prefix caching extends this across requests: a block's identity is a hash of its tokens plus its prefix, so any new request with the same prefix maps to existing blocks. Sharing saves memory (for 4 samples of a 2,000-token prompt with 300 new tokens each: 3,200 tokens versus 9,200) and prefill compute.
When the pool is exhausted, the scheduler can preempt a sequence: swap its blocks to CPU memory and bring them back later, or recompute them from the prompt. Design choices include block size (16 tokens balances waste against kernel efficiency; very small blocks increase table size and gather overhead, large blocks waste more per sequence), eviction policy for cached prefix blocks (LRU) and KV quantisation (FP8 halves bytes per token and doubles capacity at some accuracy risk). Monitor KV utilisation, preemption rate and cache hit rate; sustained utilisation near 100% with preemptions means you need more memory, shorter contexts, quantisation or more replicas.
n = 4 samples from a 2,000-token prompt, 300 generated tokens each. No sharing: 4 × 2,300 = 9,200 tokens. With shared prompt blocks: 2,000 + 4 × 300 = 3,200 tokens, a 65% reduction, with copy-on-write used only for the last partial prompt block.
How it works, step by step
Step 1 of 41. Compute KV bytes per token
Use 2 × layers × KV heads × head dimension × bytes per element for your model and precision.
- FP8 KV
- halves it
When to use it & trade-offs
What it is
PagedAttention manages the KV cache of an LLM server the way an operating system manages memory: it splits each sequence's cache into fixed-size blocks (for example 16 tokens), allocates physical blocks on demand from a shared pool and records the mapping in a block table, so a sequence's cache needn't be contiguous. The attention kernel reads keys and values through that table. This removes the memory wasted by reserving a worst-case contiguous buffer per request, allows sharing of blocks between sequences (common prompts, parallel samples) with copy-on-write, and lets the server hold many more concurrent sequences in the same GPU memory.
Why it matters: After the weights are loaded, KV cache memory decides how many requests a GPU can serve at once, and concurrency decides throughput and cost. Older serving systems reserved space for the maximum output length up front, leaving most of it empty and fragmenting the rest, so only around 20% to 40% of reserved KV memory held real tokens. Paging recovers that waste and is the foundation of continuous batching and prefix caching in modern engines.
When to reach for it
- Any LLM serving engine handling variable-length chats
- Parallel sampling and beam search
- Workloads with shared system prompts or documents
When to avoid or be careful
- Reserving the maximum context for every request
- Choosing huge block sizes that waste memory per sequence
- Ignoring preemption signals
KV cache memory strategies
Strengths: Minimal waste; sharing; high concurrency.
Watch out: Kernel indirection and block-manager complexity.
Strengths: Simple allocation.
Watch out: Large internal and external fragmentation.
Strengths: Halves bytes per token.
Watch out: Possible small accuracy loss; needs evaluation.
Interview signals & numbers to know
When this topic comes up
- “We run out of GPU memory at low concurrency”
- KV cache fragmentation
- Block table
- Copy-on-write for samples
- Preemption by swap or recompute
Benchmarks & rules of thumb
- 47 vs 277
- concurrent sequences in 64 GB: contiguous vs paged
- 0.6%
- waste from a 700-token sequence in 16-token blocks
- 3,200 vs 9,200
- tokens stored for 4 samples with and without sharing
Common mistakes & follow-ups
Common interview mistakes
- Assuming weights are the only memory constraint and ignoring KV.
- Setting max model length far above real needs and shrinking effective capacity.
- Not checking quality after quantising the KV cache.
Likely interviewer follow-ups
- What problem does PagedAttention solve?
- How does copy-on-write help parallel sampling?
- What happens when KV blocks run out?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply PagedAttention with generative AI interview Q&A and hands-on practice.