vLLM Internals: Continuous Batching & PagedAttention Non-Contiguous KV Blocks
How vLLM achieves 10×–24× higher LLM serving throughput than naive Hugging Face generate(): Iteration-Level Continuous Batching, OS-inspired PagedAttention Virtual KV Blocks (<4% VRAM waste), Chunked Prefill, and Copy-on-Write Prefix Caching.
vLLM combines Continuous Batching (inserting new requests the moment any sequence finishes) with PagedAttention (storing KV-Cache in non-contiguous fixed-size virtual memory blocks).
Static batching wastes GPU cycles waiting for the longest reply in a batch, and contiguous KV pre-allocation wastes 60%–80% of VRAM; vLLM boosts serving throughput 10×–24×.
If you deploy an open-weights LLM with naive model.generate(), you leave 90%+ of your GPU throughput on the table — vLLM / SGLang / TensorRT-LLM are mandatory for production!
PagedAttention + Continuous Batching + Automatic Prefix Caching are the three core algorithms powering almost every LLM inference engine on Earth.
Understanding why Chunked Prefill slices a giant 16K prompt into 512-token chunks interleaved with Decode steps explains how production APIs keep streaming smooth for all users simultaneously!
Classic AI infra interview question: 'How does vLLM's PagedAttention work, why did contiguous KV allocation waste 65%+ VRAM, and how does it enable zero-copy Prefix Caching?'
In a naive LLM server that pre-allocates a contiguous KV-Cache buffer of size max_seq_len = 4,096 for every user, how much of that buffer is wasted if the user only generates 400 tokens?
- Contrast Static Batching (idle GPU bubbles waiting for the longest output) with Iteration-Level Continuous Batching
- Explain why contiguous KV-Cache pre-allocation wastes ~60%–80% of GPU HBM via internal & external fragmentation
- Trace vLLM's PagedAttention Block Table mapping logical KV blocks onto non-contiguous 16-token physical GPU pages
- Explain Automatic Prefix Caching (Copy-on-Write shared KV pages) and Chunked Prefill for smooth low-jitter streaming
Imagine a restaurant (Static Batching) that locks its doors until ALL 8 tables finish dessert — wasting half the night! Continuous Batching seats a new party the instant any table finishes. Meanwhile, PagedAttention stops reserving a giant 50-seat banquet table for every couple who might invite friends — instead giving them small 2-seat tables (16-token pages) anywhere in the room and linking them on a clipboard (Block Table)!
1. Static Batching vs. Iteration-Level Continuous Batching
Look at the grey dashed IDLE WAIT bubbles on the left vs. the 100%-packed GPU lanes on the right!
Why Continuous Batching Multiplies Throughput by 4×–10×
Because LLM output lengths vary wildly (20 tokens vs. 2,000 tokens), Static Batching idles short requests while waiting for the single longest request. Continuous Batching schedules at the single-token iteration level: the instant Request #1 emits <|im_end|>, its slot is freed and Request #4 starts on the very next millisecond!
2. PagedAttention: Virtual-Memory KV-Cache Blocks
Drag the Actual Tokens slider in the mini-lab below to compare contiguous pre-allocation waste against PagedAttention's <4% waste!
Inside the PagedAttention CUDA Kernel
- GPU HBM KV space is pre-partitioned into a pool of uniform 16-token physical blocks.
- As User A generates token #17, the scheduler pops 1 free physical block (e.g., Block
#2anywhere in HBM) and recordsLogical 1 → Phys #2in User A's Block Table. - The fused PagedAttention kernel reads non-contiguous physical blocks on-the-fly directly into SRAM — zero external fragmentation and at most 15 tokens of internal fragmentation per request!
KV-Cache Waste: Contiguous (max=2048) vs. Paged (B=16)
3. Copy-on-Write Automatic Prefix Caching & Chunked Prefill
PagedAttention unlocks a massive bonus superpower: zero-copy shared KV pages across concurrent users!
Two Production Serving Superpowers
- Automatic Prefix Caching (vLLM / SGLang RadixAttention): Hashes each 16-token block's prefix tokens. If 100 users share the same 4,000-token System Prompt or RAG document, all 100 Block Tables simply point to the EXACT same physical KV blocks (
ref_count = 100) — zero duplicate VRAM and near-instant TTFT! - Chunked Prefill: Slices a 16K-token incoming prompt into 512-token chunks and packs them into the same GPU batch as active Decode tokens — combining compute-bound Prefill with memory-bound Decode for maximum Tensor Core utilization!
Worked Example: PagedAttention Waste for a 50-Token Reply
Max context = 4,096, actual reply = 50 tokens, PagedAttention block size B = 16.
Reserves 4,096 slots → 4,046 unused → 98.8% wasted VRAM!
In vLLM PagedAttention, what data structure maps a request's logical token blocks to scattered physical GPU HBM pages?
If you have 100 concurrent users running Beam Search (beam_width = 4) or Best-of-N (N = 4) on the same prompt, how much prompt KV-Cache memory does PagedAttention Copy-on-Write save?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
SGLang stores cached KV-Cache blocks inside a Radix Tree (compressed prefix trie) in GPU HBM with LRU eviction — making multi-turn chat, few-shot prompts, and tree-of-thought branches automatically reuse shared prefixes in lookup!
vLLM PagedAttention Physical Block Allocator & Shared Prefix Pool
Watch 3 concurrent users allocate non-contiguous 16-token KV pages on demand while sharing Page #0 (System Prompt).
High-Throughput Production APIs (vLLM / SGLang / TensorRT-LLM)
Standard stack delivering 10×–24× higher tokens/sec/$ than naive PyTorch serving.
# PagedAttention Block Table: Map Logical KV Blocks to Non-Contiguous Physical VRAM Slots
class PagedKVCacheManager:
def __init__(self, num_physical_blocks: int, block_size: int = 16):
self.block_size = block_size
self.free_blocks = list(range(num_physical_blocks))
self.block_tables: dict[str, list[int]] = {}
def allocate_tokens(self, req_id: str, num_tokens: int) -> list[int]:
needed = (num_tokens + self.block_size - 1) // self.block_size
table = self.block_tables.setdefault(req_id, [])
while len(table) < needed:
table.append(self.free_blocks.pop(0))
return table
def free_request(self, req_id: str):
self.free_blocks.extend(self.block_tables.pop(req_id, []))
mgr = PagedKVCacheManager(num_physical_blocks=8, block_size=16)
print("Req A blocks (35 tok):", mgr.allocate_tokens("req_A", 35))
print("Req B blocks (20 tok):", mgr.allocate_tokens("req_B", 20))
mgr.free_request("req_A")
print("Free physical blocks after Req A finishes:", mgr.free_blocks)