FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Inference Engine Architecture

How schedulers KV-cache managers model runners and distributed executors determine serving behavior.

Freshness: current•16 min read•Model Serving and MLOps

Key Learning Outcomes

  • ✓Trace scheduler cache manager and model runner responsibilities
  • ✓Explain continuous batching and paged KV memory
  • ✓Diagnose engine-level throughput constraints
Full Technical Reference Document

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.

AsyncLLM Request Queue
Scheduler Budget Admission
Paged KV Block Allocation
Prefix Cache & CoW Sharing
CUDA-Graph / Prefill Runner
Conceptual teaching model synthesized from:Efficient Memory Management for Large Language Model Serving with PagedAttentionvLLM inference and serving enginevLLM AsyncLLM engine at v0.10.2vLLM V1 KV cache manager at v0.10.2

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 BB tokens (typically B=16B = 16 or \$32$).

PagedAttention Block Tables & Fragmentation Math

Each sequence maintains a logical-to-physical block table mapping logical block index j=⌊t/B⌋j = \lfloor t / B \rfloor to any free physical VRAM block frame pjp_j. 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 (B−1)/2(B - 1)/2 tokens per sequence):

KVbytes/token=2⋅L⋅nkv⋅dhead⋅sdtype\text{KV}_{\text{bytes/token}} = 2 \cdot L \cdot n_{\text{kv}} \cdot d_{\text{head}} \cdot s_{\text{dtype}}

Here, LL is transformer layer count, nkvn_{\text{kv}} is KV head count (under GQA/MQA), dheadd_{\text{head}} is head dimension, sdtypes_{\text{dtype}} 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 (L=80L = 80, nkv=8n_{\text{kv}} = 8, dhead=128d_{\text{head}} = 128) in FP16 (sdtype=2s_{\text{dtype}} = 2) with block size B=16B = 16 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 (B=16B = 16) 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,830 physical blocks (157,280 token slots).
  • Under naive contiguous pre-allocation for max_model_len = 8192 (512 blocks/request), VRAM accommodates at most 9,830 / 512 = 19 concurrent requests—even if average requests use only 1,000 tokens (63 blocks). With PagedAttention allocating blocks on demand, 9,830 / 63 fits 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)

Prompt Length (L tokens)64 tokens
Blocks per seq: ⌈L/B⌉ = 4Page Size B = 16
Active Sequences (Concurrency)3 requests
Total blocks needed: 12Pool Capacity: 32
Physical GPU Block Table (32 × 16-Token Pages)Allocated: 12/32 Blocks
#0S0
#1S0
#2S0
#3S0
#4S1
#5S1
#6S1
#7S1
#8S2
#9S2
#10S2
#11S2
#12·
#13·
#14·
#15·
#16·
#17·
#18·
#19·
#20·
#21·
#22·
#23·
#24·
#25·
#26·
#27·
#28·
#29·
#30·
#31·
Blocks per Seq⌈64/16⌉ = 4
Allocated Blocks12 / 32
Internal Waste0 tokens
Fragmentation0%

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 BB 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 MechanismPrimary Latency / Throughput GainMemory or Compute CostFailure / Trade-off Boundary
Small KV Block Size (B=16B = 16)Low internal tail waste; fine-grained prefix sharingLarger block tables; slightly less coalesced attention readsVery small blocks (B=4B = 4) hurt attention kernel bandwidth
Large KV Block Size (B=64B = 64 or \$128$)High vectorized HBM throughputUp to (B−1)(B - 1) wasted tokens per sequence; coarse prefix hitsPrompts shorter than BB miss prefix cache completely
Radix / Hash Prefix CachingEliminates redundant prefill compute on shared promptsBlock-hash lookup overhead; pinned stale blocks shrink active poolHigh-churn unique prompts gain zero hits and add hash cost
CUDA Graph Decode CaptureRemoves CPU kernel-launch jitter during small-batch decodePre-allocates static activation buffers per captured batch sizeRestricts 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 BB-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 B=16B = 16 (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.

python
import hashlib
from dataclasses import dataclass, field
@dataclass
class 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 None
if key and key in self.radix:
bid = self.radix[key]; self.blocks[bid].ref_count += 1; parent = key
if 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), key
if key: self.radix[key] = bid; parent = key
table.append(bid)
return table
def 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 table
nid = self.free_ids.pop()
if len(tail.tokens) < self.bs: # Copy-on-Write split for shared tail block
self.blocks[nid].tokens, tail.ref_count, self.blocks[nid].ref_count = list(tail.tokens) + [tok], tail.ref_count - 1, 1
return table[:-1] + [nid]
self.blocks[nid].tokens, self.blocks[nid].ref_count = [tok], 1; return table + [nid]

Knowledge check

Reflect before revealing the guide

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?

Prerequisites & Related Concepts (4)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-101Model Serving and Inference

Understand inference engines memory scheduling batching routing scaling distributed execution lifecycle controls observability and economics.

19 concepts~23h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.