Chapter 34 of 40 · ~24 min read & lab+85 XP
Chapter 34 · Generative AI

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.

What Is It?

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).

Why Is It Required?

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×.

Everyday Analogy: Operating-system virtual memory paging for GPU VRAM, paired with a restaurant that seats a new table immediately instead of waiting for every diner in the room to finish.
Why ML Engineers & Data Scientists Actually Need This

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!

ML / AI Engineer

PagedAttention + Continuous Batching + Automatic Prefix Caching are the three core algorithms powering almost every LLM inference engine on Earth.

Data Scientist

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!

Interview & Debug Edge

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?'

Step 0 · Test Your Gut Before Any Math!

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?

What You Will Master in This Chapter
  • 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
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 3
Continuous Batching\text{Continuous Batching}Say aloud:“iteration-level scheduling”
Plain-English Meaning
Evicts finished requests and admits new waiting requests at EVERY single decode token step
Everyday Example
Eliminates static-batch idle bubbles!
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

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

Everyday Story First (Zero Math Yet!)

Look at the grey dashed IDLE WAIT bubbles on the left vs. the 100%-packed GPU lanes on the right!

Static Batching (Idle Bubbles) vs. Continuous Iteration-Level Batching (vLLM)Static Batching (Wastes 50%+ GPU!)IDLE WAITContinuous Batching (Zero Bubbles! ✓)Req 4 slotted immediately!
Static batching stalls finished users until the longest request in the batch finishes (wasting 60%+ GPU cycles); Continuous (Iteration-Level) Batching slots new requests in at EVERY single decode step!

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

Everyday Story First (Zero Math Yet!)

Drag the Actual Tokens slider in the mini-lab below to compare contiguous pre-allocation waste against PagedAttention's <4% waste!

vLLM PagedAttention: Logical KV Blocks → Non-Contiguous Physical GPU PagesLogical KV (User A)Block 0 (tok 0–15)Block 1 (tok 16–31)Block TableLogical 0 → Phys #5Logical 1 → Phys #2Physical GPU HBM Pool#0 (B)#1 (B)#2 (A)#3 (B)#4 (B)#5 (A)
vLLM's PagedAttention borrows OS Virtual Memory: logical KV tokens map via a Block Table onto non-contiguous 16-token physical GPU blocks — cutting KV-Cache waste from ~65% down to <4%!

Inside the PagedAttention CUDA Kernel

  1. GPU HBM KV space is pre-partitioned into a pool of uniform 16-token physical blocks.
  2. As User A generates token #17, the scheduler pops 1 free physical block (e.g., Block #2 anywhere in HBM) and records Logical 1 → Phys #2 in User A's Block Table.
  3. 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!
Animated Mini-Lab • 6.2

KV-Cache Waste: Contiguous (max=2048) vs. Paged (B=16)

Contiguous Pre-Allocation Waste
84.4% wasted!
PagedAttention (16-tok blocks)
0.0% waste ✓

3. Copy-on-Write Automatic Prefix Caching & Chunked Prefill

Everyday Story First (Zero Math Yet!)

PagedAttention unlocks a massive bonus superpower: zero-copy shared KV pages across concurrent users!

Automatic Prefix Caching (Copy-on-Write Shared KV Pages)User 1: [Sys Prompt] + Q1User 2: [Sys Prompt] + Q21 Shared Physical System-Prompt KV Page!Zero duplicate Prefill FLOPs · Zero duplicate KV VRAM ✓
Because PagedAttention stores KV-Cache in fixed blocks, multiple users sharing the same System Prompt point to the EXACT same physical KV pages (Copy-on-Write) — slashing TTFT & VRAM!

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!
Walk Through With Me · Interactive Worked Example

Worked Example: PagedAttention Waste for a 50-Token Reply

Max context = 4,096, actual reply = 50 tokens, PagedAttention block size B = 16.

11. Naive Contiguous Pre-AllocationStep 1 / 2

Reserves 4,096 slots → 4,046 unused → 98.8% wasted VRAM!

Teacher's Note: Limits max batch size to just a handful of users!
Pause & Check · Quick Intuition Pulse

In vLLM PagedAttention, what data structure maps a request's logical token blocks to scattered physical GPU HBM pages?

Try It YourselfStandard

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?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

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 O(L)O(L) lookup!

Interactive Visual Lab
Lab Challenge: Watch the 60 FPS vLLM Physical Block Allocator assign non-contiguous KV pages to 3 users sharing Page #0.
Interactive Animation • 6.2 Deep Lab

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).

Allocated: 1 / 6 Pages
Page #0
SYS (Shared)
Page #1
FREE
Page #2
FREE
Page #3
FREE
Page #4
FREE
Page #5
FREE
0%
Decode Iteration 1
Intuition Takeaway: vLLM combines Continuous Batching (zero idle bubbles), PagedAttention (non-contiguous 16-token virtual KV pages cutting waste from 65% → <4%), Prefix Caching, and Chunked Prefill for 10×–24× higher throughput.
Where This Powers Real ML, Deep Learning & Generative AI

High-Throughput Production APIs (vLLM / SGLang / TensorRT-LLM)

Standard stack delivering 10×–24× higher tokens/sec/$ than naive PyTorch serving.

Production NumPy & PyTorch Code Patterns
# 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)
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Saying PagedAttention reduces the mathematical size of 1 token's KV vector.
Best Practice: Be precise: GQA / MLA / FP8 KV shrink each token's KV bytes; PagedAttention eliminates fragmentation & over-reservation waste and enables shared-prefix Copy-on-Write!
Chapter Mastery Check (+85 XP)
Score: 0 / 1
1What primary memory problem does vLLM's PagedAttention solve?

Apply What You Learned — Solve Matching Coding Problems