Mental model
An LLM inference engine is a stateful queueing scheduler wrapping finite HBM memory pools and Tensor Core budgets. Replacing static padded request batches with iteration-level continuous batching, PagedAttention virtual KV blocks, bounded chunked prefill, and prefill-decode disaggregation eliminates fragmentation and head-of-line latency stalls simultaneously.
Learning outcomes
- Quantify padding waste in static request-level batching versus iteration-level continuous scheduling in vLLM V1.
- Explain how PagedAttention eliminates external fragmentation and upfront
max_seq_lenover-reservation using fixed-size KV blocks. - Size chunked prefill token budgets (
max_num_batched_tokens) to protect decode inter-token latency (ITL) from long-prompt stalls. - Evaluate when prefill-decode (P/D) disaggregation over NVLink or RDMA outperforms unified chunked-prefill pools.
Theory
Traditional neural serving engines group requests into a static tensor padded to and hold every GPU slot until the longest sequence emits end-of-sequence (EOS). If one request emits 1,024 tokens while three others finish at 32 tokens, the engine wastes over two-thirds of active GPU iterations. Continuous iteration-level scheduling (implemented in vLLM's V1 scheduler, vllm/v1/core/sched/scheduler.py) makes scheduling decisions on every forward step: finished sequences release their KV blocks immediately and queued requests enter the running batch on the very next token step.
Even with continuous batching, contiguous KV allocation wastes 60%–80% of HBM because engines must pre-reserve contiguous buffers up to max_model_len before knowing how long a response will grow, leaving unusable external fragmentation holes between variable-length sequences. PagedAttention (vllm-paper) virtualizes KV memory into fixed-size pages of tokens (typically 16). A per-sequence block table maps logical token positions onto non-contiguous physical GPU blocks allocated lazily on demand, bounding internal waste to at most tokens on the tail page and enabling zero-copy prefix sharing across requests sharing system prompts.
KV-Cache Block Allocator (Paged vs Contiguous)
Continuous batching alone still suffers from prefill-decode interference: when a 16,384-token RAG prompt arrives, running its entire prefill in one step hijacks the GPU for hundreds of milliseconds, stalling ITL across every concurrent interactive decode stream (head-of-line blocking). Two production architectures solve this:
- Chunked Prefill: Splits long prompts into bounded slices (e.g., tokens) and merges each prefill slice with active 1-token decode steps up to a fixed iteration token budget:
Piggybacking decode tokens onto prefill chunks saturates Tensor Cores while capping worst-case decode ITL jitter.
- Prefill-Decode (P/D) Disaggregation: Dedicates separate GPU pools to compute-bound prefill and bandwidth-bound decode, streaming materialized KV blocks over NVLink or RDMA. Disaggregation wins on strict SLO isolation whenever KV transfer latency is negligible relative to co-located prefill stalls:
When aggregate free KV blocks drop below demand during extreme bursts, the scheduler performs preemption—either swapping evicted blocks to host CPU RAM or discarding them for later recomputation (recompute often beats PCIe swap latency on fast compute models).
Worked quantitative example
Consider 4 requests arriving together with output lengths [32, 64, 128, 1024] on a model with max_model_len = 4,096 and 128 KiB/token GQA-8 KV footprint:
- Static Padded Batching + Contiguous
max_model_lenReservation: Reserving contiguous slots for4,096tokens per request pins upfront, while waiting1,024iterations occupies4 * 1,024 = 4,096decode slot-steps for only32 + 64 + 128 + 1024 = 1,248real tokens—wasting69.5%of slot-steps on idle padding! - PagedAttention (
B_page = 16) + Continuous Batching: Actual blocks needed match live token growth (ceil(len / 16)), keeping internal fragmentation below4%on average and freeing the32-token request's slots after step32so new requests backfill immediately. - Chunked Prefill vs P/D Disaggregation on an
8,192-Token Prompt: Full unchunked8kprefill stalls co-located decode by~400 ms. Chunking prefill into512-token steps (16iterations) caps per-step decode interruption near~25 ms. Conversely, transferring the8,192 * 128 KiB = 1.0 GiBKV cache from a dedicated prefill pool over400 GbpsRoCEv2/RDMA (50 GB/seffective) takes —completely decoupling decode ITL from8k+prefill bursts.
Inference serving architecture comparison
| Serving Design | KV Fragmentation | Head-of-Line Decode Stall | Batch Throughput | Operational Complexity |
|---|---|---|---|---|
| Static Batching + Contiguous KV | Very high (60%–80% waste) | Severe (max_out stalls) | Low (1x baseline) | Minimal |
| Continuous Batching + PagedAttention | Minimal (< 4% tail page) | High during long prefills | High (2.5x–3.5x) | Moderate (block table + preemption) |
| Chunked Prefill + Continuous Batching | Minimal (< 4%) | Bounded by T_budget | Very high (decode piggybacks prefill) | Moderate (token-budget tuning) |
| Disaggregated Prefill / Decode (P/D) | Minimal (< 4%) | Eliminated across pools | Peak per-tier specialization | High (RDMA/NVLink KV transport + P:D ratio) |
Trade-offs
Chunked prefill inside a unified GPU pool maximizes hardware utilization because decode tokens ride along inside prefill matrix multiplications for almost free, avoiding idle interconnect overhead or rigid prefill-to-decode replica sizing ratios. However, very long prompts (32k–128k tokens) still raise decode ITL slightly across all chunks, and unified pools share failure domains.
Prefill-decode disaggregation delivers unmatched TTFT and ITL isolation for latency-critical interactive products at scale, enabling independent tensor-parallelism topologies (e.g., high-TP compute nodes for prefill, memory-optimized nodes for decode). Its costs are network fabric requirements (NVLink / 400G RDMA), KV transfer serialization complexity, and dynamic capacity imbalance when average prompt-to-output length ratios shift mid-day.
Failure modes and misconceptions
- Assuming higher
max_num_batched_tokensalways improves user experience. Raising the iteration token budget boosts prefill throughput, but oversizing it lets multi-thousand-token prefills inflate decode ITL spikes across streaming chat users. - Ignoring preemption thrashing (
num_preemptions_total) under tight KV pools. Running KV utilization at 99% causes constant sequence eviction and recomputation loops that burn compute without advancing completed tokens; target80%–85%steady utilization with backpressure gating. - Mixing interactive and long-document batch traffic without priority classes. Without separate queues or preemption priority, batch extraction jobs starve interactive TTFT and consume shared KV blocks.
- Forgetting prefix-cache memory pinning hazards. Copy-on-write prefix KV blocks accelerate shared system prompts massively, yet pinning stale tenant prefixes without LRU eviction starves new requests of physical pages.
Decision scenario
A multi-tenant coding assistant handles both short interactive autocomplete/chat prompts (400 input tokens, 150 output tokens, strict ITL P99 at most 30 ms) and repository-wide refactoring requests (16,000 input tokens, 800 output tokens) on 8-GPU nodes connected via InfiniBand/RDMA. Users report rhythmic 380 ms freezes during streaming whenever someone submits a full-repository prompt.
First, verify whether unified chunked prefill (max_num_batched_tokens = 512, enable_chunked_prefill = True) paired with priority scheduling (prioritizing running decodes and short interactive prefills before chunking long repository prompts) pulls decode ITL P99 under 30 ms. If peak repository-upload concurrency still forces prefill chunk queues over TTFT budgets, transition to 2:6 disaggregated Prefill-to-Decode pools transferring PagedAttention KV blocks over RDMA while monitoring KV utilization (under 85%) and preemption counters.
Implementation example
This Python iteration scheduler models continuous batching with PagedAttention physical block accounting, chunked prefill token budgeting (T_budget), and LIFO preemption when free KV blocks exhaust.
pythonfrom collections import dequefrom dataclasses import dataclassimport math@dataclassclass SeqState:seq_id: strprompt_rem: inttokens: int = 0blocks: int = 0def step_scheduler(running: list[SeqState], waiting: deque[SeqState], free_blocks: int, page: int = 16, budget: int = 512) -> tuple[int, int, int, list[str]]:rem, preemptions, scheduled = budget, 0, []for seq in list(running) + list(waiting):if rem <= 0:breaktoks = 1 if seq.prompt_rem == 0 else min(seq.prompt_rem, rem)need = max(0, math.ceil((seq.tokens + toks) / page) - seq.blocks)while need > free_blocks and running and running[-1] is not seq:victim = running.pop()free_blocks, victim.blocks = free_blocks + victim.blocks, 0waiting.appendleft(victim)preemptions += 1if need <= free_blocks:if seq in waiting:waiting.remove(seq); running.append(seq)free_blocks, seq.blocks = free_blocks - need, seq.blocks + needseq.prompt_rem, seq.tokens = max(0, seq.prompt_rem - toks), seq.tokens + toksrem -= toks; scheduled.append(seq.seq_id)return budget - rem, free_blocks, preemptions, scheduledrun_q, wait_q = [], deque([SeqState("chat-1", 64), SeqState("rag-2", 1200)])assert step_scheduler(run_q, wait_q, free_blocks=64) == (512, 32, 0, ["chat-1", "rag-2"])
How do chunked prefill and prefill-decode disaggregation protect decode inter-token latency without sacrificing GPU utilization?