# Efficient Memory Management for Large Language Model Serving with PagedAttention

Woosuk Kwon, Zhuohan Li, Siyuan Zhuang, Ying Sheng, Lianmin Zheng, Cody Hao Yu and 3 more · arXiv · 2023-9-12

- **Problem** Contiguous, maximum-length reservation of KV cache memory wastes GPU memory and blocks sharing, which caps how many requests fit in one batch.
- **Method** Splits each sequence's KV cache into fixed-size blocks mapped through per-request block tables, as virtual memory does, and copies a shared block only when a sharing sequence writes to it.
- **Results** Reached 2-4× serving throughput over FasterTransformer and Orca at the same latency level, in the authors' evaluations.

![Figure 2: Average percentage of memory wastes in different LLM serving systems during the experiment in §6.2](https://refivu.com/papers/a69a26aa-a470-4bff-9c73-2a7fe8ffd528/figures/figure-dbf8adaaa7e24cc465386e304d671f28.png?thumb=512)

**Figure 2** . Average percentage of memory wastes in different LLM serving systems during the experiment in §6.2.

[Original paper](https://arxiv.org/abs/2309.06180v1) · [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) · Woosuk Kwon, Zhuohan Li, Siyuan Zhuang, Ying Sheng, Lianmin Zheng, Cody Hao Yu, Joseph E. Gonzalez, Hao Zhang, Ion Stoica · Efficient Memory Management for Large Language Model Serving with PagedAttention · Original paper figure · Extracted the figure area from page 2 of the original PDF.

## Why KV cache memory caps batch size

Batch size sets serving throughput, and on an NVIDIA A100 40GB GPU a 13B-parameter model spends about 65% of memory on weights that stay fixed during serving. Close to 30% of the memory holds the dynamic request states, namely the key and value tensors of earlier tokens. Figure 1 lays out this split between parameters, KV cache and a small activation area.

Existing systems keep the KV cache of each request in one contiguous tensor, since the deep learning frameworks they rely on expect contiguous storage. Output length cannot be known in advance, so these systems reserve a chunk sized for the maximum length, such as 2048 tokens. That reservation produces internal fragmentation, external fragmentation between chunks of different sizes, and slots held for future tokens that stay idle.

Figure 2 reports how much of the KV cache memory each system wastes on average.

In the profiled existing systems, only 20.4% - 38.2% of KV cache memory held actual token states. Sharing is also blocked, because parallel sampling and beam search would let the sequences of one request reuse prompt cache, but separate contiguous spaces prevent that.

## PagedAttention and block tables

PagedAttention splits each sequence's KV cache into KV blocks, and each block holds the keys and values for a fixed number of tokens, denoted B. Those blocks can sit in non-contiguous physical memory, so the attention kernel fetches each block separately.

The block-wise form computes the output \\(o\_i\\) as the sum over blocks \\(j\\) from 1 to \\(\\lceil i/B \\rceil\\) of \\(V\_j A\_{ij}^\\top\\), where \\(A\_{ij}\\) holds the scores of query \\(q\_i\\) against the keys of block \\(j\\), normalized by the sum over the blocks up to \\(\\lceil i/B \\rceil\\). This is a regrouping of the usual self-attention over positions, computed one block at a time.

In the example, the query token "forth" is scored against the keys of "Four score and seven" in block 0, and the keys and values are spread across three blocks that are not contiguous in physical memory.

The KV cache manager borrows from operating system virtual memory: logical blocks map to physical blocks, and physical space is allocated when needed. Each request has a block table that records, for every logical block, its physical block and how many positions are filled. Separating logical and physical blocks lets the KV cache grow without reserving every position in advance.

## Allocating blocks while decoding

In the walkthrough, a 7-token prompt maps logical blocks 0 and 1 to physical blocks 7 and 1. The first 4 tokens fill logical block 0, the next 3 fill logical block 1, and one slot stays reserved for generation. The first decoding step writes its new KV cache into the open slot of the last block, and the second step allocates physical block 3 because the last block is full.

Each iteration first selects the sequences to batch and allocates physical blocks for the newly needed logical blocks. The input tokens of all requests in that iteration are then concatenated into one sequence and fed to the model.

Block size trades off two effects: more tokens per block let the kernel process more positions in parallel, while larger blocks increase fragmentation.

## Sharing blocks across sequences

In parallel sampling, the logical prompt blocks of every sample map to the same physical blocks, and each physical block carries a reference count. In the example, physical blocks 7 and 1 both have a reference count of 2.

When sample A1 writes to its last logical block, the shared physical block 1 has a count above 1, so vLLM allocates physical block 3, copies the data, and lowers the count to 1. Sample A2 then writes to physical block 1 directly, because its count is already 1. Sharing covers all blocks except the final, partly filled one, which is handled by copy-on-write.

Beam search keeps the top-k candidates out of k times the vocabulary size at each step. Beams share the prompt block and more blocks as they diverge, and when a candidate drops out, its blocks are freed once their reference counts reach zero. Earlier systems copy large parts of the KV cache between candidates, whereas here a copy is needed only when a newly generated token lands in an old shared block, and that copies one block.

Many requests begin with the same long system prompt, so the service can reserve physical blocks for such prefixes in advance and map each request onto them.

## Eviction, swapping and recomputation

When requests exceed capacity, vLLM serves them first come, first served and preempts the latest arrivals first. Since all blocks of a sequence are accessed together, eviction is all-or-nothing, and the sequences of one beam search request are preempted together.

Swapping copies evicted blocks to CPU memory, and the swap space on the CPU never exceeds the GPU space reserved for KV cache.

Recomputation rebuilds the KV cache of a rescheduled sequence by treating its generated tokens as part of a new prompt, which takes one prompt-phase iteration. The authors note that recomputation latency can be much lower than the original latency.

## Distributed KV cache management

vLLM supports Megatron-LM style tensor model parallelism, in which linear layers and attention heads are split across GPUs under SPMD execution. A single KV cache manager sits in the centralized scheduler and serves all workers, because each model shard processes the same input tokens and positions. Each worker stores only the KV cache for its own attention heads, while all workers use the same physical block IDs.

At each step the scheduler sends a control message with the input token IDs and the block table of each request. Workers synchronize their intermediate results with all-reduce and return the sampled tokens, and they do not synchronize on memory management.

## Throughput against FasterTransformer and Orca

The evaluation uses OPT models at 13B, 66B and 175B parameters and LLaMA at 13B, on A100 instances. Workloads are synthesized from ShareGPT and Alpaca with Poisson arrival times at several request rates. Baselines are FasterTransformer, with a custom dynamic batching scheduler, and three Orca variants that differ in how much output space they over-reserve.

Normalized latency is the main measure, and throughput is read as the highest request rate a system keeps at low normalized latency. Across evaluations the authors report 2-4× throughput at the same latency level compared with the state-of-the-art systems.

On ShareGPT, vLLM sustained 1.7×–2.7× higher request rates than Orca (Oracle) and 2.7×–8× higher than Orca (Max), while keeping similar latencies. Against FasterTransformer, the sustainable request rate reached up to 22× higher.

On Alpaca the trend is similar, but the advantage over Orca (Oracle) and Orca (Pow2) for OPT-175B is smaller. The authors attribute this to the large GPU memory left for KV cache and the short Alpaca sequences, which make those systems compute-bound rather than memory-bound.

## Gains from parallel sampling and beam search

Figure 14 compares parallel generation at parallel sizes 2, 4 and 6 and beam search at widths 2, 4 and 6, on OPT-13B with the Alpaca dataset. The authors state that more sampled sequences bring larger gains over the Orca baselines, and beam search, which shares more, brings the largest.

These savings were measured for OPT-13B serving the Alpaca trace.

On OPT-13B with Alpaca, the improvement of vLLM over Orca (Oracle) rises from 1.3× in basic sampling to 2.3× in beam search.

## Swapping versus recomputation by block size

The comparison covers block sizes from 1 to 256 and includes a microbenchmark of overhead and an end-to-end run of OPT-13B with ShareGPT traces at the same request rate.

Swapping has high overhead at small block sizes, which the authors attribute to many small CPU-GPU transfers that limit the effective PCIe bandwidth. Recomputation overhead stays constant across block sizes, since it does not use the KV blocks, and it never exceeds 20% of swapping latency.

Recomputation is more efficient for small blocks and swapping for large ones, and for medium block sizes from 16 to 64 the two perform comparably end to end.

## Limitations of the evaluation scope

The authors expect memory indirection and non-contiguous block memory to degrade compute-bound GPU workloads, such as serving DNNs that are not LLMs. They also note that DNN training has static tensor shapes, so memory can be planned ahead of time there.

Experiments cover OPT at 13B, 66B and 175B and LLaMA at 13B, with ShareGPT and Alpaca only. Most runs used 1-hour traces, while the OPT-175B runs used 15-minute traces because of cost.

Orca was not publicly available, so the authors implemented their own versions of it. Orca (Oracle) assumes knowledge of the true output lengths and is an upper bound that the authors consider infeasible in practice.

## Paper info

- **Authors**: Woosuk Kwon, Zhuohan Li, Siyuan Zhuang, Ying Sheng, Lianmin Zheng, Cody Hao Yu, Joseph E. Gonzalez, Hao Zhang, Ion Stoica
- **Venue**: arXiv · Preprint
- **First published**: 2023-9-12
- **Added**: 2026-10-20
- **Updated**: 2023-9-12
- **Version**: v1
- **arXiv**: 2309.06180
- **Category**: cs.LG · cs.DC
- **Original paper terms**: [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/)
- **What we show**: Paper info, commentary and permitted figures from the original paper

[Original paper ↗](https://arxiv.org/abs/2309.06180v1) · [PDF ↗](https://arxiv.org/pdf/2309.06180v1)

AI commentary is a separate explanation from the original paper and may contain errors. The original paper and figures follow each source's terms of use and any rights noted separately.

## Abstract

High throughput serving of large language models (LLMs) requires batching sufficiently many requests at a time. However, existing systems struggle because the key-value cache (KV cache) memory for each request is huge and grows and shrinks dynamically. When managed inefficiently, this memory can be significantly wasted by fragmentation and redundant duplication, limiting the batch size. To address this problem, we propose PagedAttention, an attention algorithm inspired by the classical virtual memory and paging techniques in operating systems. On top of it, we build vLLM, an LLM serving system that achieves (1) near-zero waste in KV cache memory and (2) flexible sharing of KV cache within and across requests to further reduce memory usage. Our evaluations show that vLLM improves the throughput of popular LLMs by 2-4$\\times$ with the same level of latency compared to the state-of-the-art systems, such as FasterTransformer and Orca. The improvement is more pronounced with longer sequences, larger models, and more complex decoding algorithms. vLLM's source code is publicly available at https://github.com/vllm-project/vllm

## Quote from the paper

Woosuk Kwon, Zhuohan Li, Siyuan Zhuang, Ying Sheng, Lianmin Zheng, Cody Hao Yu, Joseph E. Gonzalez, Hao Zhang, Ion Stoica (2023). Efficient Memory Management for Large Language Model Serving with PagedAttention. arXiv:2309.06180v1. https://arxiv.org/abs/2309.06180v1

**BibTeX**

```
@misc{kwon2023efficient,
  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.06180v1}
}
```

## Other paper commentary

- [Retentive Network: A Successor to Transformer for Large Language Models](https://refivu.com/en/papers/ca4ee5c6-87cf-427b-ae91-b593c10e0b48-retentive-network-a-successor-to-transformer-for-large.md)
- [OLMo: Accelerating the Science of Language Models](https://refivu.com/en/papers/674dc7cc-bbc8-47b3-a55b-69c562d96047-olmo-accelerating-the-science-of-language-models.md)
- [Tree of Thoughts: Deliberate Problem Solving with Large Language Models](https://refivu.com/en/papers/708b6d99-e4dc-4582-abc4-e2de5a72d5d3-tree-of-thoughts-deliberate-problem-solving-with-large.md)
- [Self-Instruct: Aligning Language Models with Self-Generated Instructions](https://refivu.com/en/papers/b7e9c5f5-b8d4-4382-9c03-d006766b8f88-self-instruct-aligning-language-models-with-self-generated.md)
- [DeepSeek-V3 Technical Report](https://refivu.com/en/papers/761895a4-08f3-446f-98de-60152a184c97-deepseek-v3-technical-report.md)
- [The Llama 3 Herd of Models](https://refivu.com/en/papers/27985e84-42ca-486e-8e0e-2fa739789ab4-the-llama-3-herd-of-models.md)
- [Mamba: Linear-Time Sequence Modeling with Selective State Spaces](https://refivu.com/en/papers/b149783d-1b22-47f2-94df-544d57bb2621-mamba-linear-time-sequence-modeling-with-selective-state.md)
- [Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification](https://refivu.com/en/papers/83083238-3fc6-4f4e-a3b1-6db4f84268de-delving-deep-into-rectifiers-surpassing-human-level.md)
- [Direct Preference Optimization: Your Language Model is Secretly a Reward Model](https://refivu.com/en/papers/b96eaaaa-8c14-4a06-93bf-d13e70a14b14-direct-preference-optimization-your-language-model-is.md)
- [GShard: Scaling Giant Models with Conditional Computation and Automatic Sharding](https://refivu.com/en/papers/2481fdbe-b100-433d-877a-6976f982ccaa-gshard-scaling-giant-models-with-conditional-computation-and.md)
- [GLUE: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding](https://refivu.com/en/papers/a5e0caad-afbf-4fa4-b072-f6f5cab0c916-glue-a-multi-task-benchmark-and-analysis-platform.md)
- [Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks](https://refivu.com/en/papers/569bb9ab-8345-4766-a539-e7ffb7b1754e-retrieval-augmented-generation-for-knowledge-intensive-nlp.md)

## Terms in this paper

- [Transformer](https://refivu.com/en/terms/48e8be2570bc-transformer)
- [self-attention](https://refivu.com/en/terms/426589b81077-self-attention)
- [beam search](https://refivu.com/en/terms/3e449f8f713b-beam-search)
- [Large Language Models](https://refivu.com/en/terms/f2404476b183-large-language-models)
- [vLLM](https://refivu.com/en/terms/fe3c96648564-vllm)
- [Alpaca](https://refivu.com/en/terms/acd615a4ec0a-alpaca)
- [KV cache](https://refivu.com/en/terms/cbf2f6d2bcc1-kv-cache)
- [Recomputation](https://refivu.com/en/terms/aad7a3f653a4-recomputation)
- [ShareGPT](https://refivu.com/en/terms/eec8a738c5eb-sharegpt)
- [normalized latency](https://refivu.com/en/terms/89bee2e06409-normalized-latency)

---

AI-written text can contain mistakes. [Refivu](https://refivu.com/en/papers/a69a26aa-a470-4bff-9c73-2a7fe8ffd528-efficient-memory-management-for-large-language-model-serving)
