Dev Pratap Singh

PagedAttention: The Paper That Made LLM Inference Click for Me

PagedAttention 8 min

Notes from reading “Efficient Memory Management for Large Language Model Serving with PagedAttention”

I picked up this paper because I wanted to understand what vLLM was doing under the hood. I had heard about KV cache, but hadn't connected it to context length, GPU memory and serving capacity.

This paper helped me see how they fit together.

It isn't proposing a new language model. It looks at a problem that appears when a trained model is serving requests: how do you keep the attention state for many users without wasting GPU memory?

First, how does an LLM generate a response?

An autoregressive language model produces text one token at a time. It reads the prompt, predicts a distribution for the next token, selects one, appends it to the sequence, and repeats. Every new prediction depends on the tokens that came before it.

Inside a Transformer, self-attention lets each token use information from earlier tokens. The model projects each token representation into three vectors: Query (Q), Key (K) and Value (V). I remember them this way: the query is what the current position is looking for; keys help decide which earlier tokens are relevant; values contain the information that gets mixed into the output.

Attention compares the query with keys, turns the scores into weights with softmax, and uses those weights to combine the values:

Attention(Q, K, V) = softmax(QKᵀ / √dₖ) V

A causal mask stops a token from looking at future tokens. It can only use its own position and what came before.

The detail that matters here is that every new token needs keys and values from earlier tokens.

Why keep a KV cache?

Imagine the model has already processed the prompt and generated a few tokens. To produce the next token, attention needs the previous tokens' keys and values. Those tensors have already been calculated. Recomputing them at every step would be wasted work.

So the model keeps them in memory. This is the KV cache: the Key and Value tensors for processed tokens across the model's layers and KV heads. When a new token is generated, the model calculates its K and V, adds them to the cache, and reuses the older entries on the next step. It isn't a copy of the text; it's the model's attention state stored as tensors.

Inference has two phases: prefill processes the prompt in parallel and creates the initial cache; decode generates one token per iteration, reusing the cache and adding the new token's K and V.

Prefill uses large parallel matrix operations. Decode is sequential because each token depends on the previous one, and the paper describes it as memory-bound: the GPU repeatedly reads model weights and the growing cache for each new token.

The cache saves computation, but grows with every active sequence.

The memory number that made this real

The paper uses OPT-13B to show how large the cache can get. It has 40 Transformer layers and a hidden size of 5,120. With FP16 values, each element takes 2 bytes. For this standard multi-head attention example, the cache for one token is:

2 (Key and Value) × 5,120 × 40 layers × 2 bytes = 819,200 bytes

That's about 800 KB per token. At 2,048 tokens, one request can need roughly 1.6 GB of KV cache.

A more general estimate is:

KV bytes = 2 × layers × tokens × KV heads × head dimension × bytes per value

The exact number depends on the model. Grouped-query and multi-query attention use fewer KV heads, reducing cache size. Context length and active request count both increase memory usage.

The GPU also holds model weights and temporary activations. In the paper's A100 40 GB example for a 13B model, weights use about 26 GB and KV cache takes close to 30% of memory. Request state is a significant part of the GPU budget.

The allocation problem

A serving system doesn't know how long a request will run. One might stop after 80 tokens; another might approach its maximum length.

The systems discussed in the paper reserve a contiguous chunk for each request, often sized for its maximum sequence length. That is a poor fit for data that grows while the request runs.

The paper identifies three kinds of waste: reserved memory held for possible future tokens; internal fragmentation, the unused tail when a request finishes early; and external fragmentation, where free memory is split into holes too small for a new contiguous allocation.

In the tested existing systems, only 20.4% to 38.2% of allocated KV cache memory held actual token states. In vLLM, the paper reports 96.3%. The result makes the cost of poor allocation concrete: GPU memory can be occupied without holding useful KV data.

The OS idea behind PagedAttention

The solution borrows virtual memory from operating systems. A process sees a continuous logical address space, while the OS maps its pages to physical frames that need not be adjacent.

PagedAttention applies a similar idea to the KV cache. It divides a sequence's cache into fixed-size KV blocks. Each block holds the keys and values for a fixed number of tokens. A request has logical blocks (0, 1, 2, and so on), and a block table maps those logical blocks to physical blocks in GPU memory.

For example, logical blocks 0, 1 and 2 could map to physical blocks 7, 1 and 3. The order of the sequence is preserved; only the physical placement is scattered.

Blocks are allocated as the cache grows. If the last block has room, the new K and V go there; once it is full, another physical block is allocated and the table is updated. Finished requests release their blocks.

The PagedAttention kernel follows the block table, reads the relevant K and V blocks, and calculates attention across them. The attention calculation is still exact; PagedAttention changes how K/V data is stored and accessed.

Equal-sized blocks avoid external fragmentation in the block pool. Since a sequence only leaves unused space in its final block, the internal waste is limited to that one block. The paper uses a block size of 16 tokens in its evaluation. Smaller blocks reduce unused space at the end; larger blocks can let the kernel process more tokens together. It's a trade-off between memory waste and execution efficiency.

Sharing and serving requests

Sharing is another benefit. If one prompt produces four sampled outputs, all four sequences can point to the same physical blocks for their common prefix instead of keeping four copies.

They cannot share the parts where their generated tokens differ. vLLM tracks how many sequences reference a physical block using a reference count. If one sequence needs to write into a block that is still shared, it uses copy-on-write: allocate a new block, copy the contents, and let that sequence continue on its own copy. The other sequence keeps the original.

The paper also covers beam search, where candidates may share more than the prompt, and common prefixes across requests, such as repeated system prompts and examples.

PagedAttention is the memory-access mechanism; vLLM is the serving system around it. The scheduler chooses sequences for each iteration, the KV cache manager handles blocks and tables, and GPU workers run the model.

vLLM also uses iteration-level scheduling, often called continuous batching. Rather than waiting for every request in a batch to finish, completed sequences can leave after an iteration and new ones can join.

When GPU memory runs short, vLLM can swap a sequence's KV blocks to CPU memory and restore them later, or discard the cache and recompute it when the sequence runs again. The trade-off is data transfer versus extra computation.

For models spread across GPUs, the paper uses tensor parallelism. The central scheduler shares block-table information with workers; each worker holds the KV cache for its attention-head shard and participates in collective communication.

What I took away

In the paper's experiments, vLLM achieved 2–4× higher serving throughput at similar latency than the systems it compared against. That result applies to the paper's models, hardware and workloads; it isn't a guarantee for every deployment.

What stayed with me is how the pieces connect: generation creates a growing KV cache; unpredictable request lengths make contiguous allocation wasteful; PagedAttention borrows OS-style paging so the cache can grow in blocks and share common prefixes.

I started this paper wanting to understand one serving engine. I finished with a much clearer picture of why KV cache is such a big part of LLM inference, and why memory management affects how many requests a GPU can serve.

Paper: Efficient Memory Management for Large Language Model Serving with PagedAttention, Woosuk Kwon et al., SOSP 2023.

Comments

No comments yet.