Mental model
A modern LLM inference engine is a memory-aware runtime pipeline linking an asynchronous front-end (AsyncLLM), a continuous-batching scheduler, a virtualized KV-cache block manager (KVCacheManager), and GPU model runners. By mapping logical token blocks onto non-contiguous physical VRAM frames via PagedAttention and reusing shared prefixes through radix trees, the engine eliminates external KV fragmentation and maximizes concurrent decode batch size.
Learning outcomes
- Trace how
AsyncLLM, the V1 scheduler,KVCacheManager, and model runners coordinate continuous iteration-level batching. - Explain how PagedAttention virtual-to-physical block tables eliminate external memory fragmentation and bound internal waste below one block.
- Describe how radix-tree Automatic Prefix Caching (APC) and copy-on-write reference counting share KV blocks across system prompts and parallel beam decoding.
- Contrast eager PyTorch prefill execution against captured CUDA Graphs during memory-bandwidth-bound decode steps.
Theory
Naive static batching pads every sequence in a batch to the longest prompt plus maximum generation limit and reserves contiguous VRAM slabs upfront. Because actual generation lengths vary unpredictably, contiguous reservation wastes 60% to 80% of KV-cache memory to internal reservation slack and external memory holes between freed slabs, capping batch concurrency and starving GPU tensor cores during memory-bound autoregressive decoding.
In vLLM's V1 architecture, AsyncLLM ingests incoming requests asynchronously and dispatches them into the core scheduler loop. At every engine step, the scheduler packs waiting prefill chunks and active decode tokens under token and physical KV-block budgets, while KVCacheManager allocates fixed-size pages of tokens (typically or \$32$).
PagedAttention Block Tables & Fragmentation Math
Each sequence maintains a logical-to-physical block table mapping logical block index to any free physical VRAM block frame . Because physical blocks need not be contiguous, external fragmentation drops strictly to zero, and internal waste is bounded solely to the partial tail block (on average tokens per sequence):
Here, is transformer layer count, is KV head count (under GQA/MQA), is head dimension, is bytes per element (2 for FP16/BF16, 1 for FP8), and the factor of 2 accounts for both Key and Value tensors.
Consider serving a 70B GQA model (, , ) in FP16 () with block size tokens on an 80 GB GPU where 48 GB remains free for KV cache after weights:
- Per-token KV footprint:
2 * 80 * 8 * 128 * 2 = 327,680 bytes = 320 KiB/token. - Per-block () footprint:
16 * 320 KiB = 5,120 KiB = 5.0 MiB/block. - Total physical blocks in 48 GB (49,152 MiB):
49,152 / 5.0 = 9,830physical blocks (157,280 token slots). - Under naive contiguous pre-allocation for
max_model_len = 8192(512 blocks/request), VRAM accommodates at most9,830 / 512 = 19concurrent requests—even if average requests use only 1,000 tokens (63 blocks). With PagedAttention allocating blocks on demand,9,830 / 63fits roughly 156 concurrent sequences simultaneously (8.2x higher concurrency), wasting at most 15 tail tokens (4.7 MiB) per sequence.
KV-Cache Block Allocator (Paged vs Contiguous)
Radix-Tree Prefix Caching & Copy-on-Write Sharing
When requests share common system prompts, few-shot examples, or multi-turn histories, KVCacheManager hashes each full block of tokens chained with its preceding prefix hash (block_hash = hash(parent_hash, token_ids_in_block)). Matching blocks stay pinned in a free-but-cached LRU eviction structure (forming a prefix tree / radix trie): incoming prompts hit cached physical blocks without recomputing prefill attention, incrementing each block's reference counter (ref_count += 1).
For beam search or parallel n > 1 sampling branches diverging from one shared prompt, all child sequences point to identical physical blocks with ref_count > 1. Only when a branch writes a new token into a partially filled shared block (ref_count > 1) does the engine perform Copy-on-Write (CoW): allocating one fresh physical block, copying the shared prefix tokens inside that single page, and decrementing the old block's ref_count.
CUDA Graphs vs Eager Prefill Execution
During decode steps, each active sequence generates just 1 token, making the GPU launch-latency-bound and HBM-bandwidth-bound. Capturing fixed batch-size shapes (1, 2, 4, 8, ..., 512) into CUDA Graphs eliminates Python/CPU kernel-launch overhead and dispatches the entire forward pass in one GPU graph launch. Conversely, long variable-length prefills are compute-bound and span arbitrary token lengths, so the model runner executes them eagerly with FlashAttention kernels (and chunked prefill splits long prompts into fixed token chunks so decode sequences never stall).
Trade-offs
Configuring block sizes, prefix caching, and chunked prefill trades metadata overhead, sharing granularity, and tail latency.
| Engine Mechanism | Primary Latency / Throughput Gain | Memory or Compute Cost | Failure / Trade-off Boundary |
|---|---|---|---|
| Small KV Block Size () | Low internal tail waste; fine-grained prefix sharing | Larger block tables; slightly less coalesced attention reads | Very small blocks () hurt attention kernel bandwidth |
| Large KV Block Size ( or \$128$) | High vectorized HBM throughput | Up to wasted tokens per sequence; coarse prefix hits | Prompts shorter than miss prefix cache completely |
| Radix / Hash Prefix Caching | Eliminates redundant prefill compute on shared prompts | Block-hash lookup overhead; pinned stale blocks shrink active pool | High-churn unique prompts gain zero hits and add hash cost |
| CUDA Graph Decode Capture | Removes CPU kernel-launch jitter during small-batch decode | Pre-allocates static activation buffers per captured batch size | Restricts dynamic tensor shapes; requires padded batch buckets |
Failure modes and misconceptions
- Preempting running sequences silently thrashing VRAM: When concurrent sequences grow past free physical blocks, the scheduler must either swap blocks to host CPU RAM or recompute evicted tail blocks later. Sizing concurrency too high without headroom triggers preemption cascades where requests repeatedly re-prefill instead of finishing.
- Confusing GPU SM utilization with useful decode throughput: A 99% busy GPU running endless recomputed prefills or stalled behind unchunked 32k prompts yields terrible interactive time-per-output-token (TPOT). Always track TTFT, ITL/TPOT, KV cache utilization %, and preemption count together.
- Assuming prefix caching helps unaligned dynamic prefixes: Hashing operates per -token aligned block from token 0. Putting a variable user ID inside block 0 invalidates every subsequent block hash for the rest of the system prompt.
- Disabling chunked prefill on mixed chat/batch workloads: One incoming 16k-token summarization prompt in an unchunked engine freezes every active interactive chat stream for hundreds of milliseconds while prefill saturates the GPU.
Decision scenario
A production code-assistant deployment serves mixed interactive autocomplete requests (target TTFT < 120ms, ITL < 25ms) alongside long 12k-token PR review prompts sharing a static 2,048-token repository guideline prefix. Telemetry shows interactive ITL spiking above 180 ms whenever PR reviews arrive and KV memory exhausting at 22 concurrent streams. Enable chunked prefill with a 512-token prefill budget per scheduler step so decode steps interleave smoothly, turn on hash-based Automatic Prefix Caching with block size (pinning the 2,048-token rubric cleanly across 128 aligned blocks), and capture CUDA Graphs up to batch size 128 while reserving 10% physical KV-block headroom against preemption storms.
Implementation example
This Python KV-cache block table and prefix-hash allocator models non-contiguous physical page allocation, hash-chained prefix reuse, and Copy-on-Write branching for parallel beams.
pythonimport hashlibfrom dataclasses import dataclass, field@dataclassclass PhysicalBlock:block_id: int; ref_count: int = 0; prefix_hash: str | None = None; tokens: list[int] = field(default_factory=list)class PagedKvAllocator:def __init__(self, num_blocks: int, block_size: int = 16) -> None:self.bs, self.blocks = block_size, [PhysicalBlock(i) for i in range(num_blocks)]self.free_ids, self.radix = list(range(num_blocks - 1, -1, -1)), {}def allocate_prompt(self, token_ids: list[int]) -> list[int]:table, parent = [], "ROOT"for i in range(0, len(token_ids), self.bs):chunk = token_ids[i : i + self.bs]key = hashlib.blake2b(f"{parent}:{chunk}".encode(), digest_size=12).hexdigest() if len(chunk) == self.bs else Noneif key and key in self.radix:bid = self.radix[key]; self.blocks[bid].ref_count += 1; parent = keyif bid in self.free_ids: self.free_ids.remove(bid)else:bid = self.free_ids.pop(); blk = self.blocks[bid]if blk.prefix_hash: self.radix.pop(blk.prefix_hash, None)blk.ref_count, blk.tokens, blk.prefix_hash = 1, list(chunk), keyif key: self.radix[key] = bid; parent = keytable.append(bid)return tabledef cow_append(self, table: list[int], tok: int) -> list[int]:tail = self.blocks[table[-1]]if len(tail.tokens) < self.bs and tail.ref_count == 1: tail.tokens.append(tok); return tablenid = self.free_ids.pop()if len(tail.tokens) < self.bs: # Copy-on-Write split for shared tail blockself.blocks[nid].tokens, tail.ref_count, self.blocks[nid].ref_count = list(tail.tokens) + [tok], tail.ref_count - 1, 1return table[:-1] + [nid]self.blocks[nid].tokens, self.blocks[nid].ref_count = [tok], 1; return table + [nid]
Knowledge check
How do PagedAttention virtual block tables, chained prefix hashing, and Copy-on-Write reference counting work together to raise concurrency without corrupting shared prompt states?