Search

Search papers and lessons

Efficient Memory Management for LLM Serving with PagedAttention (vLLM)

Woosuk Kwon, Zhuohan Li, Siyuan Zhuang et al. · 2023

PagedAttention stores each request's KV cache in small blocks that need not sit side by side, like OS pages, so the vLLM server wastes far less GPU memory and serves 2-4x the throughput.

On this page

  • Colour = topic mix
  • Calculus
  • Probability
  • Neural network basics
  • Linear algebra
  • Architectures
  • Systems
  • Sign in to see your progress

TL;DR

Serving a large language model means keeping a cache of past attention keys and values for every running request. Existing systems reserve one contiguous block of GPU memory per request, sized for the longest allowed output, and most of that memory sits empty. PagedAttention splits each cache into small fixed-size blocks that can live anywhere in memory, as operating systems do with pages. The vLLM server built on it wastes almost no cache memory and reports 2-4x the throughput of the systems it was compared with.

Where you'll see it: in LLM inference servers that batch many chat requests on one GPU, and in the vLLM project the paper introduced.

The problem

Generating text with a transformer is one token at a time. Each new token attends to every earlier token, so the server keeps those tokens' key and value vectors, the KV Cache, and reads all of it for each step. Generation is slow per request and leaves the GPU's arithmetic units mostly idle, so the way to raise throughput is to batch many requests together. Batching is limited by memory. The model weights are fixed, and whatever is left over has to hold every request's KV cache.

The paper's Figure 1 example is a 13B-parameter model on a 40 GB NVIDIA A100. About 65% of memory holds the weights and close to 30% holds the request states, so the way the cache is managed decides the batch size. The paper's profiling shows existing systems use only 20.4% to 38.2% of their KV cache memory for real token states. The rest is wasted.

Two causes are named. First, the systems store each request's cache as one contiguous tensor, because deep-learning frameworks expect tensors that way. The length of the output is not known in advance, so the system reserves the maximum length (2048 tokens in the paper's example) up front. That causes internal fragmentation, since short outputs leave the reserved space unused, and external fragmentation between requests of different reserved sizes. Second, requests that share a prefix or sample several outputs from one prompt cannot share their cache, because each sequence sits in its own contiguous region. Parallel sampling and beam search are common in code assistants and translation, so this matters.

Key idea

Borrow the operating system's answer to the same problem. Virtual memory gives a process a contiguous address space while the physical memory behind it is scattered in pages, and pages are allocated only when touched. The paper maps this onto attention. It calls the cache blocks pages, tokens bytes, and requests processes:

  • Each request's cache is cut into KV blocks of a fixed number of tokens, the block size BB (the default in vLLM is 16).
  • Blocks are allocated on demand as tokens arrive, so a request never reserves space it does not use.
  • A block table maps the request's logical blocks to physical blocks in GPU memory, and those physical blocks need not be adjacent.
  • Two sequences can point at the same physical block, and a copy-on-write rule copies a block only when one sequence writes to it.

Because all blocks are the same size, external fragmentation disappears. Because a block is small, internal fragmentation is at most one partly filled block per request.

The method

The attention computation, in blocks

Standard attention for query qiq_i sums over all earlier keys and values. The paper rewrites the same sum over blocks. With key block Kj=(k(j−1)B+1,…,kjB)K_j = (k_{(j-1)B+1}, \ldots, k_{jB}) and value block Vj=(v(j−1)B+1,…,vjB)V_j = (v_{(j-1)B+1}, \ldots, v_{jB}):

Aij=exp⁡(qi⊤Kj/d)∑t=1⌈i/B⌉exp⁡(qi⊤Kt1/d),oi=∑j=1⌈i/B⌉VjAij⊤A_{ij} = \frac{\exp\big(q_i^\top K_j / \sqrt{d}\big)}{\sum_{t=1}^{\lceil i/B \rceil} \exp\big(q_i^\top K_t \mathbf{1} / \sqrt{d}\big)}, \qquad o_i = \sum_{j=1}^{\lceil i/B \rceil} V_j A_{ij}^\top

Here dd is the head dimension, ⌈i/B⌉\lceil i/B \rceil is the number of blocks that hold the first ii tokens, AijA_{ij} is the row of attention scores on block jj, and oio_i is the output. The sum over blocks gives the same result as the original sum over tokens. The only change is that the kernel fetches each block separately, so the blocks need not be contiguous. The paper's Figure 5 example shows a query attending across three blocks that are not adjacent in memory.

Walking through one request

The paper's Figure 6 example uses a block size of 4 so that it fits on a page. The prompt has 7 tokens, so the server maps logical blocks 0 and 1 to two free physical blocks (7 and 1) and reserves nothing else. The prompt's cache fills block 0 with four tokens and block 1 with three, leaving one slot free. The first generated token goes into that free slot. When block 1 fills, the next token triggers a new allocation, and the new block (physical block 3) goes into the block table. At no point does a request hold more than one partly empty block.

Sharing across decoding methods

Parallel sampling, where one prompt yields several outputs, maps the prompt's logical blocks onto the same physical blocks in every sequence. Each physical block has a reference count, and a block is written only after a copy-on-write: when a sequence must write to a block with count greater than one, the server copies that block to a new physical block and lowers the count. In beam search, candidates keep sharing blocks as the beam narrows, and blocks whose count falls to zero are freed. Previous systems had to copy a large part of the cache between beam candidates; here only one block is copied, and only when new tokens land inside a shared block.

A shared prefix, such as a system prompt used by many requests, works the same way: the server keeps the prefix's blocks and each request maps its own blocks after them.

Scheduling and preemption

When memory runs out, vLLM serves requests first come, first served, and preempts the latest arrivals first. It evicts a whole sequence group at once, because sequences that share blocks must move together. Evicted state is either swapped to CPU memory or recomputed when the sequence resumes. The paper finds that swapping costs much more with small blocks, since many small transfers use the PCIe bus poorly, while recomputation cost does not depend on block size. Recomputation was never more than 20% of swapping's latency in its tests, and the two are comparable for block sizes 16 to 64.

Distributed execution

For models too large for one GPU, the paper uses Megatron-style tensor parallelism. Every GPU worker processes the same tokens, so they all need the same positions in the cache. vLLM keeps one block manager in a central scheduler and sends each worker the block table with every step. Each worker stores only its share of the attention heads, but the physical block IDs are the same on all workers.

Results

Throughput. The abstract reports 2-4x throughput over FasterTransformer and Orca at the same latency. On ShareGPT, vLLM sustains 1.7x to 2.7x the request rate of Orca (Oracle), which knows output lengths in advance and is an upper bound, and 2.7x to 8x the rate of Orca (Max), which reserves the full 2048 tokens. Against FasterTransformer the paper reports up to 22x. On the shorter Alpaca traces the gap to Orca (Oracle) is smaller, because the 175B model has so much cache memory that Orca's waste matters less; the paper says those runs become compute-bound.

Shared prefixes and chatbots. With a one-example translation prefix, vLLM reaches 1.67x the throughput of Orca (Oracle). With a five-example prefix, it reaches 3.58x. On a chatbot workload, it sustains about 2x the request rate of the Orca variants.

Memory saved by sharing. On the Alpaca trace, sharing saves 6.1% to 9.8% of blocks for parallel sampling and 37.6% to 55.2% for beam search. On ShareGPT, the figures are 16.2% to 30.5% and 44.3% to 66.3%. Beam search shares the most because its candidates have the longest common histories.

Costs. The paper is open about overhead. Its attention kernel, which reads blocks through a table, is 20% to 26% slower than FasterTransformer's optimised attention kernel. The authors argue this is small because it touches only attention, not the linear layers, and the end-to-end numbers still favour vLLM.

Block size. On ShareGPT, block sizes from 16 to 128 perform best. On Alpaca, larger blocks hurt because the sequences are shorter than the blocks. The authors use 16 as the default because it uses the GPU well and wastes little space in most workloads.

Setup. The experiments use OPT-13B, OPT-66B, OPT-175B and LLaMA-13B on Google Cloud A100 servers, with the workloads synthesised from ShareGPT and Alpaca request lengths and Poisson arrivals.

Why it mattered

The paper's contribution is block-level management of the KV cache, co-designed with PagedAttention and a preemptive scheduler, and built into the vLLM serving engine. The authors say the system achieves near-zero waste in KV cache memory. Its discussion section says the same ideas would not help every GPU workload. Training has static tensor shapes, and non-LLM serving is usually compute-bound, so the extra indirection would only add overhead there. The paper names its own LLM-specific choices: all-or-nothing eviction, which works because a request needs all its cache on the GPU to run, and recomputation, which an operating system cannot use. Those are the claims to take from it.

Reading guide

Read the paper in this order. Each lesson listed is the prerequisite for the section it is placed beside.

  1. Introduction (Section 1): KV Cache for what is being stored, and Language Model for why generation is sequential.
  2. Background (Section 2): Language Model for the autoregressive factorisation in its Equation 1, and KV Cache for the prompt and generation phases.
  3. Memory challenges (Section 3): KV Cache for the size arithmetic, and GPU Memory Hierarchy for why memory bandwidth limits generation speed.
  4. Method, PagedAttention (Section 4.1 and 4.2): Virtual Memory for pages, block tables and the logical-to-physical mapping that the design copies.
  5. Decoding and scheduling (Sections 4.3 to 4.5): Virtual Memory again for copy-on-write, which is the same idea OS fork uses.
  6. Evaluation (Sections 6 and 7): no new prerequisites. The workloads and the throughput measure are defined in the paper.

Check yourself

QuestionA model's KV cache costs 800 KB per token. A request may generate up to 2048 tokens and currently has 100 tokens. How much memory does a contiguous reservation tie up, and how much holds real data?Show answer
The reservation covers the maximum length, so it holds 2048 × 800 KB ≈ 1.6 GB, and the paper gives the same figure. Only 100 × 800 KB = 80 MB holds real token states. That is about 5% utilisation. The rest is reserved but idle, which is the internal fragmentation the paper describes.
QuestionWith a block size of 16, how many blocks does a 100-token request need, and how many slots are wasted in its last block?Show answer
100 / 16 = 6.25, so the request needs 7 blocks, which hold 112 slots. The last block has 12 unused slots. That is less than one block of waste per request, and it is the only waste in the scheme, since every other block is full. The paper's block-size study picks 16 for this reason.
QuestionWhy does the paper use copy-on-write for parallel sampling instead of copying the prompt's cache for each output?Show answer
Copying the prompt's cache for every output multiplies the memory used by the prompt by the number of samples. With copy-on-write, all samples point to the same physical blocks while they only read them, and a block is duplicated only when a sample must write into it. The reference count tells the server when a block is still shared. The paper's example shows that only the final, partly filled block is copied. The paper measures the resulting saving at 37.6% to 55.2% on Alpaca for beam search, which combines this sharing with the block layout.
QuestionWhy is it harder to share the cache across beam-search candidates in a contiguous layout than in the paged layout?Show answer
In a contiguous layout each candidate owns a separate region, so sharing a prefix means copying it into the new candidate's region. Beam search rewires candidates every step, so those copies happen often. In the paged layout a candidate's history is a list of block IDs, so a new candidate only copies the table and the reference counts change. The paper reports that the copying in earlier systems is expensive and that vLLM copies one block at most.
QuestionThe paper's kernel is 20% to 26% slower than FasterTransformer's attention, yet the paper argues vLLM is faster end to end. Explain the apparent conflict.Show answer
Attention is one operator in the model. The rest, including the linear layers, is unchanged, and the faster batching from freed memory dominates end to end. The paper's throughput results come from serving many requests, which PagedAttention makes possible. The kernel cost is measured separately, as a microbenchmark in its ablations (Section 7.1), and it is not the same experiment as the serving throughput results.

Sources

Read the full paper

Woosuk Kwon, Zhuohan Li, Siyuan Zhuang et al., 2023. arXiv:2309.06180