12.2 PagedAttention (vLLM)
The previous section counted how much KV state a request needs. This section asks where that growing state lives. Even when the payload fits in aggregate, a serving engine can waste capacity by reserving space that requests never use or by leaving gaps that its allocator cannot reuse.
The PagedAttention paper studied these problems in the serving systems it evaluated in 2023 [1]. A contiguous cache that reserves each request’s maximum length is easy to address, but the final output length is unknown at admission. Reserving the maximum is one design choice, not a requirement of every inference backend.
PagedAttention borrows the separation between logical and physical memory from operating-system paging. A request sees its tokens in sequence order; a block table lets the attention kernel find their KV rows in non-contiguous storage. The gain comes from allocating and reusing blocks as requests grow and finish.
1. Count Reserved Space and Unusable Gaps
A contiguous allocation strategy can lose usable capacity in two ways:
- Unused reservation inside a request: suppose a request reserves 2,048 token slots, receives a 512-token prompt, and generates 20 tokens. It uses 532 slots and leaves 1,516 slots unused. Count the prompt as well as the output. Over-reservation for possible future tokens is distinct from padding waste in an allocator’s final block.
- External fragmentation: after requests finish, a contiguous allocator may have several free regions whose total size is sufficient but whose largest individual region cannot hold a new request. Whether this happens depends on the allocator and its compaction strategy.
The original vLLM release reports that 60%–80% of KV-cache memory was wasted in the existing systems it analyzed [2]. That historical observation motivates the design; it is not a measured waste rate for every current engine or workload.
2. The OS Inspiration: Paging and Block Tables
In modern Operating Systems, physical RAM is not allocated to applications in large, contiguous chunks. Instead, memory is divided into fixed-size “pages.” The application sees a contiguous logical memory space, but the OS maps this to non-contiguous physical pages using a Page Table.
PagedAttention applies this exact paradigm to the KV cache:
- Logical Blocks: The sequence of tokens in a user’s request is divided into logical blocks (e.g., 16 tokens per block).
- Physical Blocks: The GPU VRAM is pre-divided into a massive pool of fixed-size physical blocks.
- Block Table: A mapping table tracks which physical block corresponds to which logical block for a given request.
When a request begins, the engine only allocates enough physical blocks to hold the initial prompt. As the model generates new tokens autoregressively, the system allocates new physical blocks on demand.
Within the fixed-size KV block pool, any free block is reusable, avoiding external fragmentation there. This does not describe all GPU allocations. Internal waste in final blocks depends on block size and the request-length distribution.
Interactive PagedAttention Simulation
The following component starts with two requests. Generate tokens to see when crossing a block boundary requires another physical block. Free one request, then grow the remaining request to observe reuse of the released blocks.
PagedAttention Memory Allocator
Logical View (Requests)
Physical VRAM (Blocks)
3. Which five values does the query actually read?
Use the diagram’s initial request A. Each block holds four tokens. A has five tokens and the block table [0, 2]. Physical block 1 belongs to request B.
| Logical token position | Physical block | Slot within block | Value |
|---|---|---|---|
| 0, 1, 2, 3 | 0 | 0, 1, 2, 3 | 1, 2, 3, 4 |
| 4 | 2 | 0 | 101 |
For token position and block size , first read the block ID at in A’s table, then take slot in that physical block. Stop after position 4. There are three more slots in A’s second block, but the request has no tokens there yet.
Set the query and keys to zero. All five scores are equal, so the answer is the mean of the values, . If the second block entry is missing, averaging the first four values gives a plausible 2.5 for the wrong sequence. Check that the table covers the stated context length before computing attention. In a fixed-width table, only the entries needed for that length are active.
Scope of the CPU example. The script reads one nonempty request with one decode query, a Python list of block IDs and precomputed keys and values. It gathers rows into ordinary PyTorch tensors to check against an independent dense reference. The original paged kernel reads the blocks directly. The example omits allocation, concurrent writes, shared-block ownership, GPU scheduling and kernel performance [1].
Download the CPU PyTorch example (paged_attention.py)
Read the address calculation and the three invalid-table checks
"""Trace one decode query through a KV block table. Run with CPU PyTorch.
Foundation Model Engineering, section 12.2
English: https://sungeuns.github.io/foundation-model-engineering/chapter-12/paged-attention-vllm/#paged-kv-addresses
Korean: https://sungeuns.github.io/foundation-model-engineering/ko/chapter-12/paged-attention-vllm/#paged-kv-addresses
"""
import torch
from torch.nn.functional import scaled_dot_product_attention
def gather_kv(pool, block_table, length):
"""pool: [blocks, slots, 2 (K and V), heads, head_dim]. One nonempty request."""
block_count, block_size = pool.shape[:2]
if length < 1:
raise ValueError("the query needs at least one valid key")
needed = (length + block_size - 1) // block_size
if len(block_table) < needed:
raise ValueError(f"{length} tokens need {needed} block entries")
active = block_table[:needed] # unused capacity in a wider table is allowed
if any(type(b) is not int or not 0 <= b < block_count for b in active):
raise ValueError("active table entry is not a valid physical block ID")
positions = torch.arange(length, device=pool.device)
blocks = torch.tensor(active, device=pool.device)[positions // block_size]
rows = pool[blocks, positions % block_size]
keys, values = rows.unbind(dim=1)
# [length, heads, head_dim] -> [1, heads, length, head_dim]
return keys.transpose(0, 1).unsqueeze(0), values.transpose(0, 1).unsqueeze(0)
def main():
# Same initial mapping as request A in the diagram. Block 1 is not ours.
pool = torch.zeros(3, 4, 2, 1, 1, dtype=torch.float64)
pool[:, :, 1, 0, 0] = torch.tensor([
[1, 2, 3, 4], [900, 900, 900, 900], [101, 700, 700, 700]
])
query = torch.zeros(1, 1, 1, 1, dtype=pool.dtype)
table = [0, 2]
keys, values = gather_kv(pool, table, 5)
dense_values = torch.tensor([1, 2, 3, 4, 101], dtype=pool.dtype).view(1, 1, 5, 1)
torch.testing.assert_close(values, dense_values) # checks logical token order
dense = scaled_dot_product_attention(query, torch.zeros_like(dense_values), dense_values)
paged = scaled_dot_product_attention(query, keys, values)
torch.testing.assert_close(paged, dense)
assert abs(paged.item() - 22.2) < 1e-10
# These three tail slots and the unused table suffix do not belong to the prefix.
pool[2, 1:, 1] = 9999
keys, values = gather_kv(pool, table + [-1], 5)
torch.testing.assert_close(scaled_dot_product_attention(query, keys, values), dense)
for invalid in ([0], [0, -1], [0, 3]):
try:
gather_kv(pool, invalid, 5)
except ValueError:
continue
raise AssertionError(f"accepted invalid active block table {invalid}")
print(f"Five logical values: {dense_values.flatten().tolist()}")
print(f"Dense and paged result: {paged.item():.1f}")
if __name__ == "__main__":
main() Run python paged_attention.py with CPU PyTorch. It checks the five values in logical order and the attention result. Raising every unused tail value leaves the result at 22.2. A missing entry, a negative active ID and an ID outside the pool each raise an error. An unused suffix in a wider table is ignored.
4. Advanced Memory Management: Copy-on-Write (CoW)
Separating logical blocks from physical storage also lets multiple requests reference the same immutable prefix blocks.
Consider Parallel Sampling or Beam Search, where a single prompt is passed to the model, and the model generates multiple different candidate responses simultaneously. An implementation that copies the full cache for each candidate duplicates their shared prompt; reference-counted blocks can avoid those copies.
With PagedAttention, vLLM implements Copy-on-Write (CoW):
- All candidate sequences share the exact same logical-to-physical block mapping for the prompt. The physical blocks simply maintain a reference count.
- As the sequences begin generating new tokens, they share the physical blocks until a sequence diverges.
- When a sequence needs to write a new token to a shared block, the system detects the reference count is , allocates a new physical block, copies the shared data, and updates that specific sequence’s Block Table.
The 2023 vLLM release reports up to 55% lower memory use from sharing in its parallel-sampling and beam-search experiments [2]. The gain depends on how much prefix remains shared, the number of candidates, and block occupancy.
5. Reading a case study: benchmark throughput versus deployment cost
The 2023 vLLM release reports up to 24× HF and 3.5× TGI throughput in tests using ShareGPT input/output lengths, LLaMA-7B on A10G and LLaMA-13B on A100 40GB. These are configuration-specific laboratory results. Separately, it reports a 50% reduction in GPUs used by the LMSYS deployment. That does not establish a 50% reduction in all operating costs or unchanged TTFT for every request. [2]
For adoption, match model, lengths, concurrency, precision and completion count, then compare throughput, TTFT, inter-token latency, failures and total cost together.
6. Summary and Open Questions
Paged allocation makes free blocks reusable within the KV pool and supports prefix sharing. It still leaves tail-block waste, metadata, kernel workspaces, and finite cache capacity. Evaluate those costs under the actual request-length distribution instead of treating paging as a promise that every allocation or latency problem disappears.
However, as we efficiently pack more requests into a batch, we encounter a new problem: Scheduling. If Request A generates 10 tokens and Request B generates 1,000 tokens, how do we efficiently swap requests in and out of the GPU without stalling the entire batch? This leads us directly to the concept of Continuous Batching, which we will explore in the next section.
Quizzes
Quiz 1: How does PagedAttention specifically resolve the issue of External Fragmentation in the KV Cache?
External fragmentation occurs when free memory is split into small, non-contiguous chunks that cannot accommodate a large contiguous allocation. Because PagedAttention allocates memory in fixed-size, non-contiguous physical blocks and maps them logically via a Block Table, any free physical block can be utilized by any request, regardless of where it resides in VRAM. This avoids external fragmentation inside the fixed-size KV block pool; it does not cover unrelated GPU allocations.
Quiz 2: How much tail waste remains with block size B?
Fewer than B token slots per sequence can be unused. With B=16 and length 3, thirteen slots are empty, so fractional overhead can be large. Aggregate overhead depends on length distribution and block size.
Quiz 3: Why is the Copy-on-Write (CoW) mechanism particularly advantageous for Beam Search decoding?
In Beam Search, multiple candidate sequences share the exact same initial prompt and often share early generated tokens before diverging. CoW allows all these sequences to map to the same physical memory blocks for the shared context. A write to a shared partial block requires a private copy; a write past a full block requires a new block. This can save memory compared with copying the entire history for every candidate.
Quiz 4: Does PagedAttention guarantee bitwise-identical logits?
It computes the same attention in exact arithmetic with a different storage layout. Kernel and operation-order changes can alter finite-precision results. Verify numerical tolerances and generation quality rather than assuming bitwise equality.
Quiz 5: With blocks of four slots, how many bytes go unused for independent requests of lengths 4, 5 and 8?
Only the five-token request leaves a partial final block, so three slots are unused. If one token takes bytes, the batch wastes bytes. In general request of length wastes bytes for block size . Sum over requests with no sharing or extra reservation. If lengths modulo are uniformly distributed, expected waste is per request.
Quiz 6: A five-token query returns 2.5 instead of 22.2 in the example. Which two things should you check?
Check that the table supplies two active entries and that the fifth position maps to block 2, slot 0. A one-block read silently drops the value 101 and averages the first four values.
References
- Kwon, W., Li, Z., Zhuang, S., Sheng, Y., Zheng, L., Yu, C. H., … & Stoica, I. (2023). “Efficient Memory Management for Large Language Model Serving with PagedAttention”. Proceedings of the 29th Symposium on Operating Systems Principles (SOSP). arXiv:2309.06180
- Kwon & Li (2023). vLLM release and benchmark methodology. Historical result; accessed 2026-11-15.