Sub topic 4
PagedAttention: managing the KV cache in blocks
This chapter assumes you know what the KV cache is and why it grows with every generated token (covered in the previous chapter). You should also be comfortable reading short Python snippets and thinking about GPU memory as a fixed budget.
The problem: contiguous allocation wastes memory
Each running request owns a KV cache. For every token in the sequence, the cache stores one key vector and one value vector per layer. The cache grows by one token at each decode step.
A simple server allocates one contiguous region of GPU memory per request. It does not know how long the output will be, so it must reserve space for the worst case, usually the maximum sequence length. This causes three kinds of waste:
- Internal fragmentation. The request reserved room for 4096 tokens but produced 300. The remaining space is held and unused.
- Reservation waste. Space for tokens that will be generated later sits empty while the request runs. No other request can use it.
- External fragmentation. Requests finish at different times and leave holes of different sizes. A new request may need a large contiguous region and fail to fit, even though the total free memory is large enough.
The vLLM paper that introduced PagedAttention reported that earlier systems used only a fraction of KV cache memory for real token data. The exact fraction depends on the workload. The direction is the point: wasted cache means fewer concurrent requests, and fewer concurrent requests means lower throughput.
The idea: borrow virtual memory from operating systems
Operating systems solved a similar problem decades ago. A program sees a contiguous virtual address space. The OS splits memory into fixed-size pages and maps virtual pages to physical pages through a page table. The physical pages can be anywhere.
PagedAttention applies the same design to the KV cache:
- The cache is divided into fixed-size blocks. Each block holds the keys and values for a set number of tokens. The default block size in recent vLLM versions is 16 tokens.
- A sequence is a list of logical blocks, in token order.
- A block table maps each logical block to a physical block in GPU memory. Physical blocks need not be adjacent.
- Blocks are allocated on demand. A new block is taken from a free pool only when the current one is full.
The attention kernel is rewritten to read keys and values through the block table. That is where the name comes from: attention that works over paged memory.
What this saves
Waste is now limited to the last block of each sequence, which may be partly filled. With 16-token blocks, a sequence wastes at most 15 token slots. There is no worst-case reservation and no external fragmentation, because every block is the same size and any free block can serve any sequence.
The saved memory is not an end in itself. It lets the scheduler keep more sequences running at once, and a larger batch gives higher throughput. The next chapter covers the scheduler.
A worked calculation
Memory per token depends on the model. For a model with L layers, H_kv key/value heads, head dimension D, and B bytes per element, the cache needs:
2 * L * H_kv * D * B bytes per token
The factor 2 covers keys and values. The following script computes this for a configuration like Qwen2.5-1.5B (28 layers, 2 KV heads, head dimension 128, 16-bit values) and compares block-based allocation with worst-case reservation.
import math
layers = 28
kv_heads = 2
head_dim = 128
bytes_per_elem = 2 # fp16 / bf16
block_size = 16 # tokens per block
max_model_len = 4096
bytes_per_token = 2 * layers * kv_heads * head_dim * bytes_per_elem
bytes_per_block = bytes_per_token * block_size
def paged_bytes(actual_tokens: int) -> int:
blocks = math.ceil(actual_tokens / block_size)
return blocks * bytes_per_block
def reserved_bytes() -> int:
return max_model_len * bytes_per_token
actual = 300
print(f"bytes per token: {bytes_per_token}")
print(f"bytes per block: {bytes_per_block}")
print(f"paged, 300 tokens: {paged_bytes(actual) / 1024:.0f} KiB")
print(f"reserved, 4096: {reserved_bytes() / 1024:.0f} KiB")
print(f"requests per GiB (paged): {int(1024**3 // paged_bytes(actual))}")
print(f"requests per GiB (reserved): {int(1024**3 // reserved_bytes())}")For these numbers, one token costs 28,672 bytes. A 300-token request takes 19 blocks, about 8.5 MiB with paging, against 112 MiB when reserving for 4096 tokens. That is roughly 13 times as many concurrent requests in the same memory. Real gains depend on how long your requests actually are. If every request runs to the full context length, the gain shrinks.
Sharing blocks between sequences
Because blocks are reached through a table, two sequences can point to the same physical block. vLLM tracks a reference count on each block.
- Parallel sampling. When you ask for
n=4completions of one prompt, all four share the prompt's blocks. Only the blocks written during generation are separate. - Copy-on-write. If a shared block must change, for example when two sequences share a partly filled last block and one appends a token, vLLM copies the block first. Each sequence then writes to its own copy.
- Prefix sharing. Requests that begin with the same tokens, such as a long system prompt, can reuse the same physical blocks. vLLM exposes this as automatic prefix caching, which has its own chapter.
Running out of blocks
The pool of physical blocks is finite. Its size is set when the server starts, from the memory left after model weights and activations, within the share you allow through gpu_memory_utilization. At startup vLLM logs the result, in a line similar to GPU KV cache size: N tokens. Read it. It tells you how many tokens of context can be live across all requests at once.
When the pool is full and a running sequence needs a new block, the scheduler must make room. It does this by preempting a sequence, which means pausing it and freeing its blocks. The preempted request goes back to the waiting queue. When it resumes, vLLM recomputes its KV cache (in recent versions) or swaps it to CPU memory (in older ones). Either way, preemption costs latency.
Common errors and misunderstandings
- "PagedAttention makes attention faster." Not directly. It makes memory use efficient. The custom kernel has some indirection overhead, and the gain comes from fitting more requests in the batch.
- "Paging means the cache lives in CPU memory." No. The blocks are in GPU memory. The "pages" are a bookkeeping scheme, not a swap file.
- Setting a huge
max_model_lento be safe. Under paging this no longer reserves memory per request. But vLLM checks at startup that the pool can hold at least one full-length sequence, and it fails if not. A large value can therefore stop the server from starting, or leave room for only a few such requests. - Confusing the weights with the cache. Weights are fixed in size. The block pool takes whatever is left, so a larger model leaves fewer blocks.
- Expecting zero waste. The last block of each sequence is still partly empty. With very many short sequences this is a small but real cost.
Summary of the mechanism
| Concern | Contiguous allocation | PagedAttention |
|---|---|---|
| Unit of allocation | One region per request | Fixed-size blocks |
| Reservation | Worst-case length | On demand |
| Fragmentation | Internal and external | Only the last block |
| Sharing between requests | Copy the data | Shared blocks with reference counts |
| Effect on batch size | Small | Larger |
Exercise
A model uses 100,000 bytes of KV cache per token, and the block size is 16 tokens. A request has a 1,000-token prompt and generates 50 tokens. How many blocks does it hold at the end, how many token slots in the last block are unused, and how much memory is that in total?
Show answer
The sequence has 1,050 tokens. 1,050 / 16 = 65.6, so it needs 66 blocks. 66 16 = 1,056 slots, so 6 slots in the last block are unused. Total memory is 66 16 * 100,000 = 105,600,000 bytes, about 105.6 MB, of which 600,000 bytes (0.6 MB) is unused.
Exercise
You start a server and the log shows a KV cache of 40,000 tokens. Requests average 2,000 tokens in total, counting prompt and output. Roughly how many requests can run at once, and what happens if more arrive?
Show answer
About 20 requests (40,000 / 2,000), less in practice because of partly filled last blocks. Extra requests wait in the queue. If running requests grow and the pool fills, the scheduler preempts some sequences, frees their blocks, and resumes them later, which adds latency.