Paper notes

vLLM and PagedAttention: Managing the KV Cache Like Paged Memory

The vLLM paper (SOSP 2023) brings operating-system paging to the KV cache: fixed-size blocks, on-demand allocation, a block table, copy-on-write sharing. This post checks the paper's numbers and shows the real range behind the headline 2-4x, what it was compared with, and where it stops applying.

Published Updated 29 min read

On this page
  1. Why this paper matters
  2. What the paper contributes
  3. Background: the memory budget and three kinds of waste
  4. How big is the KV cache of one token
  5. Contiguous reservation: where the waste comes from
  6. Method: bringing paging to the KV cache
  7. PagedAttention: attention over a blocked KV cache
  8. The KV cache manager: logical blocks, physical blocks and the block table
  9. Sharing and copy-on-write
  10. Scheduling and preemption
  11. Distributed execution and implementation
  12. Recompute it yourself: do the paper’s numbers add up?
  13. Table 1: how many token positions fit in the KV cache memory
  14. Reserving the maximum length: a 13B fits only 7 requests
  15. Fig. 2: the waste shares, and what paging leaves
  16. Why OPT-175B on Alpaca is the exception
  17. What about today’s models
  18. Experiments: against whom, and what was measured
  19. Experimental setup
  20. Overview of the results
  21. Ablations: kernel overhead, block size, swapping versus recomputation
  22. Limits and what to keep in mind
  23. What to take away from this paper
  24. Further reading
  25. FAQ

Why this paper matters

The vLLM paper (Kwon et al., SOSP 2023) answers a very concrete question: the GPU is powerful, so why does the throughput of LLM serving stay low? Its answer is that the number of requests processed at the same time is capped by the memory the KV cache occupies, and the serving systems of the time reserved one contiguous block of memory per request, so that, as the paper measured, only 20.4%-38.2% of the KV cache memory actually held token states.

PagedAttention borrows paging from operating systems: the KV cache is cut into fixed-size blocks that are logically contiguous but physically scattered, allocated on demand and mapped through a block table. The vLLM serving system built on top of it keeps 96.3% of the KV cache memory filled with real token states and lets blocks be shared between sequences. The paper reports 2-4x higher throughput than FasterTransformer and Orca at the same latency, without affecting the model’s output.

This post does three things: it explains the method; it recomputes every number in the paper that can be recomputed (see “Recompute it yourself”); and it points out what the headline figures were measured against, so that “2-4x” is not mistaken for a universal result. Five numbers to remember first:

NumberMeaningSource
20.4%-38.2%Share of the KV cache that holds token states in existing systemsFig. 2
96.3%The same share in vLLM; the other 3.7% is wasteFig. 2
2-4xThroughput gain “at the same latency” in the abstract; the multipliers stated in the body range from 1.3x to 22xAbstract, section 6
16Default block size, 16 tokens per blockSection 7.2
20-26%How much slower paging makes the attention kernel (against the FasterTransformer kernel)Section 7.1

What the paper contributes

The paper lists four contributions:

  1. It identifies the challenges of memory allocation in LLM serving and quantifies their effect on performance.
  2. It proposes PagedAttention, an attention algorithm that works on a KV cache stored in non-contiguous paged memory.
  3. It designs and implements vLLM, a distributed LLM serving engine built on PagedAttention.
  4. It evaluates vLLM in several scenarios and shows that it clearly outperforms FasterTransformer and Orca.

One premise is easy to overlook: vLLM changes neither the model nor its output; it changes only where the KV cache lives and how it is allocated. In the paper’s words, it works “without affecting the model accuracy at all”, which makes it a different kind of optimization from quantization or distillation, which give up a little accuracy.

Background: the memory budget and three kinds of waste

How big is the KV cache of one token

During autoregressive generation the model stores K and V for every request, every layer and every token it has already processed. For a multi-head attention model, the KV cache of one token takes

bytestoken=2×d×L×b\text{bytes}_{\text{token}} = 2 \times d \times L \times b

bytes, where 22 stands for one K and one V, dd is the hidden size, LL the number of layers and bb the bytes per number (2 for FP16). The paper’s example is OPT-13B: 2×5120×40×2=819,2002 \times 5120 \times 40 \times 2 = 819{,}200 bytes, which the paper writes as 800 KB (it is 800 KiB). OPT can generate up to 2,048 tokens, so the KV cache of one request can reach 1.6 GB (the exact value is 1.5625 GiB, see the check below).

On a 40 GB A100, the parameters of a 13B model take 26 GB (65%), Fig. 1 of the paper marks the KV cache as “more than 30%”, and the rest is activations and other temporary tensors. Table 1 of the paper gives 12 GB of KV cache memory, enough for at most 15.7K token positions (KV slots). So how many requests can run together is decided almost entirely by how much KV cache each request occupies, which the paper describes as serving throughput being memory-bound. It adds a trend argument: from the A100 to the H100, FLOPS grow by more than 2x while GPU memory stays at 80 GB at most, so memory will matter more and more.

Contiguous reservation: where the waste comes from

Most deep learning frameworks require tensors to be contiguous, so earlier serving systems (FasterTransformer, Orca) kept the KV cache of a request in one contiguous chunk of memory. The output length is unknown in advance, so they could only reserve for the longest length a request might reach (for example 2,048 tokens). The paper sorts the resulting waste into three kinds:

WasteHow it arisesPure waste?
ReservationSlots held in advance for tokens that will only be generated laterNo, they are eventually used, but no other request can use them while this one runs
Internal fragmentationThe reservation is for the maximum length, the real length is shorter, and the surplus is never usedYes, you only learn how much once the request finishes
External fragmentationThe reserved size differs per request and the allocator (for example a buddy allocator) leaves scattered gapsYes, it is known at allocation time that no token will ever use it
Four systems compared: existing systems store real token states in only 20.4%-38.2% of the KV cache, vLLM in 96.3%. Stacked bar chart with data from Fig. 2 of the paper. Orca (Max): token states 20.4%, reservation 13.3%, internal fragmentation 57.3%, external fragmentation and others 8.9%. Orca (Pow2): 26.8%, 17.9%, 13.6%, 41.6%. Orca (Oracle): 38.2%, 25.2%, no internal fragmentation, 36.6%. vLLM: token states 96.3%, and the remaining 3.7% is not itemized in the paper's figure. Share of the KV cache that actually holds token states Token states Reservation Internal frag. External frag. & others Rest (3.7%, not itemized) 0% 20% 40% 60% 80% 100% Orca (Max) 20.4 13.3 57.3 8.9 Orca (Pow2) 26.8 17.9 13.6 41.6 Orca (Oracle) 38.2 25.2 36.6 vLLM 96.3
Data from Fig. 2 of the paper (average shares measured in the experiment of its section 6.2), redrawn here from the numbers printed on the figure. The Orca (Oracle) bar has no internal-fragmentation segment; the 3.7% at the right end of the vLLM bar are a few thin slivers in the paper's figure and are not itemized.

The numbers come from the paper’s experiment in section 6.2. Orca (Max), Orca (Pow2) and Orca (Oracle) are three versions of Orca that the authors implemented, differing in how much space they reserve for the output (see “Experimental setup” below). Existing systems hold token states in only 20.4%-38.2% of the space, so 61.8%-79.6% is wasted, reservation included.

Contiguous allocation has two more drawbacks. One is compaction: defragmenting is possible in principle, but moving a huge KV cache around in a performance-sensitive serving system is impractical. The other is that nothing can be shared: parallel sampling and beam search produce several outputs from one prompt, and part of their KV cache could be shared, but each sequence keeps its cache in its own contiguous space. The paper’s figures are that in its parallel-sampling experiment the prompt part is 12% of the total KV cache, and that beam search can save up to 55% (the scope of that figure is explained below).

Overall the paper reduces the challenges to three: the KV cache is large; decoding algorithms are getting more complex and need sharing; and input and output lengths are unknown in advance, so scheduling is needed, including deleting or swapping out the cache of some requests when memory runs out.

Method: bringing paging to the KV cache

The paper’s analogy is direct: blocks are pages, tokens are bytes, and requests are processes.

PagedAttention: attention over a blocked KV cache

Let BB be the block size. The keys and values of the first ii positions are cut into blocks of BB positions, block jj being Kj=(k(j−1)B+1,…,kjB)K_j = (k_{(j-1)B+1}, \ldots, k_{jB}) and VjV_j, and attention is computed block by block:

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

Here AijA_{ij} is the row vector of attention scores of query qiq_i on block jj (length BB), and 1\mathbf{1} is the all-ones vector that adds up the BB scores of one block. This is the same computation as standard attention, with the sum over positions regrouped. The kernel fetches one block at a time: it multiplies qiq_i with the KjK_j of the block to get the scores, then multiplies the scores with the VjV_j of the block and accumulates the output. The blocks need not be adjacent in physical memory.

The KV cache manager: logical blocks, physical blocks and the block table

vLLM uses a centralized scheduler to coordinate GPU workers spread over several GPUs, and the KV cache manager manages the physical KV cache of those workers in a paged fashion (including CPU memory used for swapping). It sees the KV cache of a request as a series of logical blocks that are filled from left to right; the unfilled positions of the last logical block are reserved for the tokens to come. On a GPU the block engine allocates one large contiguous chunk of memory and divides it into physical blocks, and the block table records, for every logical block, which physical block holds it and how many positions are filled.

Block table: contiguous logically, scattered physically Three-column schematic. The left column shows the three logical KV blocks of request A: block 0 holds Four score and seven, block 1 holds years ago our fathers, block 2 holds brought and has only one slot filled. The middle column is the block table: logical block 0 maps to physical block 7 with 4 filled, logical block 1 to physical block 1 with 4 filled, logical block 2 to physical block 3 with 1 filled. The right column shows nine physical blocks in GPU memory; only blocks 7, 1 and 3 belong to request A, the others belong to other requests or are free, and they need not be adjacent. Block table: contiguous logically, scattered physically Logical KV blocks (request A) Block table Physical KV blocks (GPU memory) Logical 0 Four score and seven Logical 1 years ago our fathers Logical 2 brought logical physical # filled 0 → 7 4 1 → 1 4 2 → 3 1 Block 0 other/free Block 1 logical 1 Block 2 other/free Block 3 logical 2 Block 4 other/free Block 5 other/free Block 6 other/free Block 7 logical 0 Block 8 other/free Same colour = same logical block (0 maps to 7, 1 to 1, 2 to 3 in physical numbering). Grey blocks belong to other requests or are free (schematic); they need not be adjacent.
The example of Fig. 6 in the paper: block size 4, the prompt Four score and seven years ago our has 7 tokens. Prefill allocates only two physical blocks (7 and 1) and logical block 1 keeps one free slot; in the first decoding step the new token fills that slot and the filled count goes from 3 to 4; in the second decoding step block 1 is full, so physical block 3 is allocated and the block table gains a row. The figure shows the state after those two steps.

Two properties decide how little is wasted. First, a physical block is allocated only after all previous blocks are full, so, as the paper puts it, vLLM confines the waste of a request to within one block; with block size 16 that is at most 15 empty positions. Second, all blocks have the same size, so external fragmentation cannot occur, and when a request finishes its blocks are immediately freed for other requests.

Sharing and copy-on-write

A request may produce several sequences, and different sequences have a lot of prefix in common. vLLM keeps a reference count for every physical block; when several sequences point to the same physical block, the one that has to write first copies the block into a private one, which is copy-on-write, the same thing an operating system does when it forks a process.

Parallel sampling (one prompt, several samples at once): in the prompt phase the KV of the prompt is stored once and the logical blocks of both sequences map to the same physical blocks; in the generation phase the two samples draw different tokens and need their own storage. The example of Fig. 8 in the paper (two samples A1 and A2, block size 4):

StageA1 blocks 0 / 1A2 blocks 0 / 1Block 7Block 1Block 3
Prompt phase7 / 17 / 1refcount 2refcount 2free
A1 writes logical block 17 / 37 / 1refcount 2refcount 2 → 1newly allocated, copied from block 1
A2 writes logical block 17 / 37 / 1refcount 2refcount is already 1, written directlybelongs to A1 only

The numbers in the A1 and A2 columns are the physical blocks that hold the sequence’s logical blocks 0 and 1. The KV of the prompt is therefore almost entirely shared, and only the last logical block has to be copied.

Beam search: at every step it keeps the kk best-scoring candidate sequences, and the candidates share not only the prompt but also other prefix blocks, a sharing pattern that changes dynamically as the search goes on, like a tree of processes that keep forking. In the example of Fig. 9 in the paper (k=4k = 4) all four candidates share the first block (the prompt); candidate 3 diverges from the second block on; candidates 0-2 share the first three blocks and diverge at the fourth; in the next round the four best candidates all descend from candidates 1 and 2, the blocks that only candidates 0 and 3 used (physical blocks 2, 4, 5 and 8) drop to a reference count of zero and are freed, and new blocks (9-12) are allocated for the new candidates. Earlier systems had to copy large parts of the KV cache between candidates; in vLLM most blocks are simply shared and copy-on-write applies only at write time.

Shared prefix (many requests begin with the same system prompt or few-shot examples): the provider can reserve physical blocks for a set of predefined prefixes, like operating systems letting several processes share one shared library; a request that carries the prefix maps its logical blocks to the cached physical blocks (the last block marked copy-on-write), and the prompt phase only has to compute the user’s own input.

Mixed decoding: vLLM translates logical blocks to physical blocks through one common mapping layer, so the model and the kernels see only a list of physical block IDs per sequence and do not care how sequences share. The paper therefore argues that requests with different sampling preferences can be placed in the same batch, which existing systems can hardly do efficiently.

Scheduling and preemption

When there are too many requests, vLLM uses first-come-first-served (FCFS): the earliest requests are served first and the latest are preempted first. When the physical blocks run out, two classic questions must be answered: which blocks to evict, and how to recover them when needed.

  • Eviction: all or nothing. All blocks of a sequence are accessed together, so either all blocks of a sequence are evicted or none. The sequences of one request (for example the candidates of a beam search) can share memory, so they form a sequence group that is preempted and rescheduled together.
  • Recovery 1: swapping. The evicted blocks are copied to CPU memory and brought back when needed; for this vLLM has a CPU block allocator next to the GPU block allocator. Once a preemption has happened, vLLM stops accepting new requests until the preempted sequences have finished, so the swap space on the CPU never exceeds the total number of KV blocks on the GPU.
  • Recovery 2: recomputation. When a preempted sequence is rescheduled, the tokens it has already generated are appended to the original prompt and treated as a new prompt, so one prefill pass produces the KV of all positions together, which can be much faster than the time it originally took to generate them.

The trade-off between the two is measured in section 7.3 of the paper, see below.

Distributed execution and implementation

vLLM supports Megatron-LM style tensor parallelism: linear layers are split for block-wise matrix multiplication, GPUs synchronize intermediate results with all-reduce, and attention is split by heads, each worker taking care of a subset of the heads. Every shard processes the same input tokens and therefore needs the KV cache of the same positions, so the centralized scheduler holds a single KV cache manager that all workers share, together with the mapping from logical to physical blocks; every worker has the same physical block IDs but stores only the part of the cache for its own heads. In each step the scheduler broadcasts the input token IDs and the block table of every request to the workers, the workers run the model and synchronize with all-reduce, and finally they send the sampled tokens back to the scheduler, so workers do not have to synchronize for memory management.

On the implementation side vLLM has a FastAPI frontend that extends the OpenAI API interface and a GPU inference engine of about 8.5K lines of Python and 2K lines of C++/CUDA: the scheduler and block manager are in Python, key operators such as PagedAttention are custom CUDA kernels, model execution builds on PyTorch and Transformers, and NCCL handles tensor communication. The paper describes three kernel optimizations: fusing the reshape of the KV and the block write into one kernel; fusing block read and attention, with one warp reading one block and support for variable sequence lengths in a batch (adapted from the FasterTransformer attention kernel); and batching the scattered copies triggered by copy-on-write into one kernel launch. All decoding algorithms are built from three methods: fork, append and free.

Recompute it yourself: do the paper’s numbers add up?

Several groups of numbers in the paper can be checked with a formula or simple arithmetic. The script below does so: the numbers are copied from Table 1, Fig. 2, Fig. 11 and Fig. 13 of the paper, and it needs no third-party packages and runs as is in Python 3.

Table 1: how many token positions fit in the KV cache memory

# Numbers copied from the paper's Table 1 (KV cache memory, KV slots);
# model shapes come from the OPT paper.
GIB = 2**30
OPT = {  # hidden size, layers, Table 1 KV memory (GB), Table 1 KV slots
    "OPT-13B": (5120, 40, 12, 15.7e3),
    "OPT-66B": (9216, 64, 21, 9.7e3),
    "OPT-175B": (12288, 96, 264, 60.1e3),
}
print(f"{'model':<9}{'B/token':>10}{'KiB':>6}{'ours':>9}{'paper':>8}")
for name, (d, layers, kv_gb, paper) in OPT.items():
    per_token = 2 * d * layers * 2  # one K and one V, 2 bytes per FP16 number
    slots = kv_gb * GIB / per_token
    print(f"{name:<9}{per_token:>10,}{per_token // 1024:>6}"
          f"{slots / 1e3:>8.1f}K{paper / 1e3:>7.1f}K")

Output:

model       B/token   KiB     ours   paper
OPT-13B     819,200   800    15.7K   15.7K
OPT-66B   2,359,296  2304     9.6K    9.7K
OPT-175B  4,718,592  4608    60.1K   60.1K

OPT-13B and OPT-175B match exactly. For OPT-66B I get 9.6K where the paper says 9.7K, 1% apart; I suspect that Table 1 gives the KV cache memory only in whole GB (a true 21.3 GB would match), but the paper does not say. More worth noticing is the unit: the paper’s “GB” is really GiB, because with 1000-based units 12 GB holds only 14.6K positions, not 15.7K.

Reserving the maximum length: a 13B fits only 7 requests

print()
# Reserve the 2048-token maximum: how many requests fit in the 13B's
# KV memory?
per_token, slots, max_len = 819_200, 15.7e3, 2048
print(f"one 2048-slot request: {per_token * max_len / GIB} GiB")
n = int(slots // max_len)
print(f"max-length reservation: {n} requests "
      f"({n * max_len / slots:.0%} of the slots)")
# Fig. 13: average number of requests batched together, OPT-13B
BATCH = {
    "ShareGPT": {"Orca (Max)": 7.00, "Orca (Pow2)": 9.81,
                 "Orca (Oracle)": 13.62, "vLLM": 30.42},
    "Alpaca": {"Orca (Max)": 7.00, "Orca (Pow2)": 43.24,
               "Orca (Oracle)": 72.75, "vLLM": 132.44},
}
for data, row in BATCH.items():
    ratios = [f"{k}: {row['vLLM'] / v:.1f}x" for k, v in row.items()
              if k != "vLLM"]
    print(f"{data:<9}vLLM vs", " | ".join(ratios))

Output:

one 2048-slot request: 1.5625 GiB
max-length reservation: 7 requests (91% of the slots)
ShareGPT vLLM vs Orca (Max): 4.3x | Orca (Pow2): 3.1x | Orca (Oracle): 2.2x
Alpaca   vLLM vs Orca (Max): 18.9x | Orca (Pow2): 3.1x | Orca (Oracle): 1.8x

A request reserved at 2,048 takes 1.5625 GiB (the paper writes 1.6 GB), so the KV memory of the 13B model holds only ⌊15.7K/2048⌋=7\lfloor 15.7\text{K} / 2048 \rfloor = 7 requests, filling 91% of the positions. That matches the average batch size of Orca (Max) in Fig. 13 of the paper, which is 7.00 on both ShareGPT and Alpaca. The reason is that Orca (Max) always reserves the maximum length whatever the real length of a request, so its batch size is set by “memory divided by 2,048” alone and does not depend on the dataset; I found this correspondence while checking, and the paper does not state it. The ratios of the vLLM batch size to those of the Orca versions on ShareGPT are 2.2x (Oracle) and 4.3x (Max), as in the paper’s text.

Fig. 2: the waste shares, and what paging leaves

print()
# Fig. 2: the parts of each bar, and waste = 100 minus token states
FIG2 = {  # token states, reservation, internal frag., external frag. & others
    # (Oracle has no internal-fragmentation segment)
    "Orca (Max)": (20.4, 13.3, 57.3, 8.9),
    "Orca (Pow2)": (26.8, 17.9, 13.6, 41.6),
    "Orca (Oracle)": (38.2, 25.2, 36.6),
}
for name, parts in FIG2.items():
    print(f"{name:<14}sum {sum(parts):5.1f}  waste {100 - parts[0]:.1f}%")
print(f"{'vLLM':<14}token states 96.3  waste {100 - 96.3:.1f}%")
# Rough estimate: with paging a sequence wastes about (B-1)/2 slots, the
# unfilled part of its last block
B = 16
mean_len = 161.31 + 337.99  # Fig. 11: ShareGPT mean input + mean output
print(f"mean ShareGPT length {mean_len:.1f}; B={B}: "
      f"~{(B - 1) / 2} slots = {(B - 1) / 2 / mean_len:.1%} per request")
print(f"reserve {max_len}: wastes {max_len - mean_len:.0f} slots "
      f"= {(max_len - mean_len) / max_len:.1%} of the reservation")
print(f"ShareGPT / Alpaca: input {161.31 / 19.31:.1f}x, "
      f"output {337.99 / 58.45:.1f}x")

Output:

Orca (Max)    sum  99.9  waste 79.6%
Orca (Pow2)   sum  99.9  waste 73.2%
Orca (Oracle) sum 100.0  waste 61.8%
vLLM          token states 96.3  waste 3.7%
mean ShareGPT length 499.3; B=16: ~7.5 slots = 1.5% per request
reserve 2048: wastes 1549 slots = 75.6% of the reservation
ShareGPT / Alpaca: input 8.4x, output 5.8x

The numbers on each bar of Fig. 2 add up to 99.9%, 99.9% and 100.0% (the figure rounds), and the “20.4%-38.2%” of the text agrees with the figure. The waste after paging can be estimated roughly: the last block of every sequence has on average (B−1)/2(B-1)/2 unfilled positions, which is 7.5 positions for B=16B=16, about 1.5% of the mean ShareGPT length of 499.3 tokens. Reserving 2,048 wastes 75.6% (by final length); the 79.6% of Orca (Max) in Fig. 2 is higher because it is an average over time, and requests that are still generating have not reached their final length. These estimates are my own calculation, not numbers from the paper: the 3.7% of vLLM contains other sources of waste that the paper does not itemize, so 1.5% must not be read as a result of the paper.

Why OPT-175B on Alpaca is the exception

print()
# By mean length: how many requests fit in Table 1's KV slots (an ideal
# value, with no reservation or fragmentation)
MEAN = {"ShareGPT": 161.31 + 337.99, "Alpaca": 19.31 + 58.45}  # Fig. 11
SLOTS = {"OPT-13B": 15.7e3, "OPT-66B": 9.7e3, "OPT-175B": 60.1e3}  # Table 1
print(f"{'':<10}" + "".join(f"{d:>10}" for d in MEAN))
for model, slots in SLOTS.items():
    fit = [f"{slots / m:>10.0f}" for m in MEAN.values()]
    print(f"{model:<10}" + "".join(fit))

Output:

            ShareGPT    Alpaca
OPT-13B           31       202
OPT-66B           19       125
OPT-175B         120       773

This table is an ideal value: by mean length, how many requests the KV cache memory can hold at most, with no reservation or fragmentation. OPT-175B on Alpaca holds 773 requests, far more than will ever be in flight, and the paper says that in this setup (Fig. 12f) Orca (Oracle) and Orca (Pow2) can also batch a large number of requests, performance becomes compute-bound instead of memory-bound, and the advantage of vLLM is small. By contrast, OPT-66B on ShareGPT holds only 19 requests, so the quality of memory management directly decides the throughput.

What about today’s models

print()
# Today's models: KV bytes per token (FP16) and how many tokens the same
# 12 GiB holds
# layers, KV heads, head dim (from this site's src/data/llm-configs.ts)
MODELS = {
    "OPT-13B": (40, 40, 128),
    "Llama 2 7B": (32, 32, 128),
    "Llama 3 8B": (32, 8, 128),
    "Qwen2.5 7B": (28, 4, 128),
    "Llama 3 70B": (80, 8, 128),
}
for name, (layers, kv_heads, head_dim) in MODELS.items():
    per_token = 2 * layers * kv_heads * head_dim * 2
    print(f"{name:<12}{per_token // 1024:>4} KiB/token"
          f"{12 * GIB / per_token / 1e3:>8.1f}K slots in 12 GiB")

Output:

OPT-13B      800 KiB/token    15.7K slots in 12 GiB
Llama 2 7B   512 KiB/token    24.6K slots in 12 GiB
Llama 3 8B   128 KiB/token    98.3K slots in 12 GiB
Qwen2.5 7B    56 KiB/token   224.7K slots in 12 GiB
Llama 3 70B  320 KiB/token    39.3K slots in 12 GiB

The paper’s models use multi-head attention and so have a large KV cache per token; with a GQA model the same 12 GiB holds many more token positions (Llama 3 8B holds 6.25 times as many as OPT-13B). That does not make paging unimportant, since concurrency and context length keep growing, but it shows that the multipliers in the paper come from a setup in which the KV cache is unusually tight and cannot be carried over to other models as they are. For GQA and related techniques see efficient attention.

Experiments: against whom, and what was measured

Experimental setup

ItemThe paper’s setup
ModelsOPT 13B, 66B and 175B, and LLaMA 13B
HardwareGoogle Cloud A2 instances (NVIDIA A100): 1 A100-40GB for 13B, 4 A100 (160 GB in total) for 66B, 8 A100-80GB (640 GB in total) for 175B
WorkloadRequests synthesized from the real input and output lengths of ShareGPT and Alpaca, with Poisson arrival times; ShareGPT averages 161.31 input and 337.99 output tokens, Alpaca 19.31 and 58.45
MetricNormalized latency: the end-to-end latency of each request divided by its output length, averaged; a high-throughput system should keep it low at high request rates
DurationOne-hour traces for most experiments, 15 minutes for OPT-175B because of cost

There are two opponents, and neither is the original:

  • FasterTransformer: a distributed inference engine optimized for latency. It has no scheduler of its own, so the authors wrote a dynamic-batching scheduler similar to Triton and set the maximum batch size BB as large as the GPU memory allows.
  • Orca: an LLM serving system optimized for throughput. Orca is not public, so the authors implemented their own version and assumed it allocates KV cache addresses with a buddy allocator. Three versions differ in how much output space they reserve: Orca (Oracle) assumes the system knows how long each request will actually generate, which is an upper bound that cannot be reached in practice; Orca (Pow2) over-reserves by at most 2x (a true output length of 25 reserves 32 positions); Orca (Max) always reserves up to the model’s maximum sequence length of 2,048 tokens.

Overview of the results

ExperimentModel and dataCompared withThe paper’s result
Basic samplingOPT, ShareGPTOrca (Oracle)1.7-2.7x higher sustainable request rate
Basic samplingOPT, ShareGPTOrca (Max)2.7-8x higher
Basic samplingOPT, ShareGPTFasterTransformerUp to 22x higher
Requests batched togetherOPT-13B, ShareGPT, 2 requests/sOrca (Oracle) and (Max)2.2x and 4.3x (30.42 against 13.62 and 7.00 requests)
Parallel sampling and beam searchOPT-13B, AlpacaOrca (Oracle)1.3x for basic sampling, 2.3x for beam search of width 6
Shared prefixLLaMA-13B, WMT16 English-German translationOrca (Oracle)1.67x for a one-example prefix (80 tokens), 3.58x for a five-example prefix (341 tokens)
ChatbotOPT-13B, ShareGPT conversationsThree Orca versions2x higher sustainable request rate

The shape of the basic-sampling curves is worth a remark: at low request rates normalized latency rises slowly, and once the rate exceeds what the system can handle, the queue grows without bound and latency suddenly explodes. That is why “how high a request rate it can sustain” is the way to compare throughput. On Alpaca the trend is similar, the one exception being OPT-175B analysed above.

With parallel sampling and beam search, the more is shared, the larger vLLM’s advantage. The paper also measured the memory saved by sharing (blocks saved divided by the total number of blocks without sharing):

SettingDatasetMemory saved
Parallel sampling (2-6 samples)Alpaca6.1%-9.8%
Parallel sampling (2-6 samples)ShareGPT16.2%-30.5%
Beam search (width 2-6)Alpaca37.6%-55.2%
Beam search (width 2-6)ShareGPT44.3%-66.3%

Note the scope: the earlier text (section 3) says beam search saves “up to 55%”, which is the Alpaca ceiling; on ShareGPT it reaches 66.3%.

In the chatbot workload the paper concatenates the conversation history with the last user query as the prompt, cuts it to the last 1,024 tokens, generates at most 1,024 tokens, and does not keep the KV cache between conversation rounds. ShareGPT has many long conversations, so most prompts are exactly 1,024 tokens, and because of the buddy allocator the Orca baselines reserve 1,024 positions for the output however they predict its length, so the three Orca versions behave alike, and vLLM sustains a 2x higher request rate than all of them.

Ablations: kernel overhead, block size, swapping versus recomputation

  • Kernel overhead. Paging has to look up the block table, execute extra branches and handle variable sequence lengths, so the attention kernel is 20-26% slower than the highly optimized FasterTransformer implementation. The paper considers the overhead small because it affects only the attention operator, not linear layers or other operators, and end to end vLLM still clearly leads.
  • Block size. With blocks too small the GPU’s parallelism is not used; with blocks too large internal fragmentation grows and sharing opportunities shrink. On ShareGPT block sizes from 16 to 128 work best; on Alpaca 16 and 32 work well and larger blocks, being longer than the sequences, degrade performance clearly. 16 is the default.
  • Swapping versus recomputation. With small block sizes swapping moves many small pieces between CPU and GPU, cannot use the PCIe bandwidth and is expensive; the cost of recomputation does not depend on the block size because it does not use KV blocks. Recomputation is therefore better for small blocks and swapping for large ones, although the overhead of recomputation is never higher than 20% of the latency of swapping. For block sizes from 16 to 64 the two have comparable end-to-end performance.

Limits and what to keep in mind

Look at the opponent before the multiplier

The paper’s 2-4x was measured against opponents the authors implemented themselves, on two fixed length distributions and on A100s. Reading it as “vLLM is 2-4x faster in any scenario” over-interprets it.

  1. The opponents are the authors’ own implementations. Orca is not public, its three versions differ only in how much output space they reserve, and a buddy allocator is assumed; Orca (Oracle) assumes known output lengths and is an upper bound that cannot be reached in practice; the scheduler of FasterTransformer was also written by the authors. The multipliers reflect “Orca and FasterTransformer as implemented under these assumptions”, not the original systems.
  2. It measures throughput. The metric is normalized latency, which shows how high a request rate a system can sustain; metrics such as time to first token or tail latency are not reported separately.
  3. The requests are synthetic. Lengths follow the real distributions of ShareGPT and Alpaca and arrivals are a Poisson process, but this is not real production traffic.
  4. The gain depends on being memory-bound. The paper’s own exception (OPT-175B on Alpaca) and its discussion section both say so: in DNN training, where tensor shapes are fixed, or in non-LLM serving that is compute-bound, non-contiguous blocks can even slow things down because of the extra memory indirection.
  5. The models are from 2023. All experiments use multi-head attention models and none uses a KV-compressing structure such as GQA or MLA; the check above shows that this directly changes how tight the KV cache is.
  6. It covers the 2023 design only. Since the paper, vLLM and similar systems have added many features not discussed here; see the official documentation and the page on continuous batching and PagedAttention on this site.

Two more details inside the paper are worth checking: “GB” is really GiB, and “beam search saves up to 55%” holds only for Alpaca. They do not affect the conclusions, but you need the right scope when quoting a specific number.

What to take away from this paper

  1. The bottleneck is memory capacity, not compute. The batch size is roughly the KV cache memory divided by what each request occupies; make each request occupy less and more requests fit.
  2. Paging confines the waste to the last block and makes sharing possible. Fixed-size blocks remove external fragmentation, on-demand allocation shrinks reservation and internal fragmentation, and reference counts with copy-on-write let parallel sampling, beam search and shared prefixes save memory.
  3. The cost is small, but not zero. The attention kernel is 20-26% slower in exchange for larger batches; whether that pays off depends on being memory-bound.
  4. Look at the opponent before the multiplier. 2-4x is a summary, the multipliers in the body run from 1.3x to 22x, the opponents are the authors’ implementations, and the same setup on a GQA model has a less tight KV cache, so the gain differs.
  5. It complements continuous batching. In the paper’s words, the iteration-level scheduling of Orca lets more requests run in parallel by scheduling, while vLLM fits the working sets of more requests into memory by raising memory utilization. They solve problems at different levels, and modern inference engines use both.

Further reading

FAQ

What is the core idea of PagedAttention?
Cut the KV cache of every sequence into fixed-size blocks (16 tokens by default in vLLM), keep them logically contiguous but let them sit anywhere in GPU memory, and record in a block table which physical block holds each logical block and how many positions are filled. A new block is allocated only when the previous one is full, so the waste of a request is confined to its last block, external fragmentation disappears, and blocks can be shared between sequences and copied on write.
How much higher is vLLM's throughput than other systems?
The abstract says 2-4x at the same latency, which is a summary; the body of the paper gives a wider range. On ShareGPT vLLM sustains 1.7-2.7x higher request rates than Orca (Oracle), 2.7-8x higher than Orca (Max) and up to 22x higher than FasterTransformer. On Alpaca with OPT-13B the gain over Orca (Oracle) is only about 1.3x for basic sampling and grows to 2.3x for beam search of width 6; shared-prefix translation gives 1.67x and 3.58x, and the chatbot workload 2x. Orca is not public, so the comparison is against three versions the authors implemented themselves.
Does PagedAttention slow down the attention computation?
Yes, by a modest amount. Looking up the block table, executing extra branches and handling variable sequence lengths make the attention kernel 20-26% slower than a highly optimized FasterTransformer kernel. That affects only the attention operator, not linear layers or other operators, and the paper's conclusion is that vLLM still clearly wins end to end, because better memory use lets it process more requests at once.
Why is the default block size in vLLM 16?
A block that is too small cannot use the GPU's parallelism when reading and processing the KV cache; a block that is too large increases internal fragmentation and reduces the chance of sharing. The paper tested block sizes on ShareGPT and Alpaca: on ShareGPT 16 to 128 were all best, on Alpaca only 16 and 32 did well because larger blocks are longer than the sequences themselves. 16 is large enough to use the GPU and small enough to avoid noticeable internal fragmentation.
Do the paper's multipliers still hold for today's GQA models?
The paper tests only OPT and LLaMA-13B (multi-head attention; OPT-13B needs 800 KiB of KV cache per token) and no model that compresses the KV cache, such as GQA or MLA. In FP16, Llama 3 8B needs only 128 KiB per token, so the same 12 GiB holds about 98 thousand token positions, 6.25 times as many as for OPT-13B. The KV cache is less tight, so the absolute cost of reservation and fragmentation falls, but more concurrency and longer contexts still make it a bottleneck; measure the multiplier on your own model and workload.