Back to paper library
Paper notesarXiv 2023SOSP 2023

PagedAttention

More Empty Seats Than Guests

Original paper

Efficient Memory Management for Large Language Model Serving with PagedAttention

Paper authors

Woosuk Kwon · Zhuohan Li · Siyuan Zhuang …

Show all 9 authors

Woosuk Kwon · Zhuohan Li · Siyuan Zhuang · Ying Sheng · Lianmin Zheng · Cody Hao Yu · Joseph E. Gonzalez · Hao Zhang · Ion Stoica

Publication
SOSP 2023Conference
First submitted to arXiv
arXiv:2309.06180
Cite this paper · BibTeX

The citation identifies the linked source version. It cites the original paper and its authors.

@misc{transformerspagedattention2023,
  title = {{Efficient Memory Management for Large Language Model Serving with PagedAttention}},
  author = {Woosuk Kwon and Zhuohan Li and Siyuan Zhuang and Ying Sheng and Lianmin Zheng and Cody Hao Yu and Joseph E. Gonzalez and Hao Zhang and Ion Stoica},
  year = {2023},
  eprint = {2309.06180},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2309.06180}
}
On this page

On June 20, 2023, a team at Berkeley announced vLLM on their blog, opening with the claim that its throughput was up to 24 times higher than HuggingFace Transformers.

If you haven't worked with systems like this, here's a bit of background first. An LLM inference serving engine sits between the GPU and the users. It takes in prompts from many people at once, groups them into batches to send through the model, generates the answers one token at a time, and sends them back through an OpenAI-compatible API. The blog post says LMSYS's Chatbot Arena and Vicuna demo had been running on it since mid-April.

Three months later, the paper went up on arXiv, and the headline number became 2 to 4 times. The 24× was measured against a general-purpose model library; the 2–4× is against NVIDIA's FasterTransformer and 2022's Orca, two systems built specifically for inference serving. Both numbers hold under their own conditions; what the paper sets out to explain is where the extra throughput comes from.

The authors start from a measurement. In several existing systems they reimplemented, only 20.4% to 38.2% of the memory set aside for the KV cache actually held token data; the rest went to reservations, fragmentation and other uses.

Defining the problem

How big is the KV cache?

First, let's get the KV cache straight. A language model generates one token at a time. At each step, it compares the new token's query against the keys of all earlier positions, then uses the resulting weights to sum up the values. The keys and values of earlier positions never change once they are computed, so they are stored and read again at every later step. That data is the KV cache.

A request therefore has two phases. Prefill computes the whole prompt in one go and builds the prompt's KV; decode processes only one new token per step, adds its KV to the cache, and then generates the next token.

To show how big the KV cache gets, the paper works it out for OPT-13B. Each token stores one key vector and one value vector in every layer, each as long as the hidden dimension, 5120; the model has 40 layers; and each FP16 number takes 2 bytes:

2×5120×40×2=819,200 bytes2\times 5120\times 40\times 2=819{,}200\ \text{bytes}

That's about 800 KB. OPT can generate up to 2048 tokens, so a single request's KV cache can take up to 1.6 GB.

Now put it on a 40GB A100. OPT-13B's weights take 26 GB, about 65%; subtract the activations held temporarily during computation, and about 12 GB is left for the KV cache, enough for the KV of 15.7K tokens.

That space decides how many people can be served at once. Decode computes only one token per request per step, so the GPU spends most of its time moving weights out of memory; put many requests into one batch, and a single read of the weights serves the whole batch. Orca's iteration-level scheduling goes a step further. After every step, finished requests are moved out and new ones filled in, with no need to wait for the whole batch to finish. Once scheduling reaches this point, how big a batch can get comes down to whether the KV cache fits.

Holding seats for words not yet said

How do existing systems store the KV cache? Most deep learning frameworks require tensors to sit in contiguous memory, so FasterTransformer and Orca both prepare one whole contiguous region for each request. The trouble is that nobody knows how long an answer will be until it has been generated, so they have to allocate for the longest it could possibly be, for example 2048 tokens.

The paper divides the waste from this kind of allocation into three types. Take one request from the paper's example. Its length limit is 512, its prompt “You only live” has 3 tokens, the current step is generating “once,” and the next step will emit the end-of-sequence token <eos>:

  1. Reserved: the <eos> slot isn't used yet, but this request already holds it. This space will be used eventually; until then, no other request can have it.
  2. Internal fragmentation: the limit of 512 minus the 5 slots actually used leaves 507 slots that are never used from start to finish. Only when the request ends does the system learn that these slots were held for nothing.
  3. External fragmentation: requests have different limits, so the allocator (a buddy allocator, for example) carves out contiguous regions of different sizes, leaving gaps between requests that nobody fits into.

To see how much each type of waste accounts for, the authors tallied the average use of the KV cache region in the experiments of §6.2:

Original Figure 2: four stacked bars, with KV cache usage (%) on the vertical axis. Orca (Max): green token states 20.4, orange reserved 13.3, red internal fragmentation 57.3, gray external fragmentation and other 8.9. Orca (Pow2): 26.8, 17.9, 13.6, 41.6. Orca (Oracle): 38.2, 25.2, gray 36.6, with no red. vLLM: green 96.3, with only a thin sliver left at the top.
Original Figure 2, Kwon et al., from PDF page 2, CC BY 4.0.

Green is the part actually storing token states, orange is reserved, red is internal fragmentation, and gray is external fragmentation and other. All three Orca variants are the authors' own implementations, and they differ in how much space they reserve for the output:

  • Orca (Max): always reserves up to the model's maximum length, 2048.
  • Orca (Pow2): reserves at most twice what is needed; for example, if the actual output is 25 tokens, it reserves 32 slots.
  • Orca (Oracle): assumes the system knows in advance exactly how long each request's output will be and reserves just that much. This is impossible in practice and represents Orca's upper bound.

Orca (Max) has only 20.4% holding data, and more than half goes to internal fragmentation. Oracle knows the exact lengths, so the red disappears, yet it still uses only 38.2%; another 25.2% is seats held for future output, and 36.6% is external fragmentation and other. vLLM reaches 96.3%.

When reading this figure, watch the denominator. The percentages are of the KV cache region, not of the whole GPU. When the vLLM blog wrote that “existing systems waste 60% – 80% of memory,” someone on Hacker News asked (June 20, 2023) how 80% could possibly be wasted when the model weights obviously take up most of the GPU's memory. The blog meant the KV cache region; the person asking read it as the whole GPU.

We can verify one number while we're at it. A single A100 holds the KV of 15.7K tokens, and Orca (Max) needs a contiguous region of 2048 slots for every request:

15,700÷2048≈7.715{,}700\div 2048\approx 7.7

So it can serve at most 7 requests at once. In the average batch sizes the paper reports later, Orca (Max) comes out at exactly 7.00 on both datasets.

Besides the waste, contiguous allocation also rules out sharing. Coding assistants often sample several answers from the same prompt (parallel sampling), and machine translation often uses beam search to keep several candidates; these sequences share a long stretch of identical preceding text, whose KV could have been stored just once. Living in separate contiguous regions, each one has to store its own. In the paper's experiments, the prompt alone accounts for 12% of the total KV during parallel sampling.

Compaction could reclaim the fragments, but the KV cache is too large to shuffle around while serving, and preallocated whole regions still can't be shared.

So is there a way to let a request's KV cache be stored non-contiguously, allocated only when it's needed, and still shared between sequences?

Solving the problem

Borrowing paging from the operating system

Operating systems ran into the same thing long ago. Programs don't know how much memory they will use, and their needs vary in size; hand out contiguous physical memory directly, and it too breaks up into scattered pieces. Virtual memory divides memory into fixed-size pages. A program sees contiguous logical pages that actually map to physical pages scattered all over, with a page table translating between them; physical pages also don't need to be allocated up front, only when they are used.

vLLM carries this mapping over directly:

Table: the first three rows are the paper's analogy from §1; the page table to block table row is added by this note, based on §4.2.
Operating systemvLLM
PageKV block
ByteToken
ProcessRequest
Page tableBlock table

Each KV block holds the keys and values of a fixed number of tokens, BB, and vLLM defaults to B=16B=16. A request's KV cache is made up of a series of logical blocks, filled from left to right; on the GPU, a large pool of physical blocks is carved out in advance. Each row of the block table records which physical block a logical block maps to and how many of its slots are filled.

Attention, one block at a time

With the KV no longer contiguous, how is attention computed? PagedAttention groups the keys and values by block. Block jj is Kj=(k(j−1)B+1,…,kjB)K_j=(k_{(j-1)B+1},\dots,k_{jB}), and the same goes for VjV_j. Attention for the ii-th token is then computed block by block:

Aij=exp⁡(qi⊤Kj/d)∑t=1iexp⁡(qi⊤kt/d)A_{ij}=\frac{\exp\left(q_i^\top K_j/\sqrt{d}\right)}{\sum_{t=1}^{i}\exp\left(q_i^\top k_t/\sqrt{d}\right)} oi=∑j=1⌈i/B⌉VjAij⊤o_i=\sum_{j=1}^{\lceil i/B\rceil}V_jA_{ij}^\top

AijA_{ij} holds the attention scores of qiq_i for block jj's BB keys, a row vector of length BB; the denominator still sums over all earlier tokens, just as in an ordinary softmax. So the result is exactly the original attention, with no approximation at all; only the order in which the KV is read changes, going block by block. Each time the kernel processes a block, it looks up the physical block in the block table and loads its KjK_j and VjV_j; two neighboring blocks can sit far apart in memory.

The block table: following one request

Original Figure 6. On the left are request A's logical KV blocks: block 0 holds Four, score, and, seven; block 1 holds years, ago, our, fathers; block 2 holds brought. In the middle is the block table, whose three rows are, in order, physical block 7 with 4 slots filled; physical block 1 with 3 → 4 slots filled; and physical block 3 with 1 slot filled. On the right are physical KV blocks 0 to 8 on the GPU: Four score and seven are in block 7, years ago our fathers in block 1, and brought in block 3. The circled numbers 1, 2 and 3 next to the slots mark the step at which each one was written.
Original Figure 6, Kwon et al., from PDF page 6, CC BY 4.0.

Request A in the figure has the prompt “Four score and seven years ago our,” 7 tokens in all, with block size B=4B=4. The circled numbers are steps; let's follow them.

Step ①: prefill. 7 tokens need ⌈7/4⌉=2\lceil 7/4\rceil=2 logical blocks. vLLM takes two physical blocks from the free pool; this time it gets blocks 7 and 1, which are neither contiguous nor in order. Prefill uses ordinary attention to compute the prompt's KV and the first output token, “fathers.” The KV of the first 4 tokens goes into block 7 and that of the last 3 into block 1. The last slot of block 1 stays empty; it's the only reserved space in the entire request.

Step ②: the first decode step. The input to this step is “fathers.” PagedAttention reads blocks 7 and 1 to compute the next token, “brought”; the KV of “fathers” goes into the remaining slot of block 1, and the filled count in the block table goes from 3 to 4.

Step ③: the second decode step. The input is now “brought.” The last logical block is already full, so vLLM opens a new logical block 2, takes another physical block (block 3) from the free pool to map to it, and writes the KV of “brought” there.

Here's the block table after each step:

Table: compiled by this note from Figure 6 of the paper; each cell gives the physical block number, with the number of filled slots in parentheses.
Point in timeLogical 0Logical 1Logical 2
After ①7 (4)1 (3)–
After ②7 (4)1 (4)–
After ③7 (4)1 (4)3 (1)

Finding where a token lives from its position takes a single table lookup. The official code at v0.1.7 (released September 11, 2023, the day before the paper went up on arXiv) computes the write position for each new token in vllm/worker/worker.py:

Python
block_number = block_table[position // self.block_size]
block_offset = position % self.block_size
slot = block_number * self.block_size + block_offset

Positions are counted from 0. “brought” is at position 8; 8÷48 \div 4 rounded down is 2, and looking up block_table[2] gives physical block 3. 8 mod 4=08 \bmod 4 = 0, so it goes into the first slot of block 3, which is number 3×4+0=123\times 4+0=12 in the whole KV pool. Now try “ago.” It's at position 5, so logical block 1 and offset 1; the lookup gives physical block 1, and the slot number is 1×4+1=51\times 4+1=5. The attention kernel goes the other way. For each logical block it takes block_table[block_idx] to get the physical block number, loads that block's keys, and masks out slots beyond the sequence length.

How much can go to waste this way? Only the last logical block can be partly empty, so a sequence leaves at most B−1B-1 slots unused. With the default B=16B=16, that's at most 15 empty slots, whereas the earlier request held 507 for nothing. When a request finishes, all its blocks go back to the free pool; blocks from different requests sit interleaved in the same pool and don't need to be next to each other.

Block size involves a tradeoff too. The more tokens a block holds, the more positions the kernel can process in parallel at once; but the last block can also leave more slots empty, and there are fewer chances for sharing. We'll read the experimental results later.

Sharing one prompt: copy-on-write

Original Figure 8. On the left and right are the logical KV blocks of samples A1 and A2. Block 0 of both is Four score and seven, and block 1 of both is years ago our plus each sample's new token: fathers for A1 and mothers for A2. In the middle are physical KV blocks 0 to 8. Four score and seven is in block 7, and both samples point to it; years ago our mothers is in block 1, labeled Ref count: 2 → 1; a red arrow marked Copy-on-write runs from block 1 to block 3, which holds years ago our fathers and is pointed to by A1.
Original Figure 8, Kwon et al., from PDF page 7, CC BY 4.0.

In parallel sampling, samples A1 and A2 share the same prompt. Prefill runs only once, and logical blocks 0 and 1 of both sequences map to physical blocks 7 and 1. A physical block can be pointed to by several logical blocks, so vLLM keeps a reference count for each physical block; at this moment, blocks 7 and 1 both have a count of 2.

Then each sample draws its own next token. A1 gets “fathers” and A2 gets “mothers,” and both need to go into the last slot of logical block 1. A1 writes first. vLLM sees that block 1's reference count is greater than 1, so it allocates a new block 3, copies block 1's contents over for A1 to write into, and lowers block 1's count to 1. By the time A2 writes, the count is already 1, so it writes straight into block 1.

This is the copy-on-write that operating systems use when they fork a process. Everyone shares at first, a copy is made only when someone needs to write, and only the block being written gets copied. The prompt's other blocks exist as a single copy from start to finish. In the official code, this is handled by append_slot in block_manager.py (excerpt):

Python
# We want to append the token to the last physical block.
last_block = block_table[-1]
if last_block.ref_count == 1:
    # Not shared with other sequences. Appendable.
    return None
else:
    # The last block is shared with other sequences.
    # Copy on Write: Allocate a new block and copy the tokens.
    new_block = self.gpu_allocator.allocate()
    block_table[-1] = new_block
    self.gpu_allocator.free(last_block)
    return last_block.block_number, new_block.block_number

The free here only decrements the count; the block goes back to the free pool only when the count reaches 0. The returned (source, destination) block numbers are collected by the scheduler and handed over in batches to a dedicated copy kernel.

Beam search: a tree that gets pruned

Original Figure 9: block sharing with beam width 4. The four rows are beam candidates 0 to 3. Block 0 is shared by all four candidates; candidates 0 to 2 then share blocks 1 and 3 before splitting into blocks 5, 6 and 7; after block 0, candidate 3 goes through blocks 2, 4 and 8. Blocks 5, 2, 4 and 8 are crossed out. To the right of the dashed line are new blocks 9 to 12: block 6 leads to 9 and 10, and block 7 leads to 11 and 12.
Original Figure 9, Kwon et al., from PDF page 7, CC BY 4.0.

Sharing in beam search is more complicated, because who shares with whom keeps changing. In the figure the beam width is k=4k=4, and before the dashed line each candidate has filled 4 logical blocks. All four candidates share block 0, the prompt; candidate 3 branches off from the second block on, going through 2, 4 and 8; candidates 0 to 2 share 0, 1 and 3, and only split into 5, 6 and 7 at the fourth block.

Over the next few steps, the four most probable candidates all descend from the original candidates 1 and 2, and candidates 0 and 3 are eliminated. Their logical blocks are released and the counts of the corresponding physical blocks drop by one; blocks 2, 4, 5 and 8, whose counts reach 0, go back to the free pool, and the new candidates' KV is written into newly allocated blocks 9 to 12. Now all four candidates share 0, 1 and 3, candidates 0 and 1 share 6, and candidates 2 and 3 share 7.

In a system with contiguous allocation, the new candidate 3, which continues along old candidate 2's path, would first need its own copy of most of old candidate 2's KV. vLLM uses copy-on-write to move a block only when a new token lands in an old block that is still shared. It's much like the tree of processes that keeps forking in an operating system.

Shared prefixes and mixed decoding

Many services put a fixed set of instructions and examples in front of the user's input, namely a system prompt or few-shot examples. vLLM lets the service provider reserve a set of physical blocks for these prefixes in advance, much as an operating system lets multiple processes share the same library. A request carrying this prefix maps its leading logical blocks straight to the cached physical blocks, with the last block marked copy-on-write, so prefill only has to compute the user's own part of the input. In the paper, the prefixes are registered in advance by the service provider, not matched automatically by the system.

All the sharing relationships are hidden in the block table layer; the model and the kernels see only a list of physical block numbers for each sequence. That's why requests using greedy decoding, parallel sampling and beam search can be mixed in the same batch. In the implementation, these decoding methods are built from three operations: fork splits a new sequence off an existing one, append adds a token, and free deletes a sequence.

When memory runs out

With enough requests, physical blocks still run out. vLLM serves first-come, first-served (FCFS), and when it has to preempt, it sacrifices the most recently arrived requests first. Two questions follow. Which blocks get evicted, and how do they come back later?

When an operating system picks a page to evict, it has to guess which page will go unused for the longest. The LLM case is much simpler. All of a sequence's blocks are read together at every step, so vLLM either evicts all of a sequence's blocks or leaves them all alone. Multiple sequences within one request (such as beam search candidates) share blocks with one another, so they too are tied together as a group that leaves and returns together.

There are two ways to bring them back:

  • Swapping: move the blocks to CPU memory, managed by a separate CPU block allocator. As long as any sequence is swapped out, vLLM stops accepting new requests until the preempted sequences have all finished. The number of swapped-out blocks never exceeds the number of physical blocks on the GPU, so the swap space on the CPU side is bounded.
  • Recomputation: simply discard the KV and compute it again when the request is rescheduled. Recomputation can be much faster than the first generation, because the tokens already generated can be appended to the prompt as a new prompt, and a single prefill recomputes the KV for every position.

An operating system can't “recompute” a page of memory that has been swapped out; this option exists only in LLM inference. The paper supports both. The v0.1.7 code from the same time defaults to recomputation for requests with a single sequence, with a comment saying recomputation has lower overhead than swapping; multi-sequence requests (such as beam search) use swapping only because recomputation doesn't support them yet.

When a model is big enough to be split across several GPUs, vLLM uses Megatron-LM-style tensor parallelism, dividing the attention heads among the GPUs. There's only one KV cache manager, which lives in the central scheduler; at each step it broadcasts the token IDs together with the block table. Every GPU uses the same set of physical block numbers and stores only the KV for the heads it is responsible for.

What the kernels cost

With non-contiguous blocks, reading the KV adds a layer of indirection. The authors wrote three fused kernels to keep this overhead down:

  1. Write: each layer's newly computed KV is split into blocks, rearranged into a layout suited to block-wise reads, and written to the assigned positions according to the block table. The three tasks are fused into one kernel, saving several launches.
  2. Read plus attention: a rewrite of FasterTransformer's attention kernel that computes attention while reading the KV through the block table. One warp reads one block so that memory accesses can be coalesced, and sequences of different lengths in the same batch are supported.
  3. Copy: the blocks that copy-on-write has to move are scattered all over, and calling cudaMemcpyAsync for each one would turn into a pile of small transfers, so the authors fuse a batch of copies into a single kernel launch.
Original Figure 18 (a): attention kernel latency. The horizontal axis is context length, 64, 128 and 256; the vertical axis is latency (microseconds, 0 to 250). There are four lines, vLLM and FT each at batch size 8 (circles) and 32 (triangles). All four lines rise with length, and at the same batch size the blue vLLM line is always above the orange FT line; at batch size 32 and length 256, it's about 235 versus 195 microseconds.
Original Figure 18 (a), Kwon et al., from PDF page 12, CC BY 4.0.

Blue is vLLM and orange is FasterTransformer (FT); triangles are batch size 32 and circles batch size 8. The paper's text says vLLM's kernel is 20% to 26% slower than FasterTransformer's, a range that roughly matches the three batch-size-32 points. Reading the batch-size-8 points off the figure, the gap is roughly 25% to 45%; at context 64, for example, it's about 32 versus 22 microseconds. Also, the longest context measured is only 256 tokens.

The authors' view is that this overhead falls only on the attention computation, leaving the linear layers and other operations untouched, so end-to-end performance still leads FasterTransformer by a wide margin.

Discussion

Experimental setup

The models are OPT-13B, 66B and 175B and LLaMA-13B, running on A100 machines on Google Cloud. The three OPT configurations are:

Table: excerpt from Table 1 of the paper.
ModelGPUKV memoryTokens that fit
OPT-13B1×A100 40GB12 GB15.7K
OPT-66B4×A100 40GB21 GB9.7K
OPT-175B8×A100 80GB264 GB60.1K

The 66B row is especially tight. Once four GPUs have stored 132 GB of weights, only 21 GB is left for KV, which fits fewer tokens than 13B does on a single GPU. 175B is the opposite. Eight 80GB GPUs leave 264 GB, and as we'll see, that changes the picture.

The workloads are drawn from the length distributions of two datasets. ShareGPT consists of ChatGPT conversations shared by users, averaging 161 input tokens and 338 output tokens; Alpaca is instruction data generated by GPT-3.5, averaging 19 input and 58 output tokens. Neither has timestamps, so the authors generate request arrival times from a Poisson distribution and keep raising the request rate to see how far each system holds up. Traces generally run for one hour; 175B runs for only 15 minutes because of cost.

The metric is normalized latency, which divides each request's end-to-end latency by its output length and averages the result over all requests, in seconds per token. Once the request rate exceeds the system's capacity, the queue grows without bound and this number shoots up. When reading the plots, look at the request rate at which each curve turns upward.

There are two baselines:

  • FasterTransformer: NVIDIA's inference engine optimized for low latency, which has no scheduler of its own. The authors added a dynamic batching scheduler to it, with the batch limit set as high as memory allows.
  • Orca: not publicly available, so the authors implemented the three versions described earlier, assuming it uses a buddy allocator for the KV.

All three Orca variants schedule step by step, just like vLLM, so vLLM's lead over Orca mainly reflects the difference in memory management. In the paper's HN thread (September 14, 2023), someone asked whether the speedup actually came from scheduling; this comparison is what answers that question. Judging from PR #41, an unmerged PR from April 2023, the authors simulated Orca by swapping the block allocator of the same engine (then still called cacheflow) for a buddy allocator. As for the complete implementations of the three baselines, someone opened issue #1103 on September 19, 2023 asking to see them; no reply came from the authors, and the issue was closed on March 8, 2024 after three months without discussion (the only reply was a closing-as-stale notice).

Basic sampling

Original Figure 12: six small plots, all with normalized latency (s/token, 0 to 1) on the vertical axis and request rate (requests per second) on the horizontal axis. Top row, ShareGPT: (a) OPT-13B on one GPU, (b) OPT-66B on four GPUs, (c) OPT-175B on eight GPUs; bottom row, Alpaca: (d), (e) and (f) with the same three configurations. The five lines are, in order, gray FasterTransformer, red Orca (Max), orange Orca (Pow2), green Orca (Oracle) and blue vLLM. In every plot the curves start flat and then turn steep, with the blue line always the last to turn upward; in (f), the blue line sits close to the green and orange lines.
Original Figure 12, Kwon et al., from PDF page 10, CC BY 4.0.

The top row is ShareGPT and the bottom row Alpaca; from left to right are 13B, 66B and 175B.

On ShareGPT, vLLM sustains 1.7 to 2.7 times the request rate of Orca (Oracle) and 2.7 to 8 times that of Orca (Max), at similar latency; against FasterTransformer, the factor is up to 22. In (a), for example, Orca (Oracle) turns upward at about 1.1 requests per second, while vLLM holds out to nearly 2 per second.

Why? Look at how many requests are in a batch at the same time (OPT-13B):

Table: compiled from Figure 13 of the paper, average number of requests per batch; ShareGPT at 2 requests per second, Alpaca at 30 requests per second.
SystemShareGPTAlpaca
Orca (Max)7.007.00
Orca (Pow2)9.8143.24
Orca (Oracle)13.6272.75
vLLM30.42132.44

Orca (Max)'s 7.00 is the 7 we calculated earlier. On ShareGPT, vLLM serves 2.2 times as many concurrent requests as Orca (Oracle) and 4.3 times as many as Orca (Max), roughly in line with the throughput ratios.

The exception is (f). OPT-175B has 264 GB for KV, and Alpaca's sequences are short, so Orca (Oracle) and Pow2 can put together very large batches despite their waste. The bottleneck shifts to compute, and vLLM's advantage shrinks. This also marks out where PagedAttention applies. It only has something to save when memory fills up first.

Parallel sampling, beam search and shared prefixes

The authors measure the effect of sharing with OPT-13B on Alpaca. The more sequences sampled per request and the wider the beam, the further vLLM pulls ahead; its factor over Orca (Oracle) grows from 1.3× in basic sampling to 2.3× at beam width 6.

Memory savings are calculated as “blocks saved by sharing divided by total blocks without sharing”:

Table: compiled from §6.3 of the paper, OPT-13B; the Alpaca ranges correspond to 2, 4 and 6 samples or beam widths.
DecodingAlpacaShareGPT
Parallel sampling6.1%–9.8%16.2%–30.5%
Beam search37.6%–55.2%44.3%–66.3%

Parallel sampling shares only the prompt, while beam search can also share text generated partway through, so the latter saves much more. ShareGPT saves more than Alpaca with both methods, most likely because ShareGPT's inputs and outputs are much longer, which leaves more preceding text to share.

For shared prefixes, LLaMA-13B translates WMT16 English to German, with instructions plus translation examples placed in front of the input. With just 1 example (80 tokens), vLLM's throughput is 1.67 times that of Orca (Oracle); with 5 examples (341 tokens), the gap widens to 3.58 times.

For the chatbot scenario, ShareGPT conversation histories are joined with the latest question, the prompt is truncated to the last 1024 tokens, up to 1024 tokens are generated, and no KV is kept between turns. vLLM sustains 2 times the request rate of the three Orca variants. Here the three Orca variants perform about the same, because most prompts fill all 1024 tokens, and however the buddy allocator estimates the output length, it ends up reserving 1024 slots for the output.

Block size

Original Figure 18 (b): the horizontal axis is block size from 1 to 256 (in powers of 2), and the vertical axis is normalized latency (s/token). Blue ShareGPT stays near 0 for block sizes 16 to 128 and rises to about 1.3 at 256; orange Alpaca is lowest at 16 and 32, starts rising at 64, is about 4.8 at 128, and shoots up to about 18 at 256. Both lines sit around 2 to 3.6 for block sizes 1 to 4.
Original Figure 18 (b), Kwon et al., from PDF page 12, CC BY 4.0.

The authors fix the request rate and vary only the block size. When blocks are too small, the kernel can't make full use of the GPU's parallelism while reading KV, and latency is high for block sizes 1 to 4. ShareGPT does best between 16 and 128; Alpaca is fine at 16 and 32 but gets clearly worse beyond that, averaging around 18 seconds per token at 256, because many sequences are shorter than a single block. vLLM's default is therefore set at 16.

Swap or recompute?

Original Figure 19. (a) Microbenchmark: the horizontal axis is block size from 1 to 256, and the vertical axis is time (ms). Blue recompute stays roughly flat at 36 to 39 ms; orange swap in, green swap out and red swap in plus swap out all fall as blocks get larger, with the red line dropping from about 137 ms at block size 1 to about 33 ms at 256 and crossing the blue line around block size 16. (b) End to end: OPT-13B on ShareGPT, with normalized latency on the vertical axis. Blue recompute and red swap almost overlap for block sizes 16 to 64, both near 0; swapping is higher at block sizes 1 to 4, and recomputation is higher at block size 256.
Original Figure 19, Kwon et al., from PDF page 13, CC BY 4.0.

The left plot shows the overhead of the two recovery methods. The smaller the blocks, the slower swapping gets, because a pile of small transfers can't fill the PCIe bandwidth between CPU and GPU; at block size 1, swapping out plus in takes about 137 ms, while recomputation takes about 36 ms. Recomputation doesn't touch blocks, so its overhead stays roughly flat. Swapping is faster with large blocks, but even then recomputation is at most about 20% slower. The right plot is the end-to-end result for OPT-13B on ShareGPT; for block sizes 16 to 64, the two are almost identical.

The official code defaults to recomputation for single-sequence requests, which agrees with these numbers; at the default block size of 16, the two are about the same anyway.

Limitations and what came after

Section 8 of the paper draws its own boundaries. Paging helps LLM inference because memory demand isn't known in advance and performance is bound by memory capacity. In training, tensor shapes are mostly fixed, so allocation can be planned ahead; serving non-LLM models is usually compute-bound, so however much memory you save, it buys no speed, and an extra layer of indirection might even slow things down.

The vLLM team's replies on HN drew limits as well. vLLM targets throughput when GPU memory is full; it doesn't lower the minimum resources needed to run a model. When someone compared it with FlashAttention, the team answered that the two are basically orthogonal. FlashAttention reduces memory reads and writes, while PagedAttention reduces memory waste.

Criticism later came from the kernel side too. vAttention, in May 2024, pointed out that PagedAttention turns the KV from contiguous virtual memory into non-contiguous memory, so every attention kernel has to be rewritten to support paging, and the serving framework has to maintain its own memory management on top. Its authors instead rely on the demand paging support the underlying system already provides, keeping the KV contiguous in virtual addresses while physical memory is still allocated only when used. Besides vLLM, vAttention compares against the PagedAttention versions of the FlashAttention and FlashInfer kernels; in less than a year, block-based KV had become a format that kernels like FlashAttention and FlashInfer support as well.

The experiments themselves come with a few conditions to keep in mind. The models are all OPT and LLaMA with standard multi-head attention, and the paper doesn't measure GQA models, whose per-token KV is much smaller; the kernel overhead is measured only for contexts up to 256 tokens; the chatbot scenario doesn't keep KV across turns; and Orca is a version the authors simulated inside their own engine.

Conclusion

PagedAttention changes how the KV cache is allocated, from “each request first claims a whole contiguous region of maximum length” to “fixed-size blocks, allocated when needed, with positions translated by a block table.” Old operating-system tools like paging, copy-on-write and swapping each find a counterpart here. Fragmentation is held to less than one block, parallel sampling and beam search can share preceding text, and when memory runs short there's a choice between swapping out a whole group and recomputing it.

The evidence is fairly complete. Actual utilization of the KV region goes from 20.4%–38.2% up to 96.3%; with OPT-13B on ShareGPT, the number of concurrently served requests rises from Orca (Oracle)'s 13.62 to 30.42; and throughput is 1.7 to 2.7 times that of Orca (Oracle). The price is an attention kernel more than 20% slower than FasterTransformer's, and when compute becomes the bottleneck first (175B on Alpaca), the advantage shrinks to very little.

If you're deploying an LLM service, first find out where you're stuck. PagedAttention earns its keep when GPU memory is already full and the batch can't grow. A block size of 16 performs well on both of the paper's workloads, and services with long prompts, beam search or parallel sampling save the most memory from sharing. When you read throughput comparisons of other systems, also check who the baseline is and whether memory filled up first.

The source the paper cites for paging is Kilburn et al.'s “One-level storage system” from 1962. The idea had been around for sixty years when it turned out to fit the KV cache just right. The KV cache doesn't know in advance how big it will get, keeps growing along the way, and is thrown out all at once when it's done, the same temperament as the memory that processes used back then. The authors noticed this, and then brought copy-on-write and swapping along as well. The later vAttention disputes whether paging should be done by the serving framework itself or left to the underlying virtual memory; allocating the KV cache as it's used, instead of reserving one whole region, has become the starting point both sides share.