AI Logic

Attention Mechanisms

PagedAttention

Updated๏ผš

Structure of PagedAttention. The left side shows the computation when generating one token: from the new token's query, physical blocks are looked up in the block table, K and V are read block by block to compute scores, a softmax is taken over all blocks, and the weighted sum is output. The right side shows how the KV cache is laid out, with an example in which the logical blocks of requests A and B are mapped through block tables to scattered physical blocks in GPU memory.

What is PagedAttention?

PagedAttention is a way of computing attention that splits the KV cache used during text generation (the keys and values of past tokens) into fixed-size "blocks" so that attention can be computed while the blocks sit in non-contiguous locations in memory. Kwon et al. at UC Berkeley proposed it in 2023 in the paper "Efficient Memory Management for Large Language Model Serving with PagedAttention" (SOSP 2023) and released vLLM, an inference server built on it.

A large language model generates text one token at a time. Each step needs the keys and values of all past tokens, so they are stored in GPU memory to avoid recomputing them. This is the KV cache. The KV cache is very large: in the paper's example, the 13-billion-parameter OPT needs 800 KB per token and up to 1.6 GB for a single request.

Earlier inference servers placed each request's KV cache in contiguous memory and, since the output length is unknown in advance, reserved space for the maximum length (e.g., 2,048 tokens) up front. The paper measured that only 20.4โ€“38.2% of the reserved memory actually held token states.

PagedAttention brings in the idea of virtual memory and paging from operating systems.

OS virtual memoryPagedAttention / vLLM
PageKV block (keys and values for a fixed number of tokens)
ByteToken
ProcessRequest
Page tableBlock table (logical block โ†’ physical block)

As a bookshelf analogy: instead of emptying an entire shelf for one book (request), the pages are bound into files of a few sheets each and slotted into any free space on any shelf, with a table of contents (the block table) keeping track of their order.

In the figure at the top of the article, the right side shows how the KV cache is laid out, and the left side shows the attention computation when generating one token.

Theory

Block-wise attention: Let the block size (the number of tokens per block) be BB, the jj-th key block be Kj=(k(jโˆ’1)B+1,โ€ฆ,kjB)K_j = (k_{(j-1)B+1}, \dots, k_{jB}), and the value block be VjV_j. The attention of the ii-th token can be rewritten as a block-wise computation (Eq. (4) in the paper).

Aij=expโก(qiโŠคKj/d)โˆ‘t=1โŒˆi/BโŒ‰expโก(qiโŠคKt1/d),oi=โˆ‘j=1โŒˆi/BโŒ‰VjAijโŠคA_{ij} = \frac{\exp\bigl(q_i^\top K_j / \sqrt{d}\bigr)}{\sum_{t=1}^{\lceil i/B \rceil} \exp\bigl(q_i^\top K_t \mathbf{1} / \sqrt{d}\bigr)}, \qquad o_i = \sum_{j=1}^{\lceil i/B \rceil} V_j A_{ij}^\top

AijA_{ij} is the vector of weights for the tokens in the jj-th block (a row vector of length BB). The denominator sums over every token in every block, so the computed values are the same as in standard attention. The difference is that Kj,VjK_j, V_j may be anywhere in memory. The PagedAttention GPU program (kernel) computes while locating and reading the blocks one at a time.

Managing the KV cache: vLLM treats a request's KV cache as a sequence of "logical blocks" filled from left to right. GPU memory is divided in advance into "physical blocks" of the same size, and a block table records the mapping. Generating one request proceeds as follows (Figure 6 in the paper).

  1. Reserve only what the prompt needs: Space for the maximum length is not reserved. If the prompt has 7 tokens and B=4B = 4, two logical blocks are mapped to two free physical blocks (e.g., blocks 7 and 1).
  2. Write the prompt's KV cache: The first 4 tokens go into logical block 0 and the next 3 into logical block 1. The one remaining slot is left free for the next token.
  3. Generate the first token: PagedAttention reads physical blocks 7 and 1 to compute attention, and the new token's KV cache is written into the free slot of the last block. The "filled" count in the block table becomes 4.
  4. When a block is full, allocate one new block: For the second token, the last block is full, so a new physical block (e.g., block 3) is allocated and added to the block table.
  5. Release the blocks when generation finishes: The released blocks can be used for the KV cache of other requests.

Because blocks fill from left to right and a new block is allocated only when all previous blocks are full, the waste for a request is confined to its last block. And since all blocks are the same size, no gaps form between regions of different sizes (external fragmentation).

Saving memory by sharing blocks

Because reads go through the block table, the same physical block can be referenced by multiple sequences. The paper uses this to share memory in situations such as the following (Section 4.4).

  • Parallel sampling: When sampling multiple outputs from one prompt, all of the prompt's logical blocks are mapped to the same physical blocks. Each physical block keeps a count of how many sequences reference it (a reference count), and a block is copied only when a sequence writes to a shared block (copy-on-write). Only one block's worth is copied.
  • Beam search: Candidates share not only the prompt but also the blocks of their partial outputs. When a sequence drops out of the candidates, the reference counts of its blocks are decremented and blocks that reach 0 are freed. Earlier servers needed large copies of the KV cache every time the candidates changed.
  • Shared prefix (system prompt): When many requests start with the same instructions or examples, the physical blocks for that part are computed in advance and kept, and each request's logical blocks are mapped to them. Prompt computation is needed only for the part unique to each request.

When memory runs out: If generation progresses and no free physical blocks remain, vLLM follows a first-come-first-served policy and temporarily preempts the most recently arrived requests (Section 4.5 of the paper). The blocks of preempted requests are either moved together to CPU memory (swapping) or discarded and recomputed from the prompt and the already generated tokens when the request resumes (recomputation).

PagedAttention does not change the attention formula itself. What it changes is "where the KV cache is placed in memory and how it is found." It can therefore be used regardless of the model's attention type, such as multi-head attention or GQA, and the model's output stays the same.

Experimental results

Memory usage: In the paper's experiments (Section 6.2), the fraction of reserved KV cache memory that actually held token states was as follows (Figure 2 in the paper). The Orca baseline comes in three variants that differ in how much extra space they reserve for the output.

ServerHow space for the output is reservedFraction used for token states
Orca (Max)Always the maximum length (2,048 tokens)20.4%
Orca (Pow2)Up to 2ร— the actual length26.8%
Orca (Oracle)Knows the actual length in advance (an unachievable upper bound)38.2%
vLLMOne block at a time, as needed96.3%

Request throughput: OPT (13B, 66B, 175B) and LLaMA-13B were run on A100 GPUs, with requests generated from the input and output lengths of ShareGPT and Alpaca (Section 6.2 of the paper).

  • On ShareGPT requests, at similar latency, vLLM sustained request rates 1.7โ€“2.7ร— higher than Orca (Oracle), 2.7โ€“8ร— higher than Orca (Max), and up to 22ร— higher than FasterTransformer.
  • With OPT-13B, the number of requests processed concurrently was 2.2ร— that of Orca (Oracle) and 4.3ร— that of Orca (Max).
  • In the paper's summary, throughput was 2โ€“4ร— that of existing servers, and the gap grew with longer sequences, larger models, and more complex decoding methods.

Savings from sharing: For OPT-13B with Alpaca requests, the memory saved by sharing blocks was 6.1โ€“9.8% for parallel sampling and 37.6โ€“55.2% for beam search. On ShareGPT, the figures were 16.2โ€“30.5% and 44.3โ€“66.3%, respectively (Section 6.3 of the paper). For beam search with a beam width of 6, the improvement over Orca (Oracle) widened from 1.3ร— for basic sampling to 2.3ร—.

Practical considerations

PagedAttention improves how memory is used; it does not make the attention computation itself faster.

Looking up the block table and reading blocks from scattered locations makes the attention kernel alone slower. In the paper's measurements, the attention computation took 20โ€“26% longer than with the highly optimized FasterTransformer kernel (Section 7.1 of the paper). Even so, because many more requests can be processed at once, overall server throughput rises substantially. When memory is ample and many requests can already be processed at once (in the paper, OPT-175B with short Alpaca requests), the gap was smaller.

Keep the following points in mind when using it.

  • A block size of 16 is a good default: Too small and the GPU's parallelism goes unused; too large and the waste inside blocks grows and sharing becomes harder. In the paper, 16โ€“128 worked well for ShareGPT and 16โ€“32 for Alpaca, which has many short sequences; vLLM's default is 16 (Section 7.2).
  • Choose the preemption method by block size: Swapping small blocks involves many small transfers between CPU and GPU, which is slow. In the paper, recomputation was better for small blocks and swapping for large blocks (Section 7.3).
  • Use an inference server such as vLLM rather than implementing it yourself: PagedAttention pays off only when block table management, a scheduler, and a dedicated GPU kernel work together.

Comparison with other methods

Techniques for making attention cheaper are compared below by "what they reduce."

MethodWhat it reducesWhere it is usedComputed result
FlashAttention, FlashAttention-2HBM reads and writes during the attention computationTraining and inferenceSame
PagedAttention (Kwon et al., 2023)Wasted KV cache memory (fragmentation, over-reservation) and duplicationInference (especially servers handling many requests at once)Same
Multi-query attention, GQAThe size of the KV cache itself (K/V heads shared)InferenceModel changes
Multi-head Latent Attention (MLA)The size of the KV cache itself (K/V compressed into a low-dimensional latent vector)InferenceModel changes

PagedAttention is about "how the cache is laid out," so it can be combined with the other methods. Shrinking the cache with GQA or MLA and removing layout waste with PagedAttention lets the same GPU serve even more requests.

As a rough guide to choosing among them:

  • Building a server that generates text for many users: Use an inference server that uses PagedAttention (such as vLLM).
  • Speeding up training or inference on a single long sequence: Use FlashAttention-2.
  • Shrinking the KV cache itself: Choose GQA or MLA when designing the model.

PyTorch example

Show code
python
import torch


def paged_attention(q, k_cache, v_cache, block_table, seq_len, block_size):
    """PagedAttention for one sequence and one head (Eq. (4) of the paper; a small implementation for checking the mechanism).
    q: [d], k_cache/v_cache: [num physical blocks, block_size, d] (storage shared by all requests)
    block_table: logical block j -> physical block index, seq_len: current number of tokens"""
    d = q.shape[-1]
    n_blocks = (seq_len + block_size - 1) // block_size      # โŒˆi/BโŒ‰
    scores, values = [], []
    for j in range(n_blocks):
        phys = block_table[j]                                 # look up the physical block in the block table
        n = min(block_size, seq_len - j * block_size)         # last block: only the filled slots
        scores.append(k_cache[phys, :n] @ q / d ** 0.5)       # q_iแต€ K_j / โˆšd
        values.append(v_cache[phys, :n])
    a = torch.softmax(torch.cat(scores), dim=0)               # softmax over all blocks
    return a @ torch.cat(values)                              # o_i = ฮฃ_j V_j A_ijแต€


B, d, n_phys = 4, 64, 9
k_cache, v_cache = torch.randn(n_phys, B, d), torch.randn(n_phys, B, d)
block_table = [7, 1, 3]          # logical blocks 0, 1, 2 -> physical blocks 7, 1, 3 (need not be contiguous)
q = torch.randn(d)
out = paged_attention(q, k_cache, v_cache, block_table, seq_len=9, block_size=B)

# equals standard attention computed after rearranging into contiguous memory
k = torch.cat([k_cache[7], k_cache[1], k_cache[3, :1]])
v = torch.cat([v_cache[7], v_cache[1], v_cache[3, :1]])
print(torch.allclose(out, torch.softmax(k @ q / d ** 0.5, dim=0) @ v, atol=1e-6))  # True

# in practice, use an inference server such as vLLM (PagedAttention is used internally)
# from vllm import LLM, SamplingParams
# llm = LLM(model="facebook/opt-125m")
# outputs = llm.generate(["I am a cat."], SamplingParams(n=2, temperature=0.8))  # n=2: the prompt's blocks are shared

FAQ

Q. Does using PagedAttention change the model's output?
A.

No. The attention formula is the same as standard attention; only where the KV cache is stored and how it is read differ. The model does not need to be retrained either.

Q. How does it differ from FlashAttention?
A.

FlashAttention speeds up attention by reducing GPU memory reads and writes during the attention computation, and it is used for both training and inference. PagedAttention eliminates wasted memory by improving how the KV cache, which persists throughout generation at inference time, is laid out. Their goals differ, so they can be used together.

Q. What block size should be used?
A.

In the paper, 16 worked well in many situations, and vLLM's default is also 16. Too small and the GPU's parallelism goes unused; too large and the unused space in the last block grows and sharing becomes harder. Large blocks were especially disadvantageous when there were many short sequences.

References

  1. W. Kwon, Z. Li, S. Zhuang, Y. Sheng, L. Zheng, C. H. Yu, J. E. Gonzalez, H. Zhang, and I. Stoica, "Efficient Memory Management for Large Language Model Serving with PagedAttention," SOSP, 2023.
  2. vLLM (official repository)