Skip to content
Inference Academy

PagedAttention explained: virtual memory for the KV cache

How vLLM's PagedAttention stores the KV cache in small fixed-size blocks instead of one big reservation per request, a worked example of how many more requests that fits, how block tables and the paged attention kernel work, how the same idea enables prefix caching, parallel sampling and copy-on-write, what happens when memory runs out, and the settings and log lines worth knowing.

Key takeaways

  • Reserving one contiguous KV region per request for the worst case wastes most of the cache memory.
  • PagedAttention stores the KV cache in fixed-size blocks mapped by a per-request block table, allocated on demand.
  • In a worked 70B example, paging fits about 4 times as many requests in the same memory as worst-case reservation.
  • Shared blocks enable prefix caching, parallel sampling and copy-on-write.
  • It removes waste but doesn't shrink the per-token cache; put variable prompt content last so prefixes stay shareable.

By

7 min read

Share
On this page

Before PagedAttention, LLM servers wasted most of the memory they set aside for the KV cache. The fix, introduced with vLLM, borrowed one of the oldest ideas in operating systems: paging. It's worth understanding because it shapes how every modern engine manages memory, and because the same structure makes prefix caching almost free.

#The problem: reserving for the worst case

Each request's KV cache grows by one entry per token (KV cache explained). The server doesn't know in advance how long an answer will be. The simple approach reserves one contiguous region per request, big enough for the maximum length.

That wastes memory three ways:

  1. Over-reservation. A request that might reach 4,096 tokens but stops at 300 holds memory for 3,796 tokens it never uses.
  2. Internal fragmentation. Even when reservations are rounded sensibly, unused tails add up across many requests.
  3. External fragmentation. As requests of different sizes come and go, free memory breaks into gaps too small for a new reservation, even when the total free space would be enough.

The vLLM paper measured existing systems and found that only about 20 to 38 percent of their KV cache memory held actual token data; the rest was wasted. Less usable memory means fewer concurrent requests, smaller batches and higher cost per token.

#A worked example

Take a Llama-class 70B model with an FP8 KV cache: 160 KiB per token. A node has about 500 GB free for the cache. The server allows up to 8,192 tokens per request, but the average request actually uses about 2,048.

Approach Memory per request Requests that fit
Reserve the maximum (8,192 tokens) about 1.34 GB about 370
Allocate only what's used (about 2,048 tokens) about 0.34 GB about 1,490

Paging fits about 4 times as many requests in the same memory, and with more requests in the batch, throughput rises with it (continuous batching explained). The paper reported throughput gains of 2 to 4 times over the systems of the time.

#The idea: fixed-size pages and a block table

PagedAttention splits each request's KV cache into blocks of a fixed number of tokens (16 is a common size). Blocks live anywhere in a big shared pool. Each request has a block table that maps its logical blocks (block 0, 1, 2 and so on) to physical blocks in the pool.

Paged attention: KV memory in blocks, allocated on demand
Animated

Contiguous: reserve the maximum length (6 blocks) per sequence

Paged: blocks handed out as tokens arrive

A: 1 blockB: 0 blocksC: 0 blocksfree: 15

Sequence A starts

Its first 16 tokens fill one block. Contiguous allocation (top) must reserve room for the maximum length up front.

Each cell is a 16-token block of KV memory. Colour = which sequence owns it; hatched = reserved but empty.

  • Allocation is on demand. A request gets a new block only when it fills the last one. The most it can waste is the unused part of its final block: under 16 tokens, about 2.6 MB in the 70B example.
  • No fragmentation problem. Any free block can serve any request, so free memory is always usable.
  • Freeing is instant. When a request finishes, its blocks go back to the pool.

This is exactly how virtual memory works in an operating system: processes see contiguous addresses, while physical pages are scattered. Here, requests see a contiguous sequence of tokens, while their KV blocks are scattered.

#A block table, concretely

A request has 50 tokens so far. With 16-token blocks, it needs 4 blocks: three full ones and one holding 2 tokens. Its block table might read:

Logical block Tokens Physical block
0 0 to 15 7
1 16 to 31 2
2 32 to 47 19
3 48 to 49 (14 slots free) 4

When token 64 arrives, block 3 is full, so the engine takes any free physical block (say 31) and appends it to the table. Nothing is copied or moved.

#What changes in the attention kernel

Standard attention kernels expect each sequence's keys and values to be contiguous. A paged attention kernel instead:

  1. Looks up the block table for the sequence.
  2. For each logical block, finds the physical block and loads its keys and values.
  3. Runs the usual attention maths (with an online softmax across blocks).

The extra indirection costs very little, because each block holds enough contiguous data (16 tokens times the KV heads times the head dimension) for efficient memory reads. Decode attention is limited by bandwidth anyway, so the kernel's job is to stream the blocks as fast as memory allows. If you want to see one written out, the decode-attention kernel lesson builds a paged, split-KV kernel in Triton.

#The bonus: sharing blocks

Once the cache is a set of blocks referenced by tables, two requests can point at the same physical block. Each block keeps a reference count, and it's only freed when no table points at it. That unlocks:

  • Prefix caching. If 1,000 requests start with the same 2,000-token system prompt, the prompt's blocks are computed once and shared. Each new request skips that part of prefill entirely and stores nothing extra for it. Engines look up prefixes by hashing block contents (vLLM) or with a radix tree of token sequences (SGLang's RadixAttention; see vLLM vs SGLang).
  • Parallel sampling and beam search. Several candidate continuations of one prompt share the prompt's blocks, and only diverge when they write new tokens.
  • Copy-on-write. If a shared block needs to change, the engine copies it first, just as an operating system does with shared pages after fork.

#How prefix lookup works

In vLLM, each full block gets a hash computed from its own tokens and the hash of the block before it. So a block's hash identifies the entire prefix up to and including it. When a new request arrives, the engine hashes its prompt block by block and looks each hash up; every hit is a block it doesn't need to compute or store. Blocks no longer used by any request stay in the cache until memory is needed, then the least recently used are evicted.

Because hashing works on whole blocks, a shared prefix of 2,000 tokens reuses 125 full blocks; only the tokens after the last full shared block are recomputed.

#How much sharing saves

Ask for 4 samples of an answer to a 2,000-token prompt, each 500 tokens long:

  • Without sharing: 4×(2,000+500)=10,0004 \times (2{,}000 + 500) = 10{,}000 tokens of cache.
  • With sharing: 2,000+4×500=4,0002{,}000 + 4 \times 500 = 4{,}000 tokens of cache.

Prefix caching is one of the biggest real-world wins for chat and agent workloads, where most of each request is a repeated system prompt, tool definitions and conversation history. The prompt cache calculator estimates the savings for your traffic.

#When the pool runs out

Paging makes memory go further, but it can still fill up, for example when a burst of long requests arrives. The scheduler then preempts some running requests:

  • Recompute: free their blocks and later re-run their prefill from the tokens so far. Cheap in memory, costs compute.
  • Swap: copy their blocks to CPU memory and back later. Costs PCIe bandwidth.

Either way, preempted users see a pause. Frequent preemption means you've admitted more concurrent requests than memory supports; lower the maximum number of sequences or add memory (scheduling and preemption).

#Settings worth knowing

  • Block size (vLLM's --block-size): the default is a good choice for most cases. Smaller blocks waste less but add indexing overhead.
  • GPU memory utilisation (--gpu-memory-utilization): decides how big the block pool is after the weights are loaded.
  • Maximum model length (--max-model-len): doesn't reserve memory per request any more, but the engine checks at startup that at least one maximum-length request fits.
  • Prefix caching: on by default in recent vLLM versions; check your version and confirm the hit rate in the metrics.

At startup, vLLM logs how much KV cache it allocated, in tokens, and the maximum concurrency that implies for a maximum-length request. That's the single most useful number for capacity planning on one replica.

#What it doesn't fix

PagedAttention removes waste. It doesn't make the KV cache per token smaller. For that you need architectural changes (GQA, MLA), FP8 KV cache, or offloading (GQA vs MQA vs MLA). And when the pool is full, the engine still has to preempt requests.

#Common mistakes

  • Reading "KV blocks available" as requests. Divide by tokens per request (prompt plus expected output), then by block size.
  • Assuming prefix caching works across different system prompts. Any change early in the prompt (a timestamp, a user name) breaks sharing for everything after it. Put variable content last.
  • Not checking the prefix cache hit rate after a prompt change.
  • Ignoring preemption counters, which reveal that concurrency is set too high.

#FAQ

Is PagedAttention only in vLLM? The idea is now standard. SGLang, TensorRT-LLM, llama.cpp's server and others all use block-based KV management in some form.

Does paging slow attention down? Very slightly. The block-table lookup is cheap next to reading the keys and values themselves, and the extra concurrency it allows more than makes up for it.

Can blocks be moved to CPU memory or disk? Yes. KV offloading tiers build on the same block structure, keeping cold prefixes in cheaper memory and bringing them back on a hit (caching: prefix, semantic and KV).

#Go deeper

Attention optimisations covers PagedAttention alongside FlashAttention, GQA and sliding windows. Caching: prefix, semantic and KV goes deep on prefix caching and offload tiers. Both are in the Inference Engineering course.

paged-attentionkv-cachevllmmemoryinference-engineering

Found this useful?

Send it to someone who is learning the same thing.

Share this article

Next: learn it step by step, free

Prefill, decode and the roofline

Why decode is memory-bound, with worked numbers for real GPUs. The idea the rest builds on. A free lesson with step-through diagrams and a quiz.

Get new articles by email

One short email when a new guide is out. Unsubscribe any time.