PagedAttention: Why Splitting the KV Cache into Blocks Lets Long Contexts Fit in Memory
PagedAttention: Why Splitting the KV Cache into Blocks Lets Long Contexts Fit in Memory Serving a large language model is, to a surprising extent, a memory management problem. The weights are large, but they are fixed.
PagedAttention: Why Splitting the KV Cache into Blocks Lets Long Contexts Fit in Memory
Serving a large language model is, to a surprising extent, a memory management problem. The weights are large, but they are fixed. The part that grows while a request runs is the key-value cache, the stored keys and values for every token generated so far. When that cache is managed badly, most of the GPU memory set aside for it sits empty, and requests that could have run together wait in a queue instead. PagedAttention fixes the management, not the model, and the fix is borrowed from an old idea in operating systems: paging.
The idea was introduced in the vLLM system by Kwon and colleagues in 2023. It does not change what attention computes. It changes where the keys and values live, and how they are found, so that memory is allocated only when it is actually needed and can be shared when several requests need the same tokens.
The KV cache problem
A transformer generates one token at a time. At each step it attends to all previous tokens, and recomputing their keys and values from scratch would be far too slow. So the system caches them: after the prompt is processed, the key and value vectors for every prompt token are stored, and each newly generated token adds one more key and one more value per layer.
The cache is not small. Take a model with 32 layers and a hidden size of 4096, stored in 16-bit precision. Each token needs a key and a value in every layer, so the cache holds
about half a megabyte per token. A 2048-token sequence needs about a gigabyte of cache, for one request. A server holding dozens of concurrent requests needs tens of gigabytes just for this cache, on top of the weights.
Early serving systems handled this by reserving a contiguous chunk of memory for each request, sized for the maximum sequence length it might reach. That is simple, and it wastes almost everything. A request that ends after 300 tokens holds a reservation for 2048. The unused part cannot be given to another request, because it sits in the middle of a contiguous allocation. This is internal fragmentation, and in practice it meant that a large fraction of the cache memory was reserved but never read.
There is a second waste. Many requests share a prefix: the same system prompt, the same few-shot examples, the same document being asked about. With contiguous per-request allocations, each request stores its own copy of those shared keys and values.
Paging, borrowed from operating systems
Operating systems solved an analogous problem decades ago. A process sees a contiguous virtual address space, but the memory underneath is divided into fixed-size pages, and pages are allocated only when the process touches them. Two processes can even share a physical page when they map the same file.
PagedAttention applies the same split to the KV cache. The cache is divided into blocks, each holding the keys and values for a fixed number of tokens, commonly 16. A request's cache is a sequence of logical blocks. A block table maps each logical block to a physical block in GPU memory. The physical blocks for one request need not be adjacent, and they are allocated only when the request actually fills them.
When a request starts, it gets one physical block for its first 16 tokens. When token 17 arrives, the system allocates another block. A request that stops at 300 tokens holds 19 blocks, not a reservation for 2048. The waste is at most one partly filled block per request, instead of up to a whole maximum-length reservation. If the block holds B tokens and a request has generated n tokens, the fraction of allocated cache that is wasted is bounded by
which shrinks as the sequence grows, and is small for the long sequences that matter most.
The block table
The block table is the only new data structure, and it is small. For a request with n tokens and block size B , the table has about n/B entries, each naming one physical block. The attention kernel reads the table, looks up the physical block for each logical position, and gathers the keys and values from wherever they happen to live.
That lookup is the price of paging. Attention can no longer assume the keys sit in one neat array. The kernel has to follow pointers, one block at a time. In practice the cost is small compared with the memory saved, because the lookup happens once per block rather than once per token, and the blocks are large enough that the gather is efficient.
A simple sketch of the mapping looks like this:
# block_size = 16 tokens per block
# block_table: logical block index -> physical block index
def block_for_position(block_table, position, block_size=16):
logical_block = position // block_size
offset = position % block_size
physical_block = block_table[logical_block]
return physical_block, offset
# allocating the next block only when the current one fills up
if len(generated) % block_size == 0:
block_table.append(allocate_free_block())
Nothing here touches the model. The same weights, the same attention scores, the same sampling. Only the storage layout changes.
Attention over blocks
Computing attention from scattered blocks needs one more piece of care. The softmax over the whole sequence cannot be computed block by block in the naive way, because each block's scores need to be normalised by the total over all blocks. The kernel handles this with the same online softmax trick used in FlashAttention: it processes one block at a time, keeping a running maximum and a running sum of exponentials, and rescales the accumulated output as each new block arrives.
For a query q and the keys K in one block, the block's scores are
and the running normaliser is updated with the block maximum m through
so that by the last block the output is exactly the standard attention output, just computed in pieces. The result is numerically identical to attention over a contiguous cache. PagedAttention changes no floating point result, only the order in which partial results are combined, up to the usual floating point rounding of a different summation order.
Sharing: the part that pays twice
Paging buys a second benefit that contiguous allocation cannot offer at all: sharing. Because a block is a self-contained unit with a reference count, several requests can point at the same physical block.
Parallel sampling is the clearest case. Ask a model for four completions of the same prompt, and the prompt's keys and values are identical in all four. With paging, the prompt blocks are stored once and shared, with a reference count of four. Each completion only allocates new blocks for the tokens it generates itself. When a shared block needs to be written to, it is copied first, the classic copy-on-write rule, so one request's generation never corrupts another's.
Beam search shares in the same way. The beams diverge gradually, and until they do, they share the prefix blocks. Prefix caching goes further: if a new request arrives with a prompt that matches a cached prefix, its first blocks can be mapped straight onto the existing physical blocks instead of recomputing them.
The memory saving here is not a small constant. For parallel sampling with k samples sharing a prompt of p tokens, the shared prompt costs p tokens of cache once, not kΓp . The saving grows with the number of samples and with the length of the shared prompt, which is exactly the regime where serving is most expensive.
Choosing the block size
The block size is the one tuning knob, and it is a genuine trade-off. A smaller block wastes less space at the end of each sequence and shares more finely, since a shared prefix can be cut at a smaller boundary. But a smaller block means a bigger block table, more lookups per token, and more kernel launches per attention computation. A larger block amortises those costs and keeps the kernel simple, at the price of more waste in the final partly filled block and coarser sharing.
Sixteen tokens per block is the common default in vLLM, and it is a reasonable middle ground for the models and sequence lengths in wide use. The right value depends on the workload: short requests with long shared prompts favour smaller blocks, while very long single sequences care less, because the waste in one final block is a small fraction of a long cache either way.
Using it in practice
PagedAttention is the memory manager inside vLLM, and the same design has since appeared in other serving systems. From the user's side, nothing changes: you send a prompt and get text back. The difference shows up in the numbers a serving operator watches, throughput and latency under load. With the same GPU memory, more requests fit at once, so the queue drains faster and the time to first token falls when the system is busy.
That is worth stating plainly, because it sets the right expectation. PagedAttention does not make a single request faster. For one request running alone, the block lookups add a small overhead and the latency is essentially unchanged, sometimes slightly worse. The win is entirely about the batch: more concurrent requests per gigabyte of cache memory, less time spent waiting for a slot.
If you are choosing a serving stack, the practical questions are therefore about the workload, not the algorithm. How long are your prompts, how much do they share a prefix, how many samples do you draw per prompt, and how often is the system actually memory bound rather than compute bound? If prompts are long and shared, paging pays for itself quickly. If requests are short and independent, the gain is smaller, though the fragmentation saving alone is usually still worth having.
Limitations and pitfalls
Paging solves the memory management problem, and it is worth knowing what it does not solve. It does not reduce the compute of attention, which still grows with sequence length. It does not shrink the weights, and it does not help a request whose bottleneck is generating tokens one at a time on a single stream.
It also adds a failure mode that contiguous allocation did not have: the block table itself. A bug in allocation, reference counting, or copy-on-write handling corrupts the cache silently, producing wrong text rather than an error. The systems that ship this code test the manager heavily, and for good reason. And the kernel that gathers keys from scattered blocks is harder to write well than a kernel that reads one contiguous array, so a poor implementation can give back in speed some of what paging saves in memory.
A final pitfall is to confuse paging with prefix caching. They are related but different. Paging makes sharing possible, because blocks are the unit that can be shared. Prefix caching is a policy built on top of it: deciding which blocks to keep after a request finishes, and matching a new prompt against them. You can have paging without prefix caching, and you cannot have fine-grained prefix caching without something like paging underneath.
Takeaway
The KV cache is the working memory of a serving system, and for a long time it was managed as if memory were free and contiguous. PagedAttention treats it the way operating systems treat memory: split it into fixed-size blocks, allocate them on demand, map logical blocks to physical ones through a table, and share a physical block whenever several requests need the same tokens. Attention itself is unchanged, computed block by block with an online softmax. The payoff is less wasted memory, more concurrent requests per GPU, and a clean basis for sharing prefixes and samples. The cost is a lookup per block and a memory manager that has to be correct.
Connect with me on LinkedIn: linkedin.com/in/umeshtharukaofficial
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.