Model Serving

Dive into Deep Learning · §39.7

Model Serving: Prefill vs. Decode, Continuous Batching, PagedAttention, and SLOs
TTFT & TPOT · goodput · GGUF & AWQ/FP8 · vLLM & SGLang · continuous batching · PagedAttention · prefix caching · speculative decoding

From Single-User Notebooks to Multi-User Serving

Motivation

  • Why serial serving collapses: Running 100 two-second requests one after another makes the 100th user wait over 3 minutes while streaming weights 100 separate times (98\% ALU idle).
  • Why dynamic batching transforms decode: Advancing b concurrent users together reads the 16.4\text{ GB} model weights once per step for all b users, multiplying throughput 30\text{--}50\times.

Two Phases of Generation: Prefill vs. Decode

Workload Anatomy

Every generative request executes two physically distinct computational regimes that map directly to the two latency metrics users feel:

  • 1. Prompt Prefill \to Time to First Token (TTFT):
    • Processes all p prompt tokens in parallel to populate the initial KV cache.
    • High arithmetic intensity (compute-bound); sets the wait before the first word appears.
  • 2. Autoregressive Decode \to Time per Output Token (TPOT):
    • Generates one new token per active sequence per step.
    • Low arithmetic intensity (memory-bandwidth bound); sets the streaming reading pace (\text{tok/s} = 1/\text{TPOT}).

Latency SLOs, Raw Throughput, and Goodput

Production Metrics

  • Service Level Objectives (SLOs): Bound both Time to First Token (e.g., \text{TTFT} \le 1.0\text{ s}) and Time per Output Token (\text{TPOT} \le 50\text{ ms}, or \ge 20\text{ tok/s} per user).
  • Goodput vs. Raw Throughput: Under overload, queue depth explodes so goodput (SLO-compliant req/s) collapses toward zero even while raw token/s stays pinned near 100\% peak.

Matching the Serving Stack to the Workload (Nov 2026)

Engine Landscape

  • Local & Offline Batch: Use Ollama / LM Studio (llama.cpp GGUF) or MLX for local single-user privacy, and vLLM offline mode to maximize tokens/dollar on dataset scoring.
  • Online APIs & Datacenter Fleets: Use vLLM or SGLang (RadixAttention prefix tree) for low-latency multi-user services, and NVIDIA Dynamo + TensorRT-LLM for disaggregated multi-node fleets.

Local Serving Engines and GGUF Quantization

Single-User Inference

  • Qwen3-8B (8.2\text{B}) GGUF footprints: Q4_K_M (\sim 4.9\text{ bits/w}) takes \sim 5.2\text{ GB}, Q5_K_M takes \sim 5.8\text{ GB}, and Q8_0 takes \sim 8.7\text{ GB}.
  • Capacity + speed + KV cache: 4-bit weights nearly double batch-1 decode speed over 8-bit, and leave room on a 16 GB card for a 32K BF16 KV cache (\sim 4.8\text{ GB}).

Batched Decode Arithmetic and the TPOT Ceiling

Multi-User Roofline

\text{TPOT}(b) \approx \frac{B_w + b \, n \, B_{\text{kv}}}{\beta}, \qquad \text{Throughput}(b) = \frac{b}{\text{TPOT}(b)}

  • Qwen3-8B (BF16) on H100 (\beta = 3.35\text{ TB/s}, n = 2{,}048): Scaling b from 1 \to 64 raises TPOT by only 2.1\times (5.0 \to 10.7\text{ ms}) while multiplying throughput 30\times (201 \to 6{,}000\text{ tok/s}).
  • SLO & KV ceiling: A 20\text{ ms} TPOT SLO caps batch size at b_{\max} = 167 (8{,}350\text{ tok/s}), approaching the KV-cache ceiling \beta/(n B_{\text{kv}}) \approx 11{,}090\text{ tok/s}.

Server Engines: vLLM, SGLang, TensorRT-LLM, Dynamo

Multi-User Architectures

  • vLLM & SGLang: vLLM standardizes PagedAttention, continuous batching, and OpenAI-compatible serving (vllm serve); SGLang’s RadixAttention stores KV caches in a radix tree for multi-turn agents.
  • TensorRT-LLM & NVIDIA Dynamo: TensorRT-LLM compiles hardware-tuned FP8/NVFP4 kernels, while Dynamo disaggregates prefill and decode onto separate GPU pools with prefix-aware routing.

The OpenAI API Contract and Conformance Testing

Portable Client Code

Because local and server engines implement the OpenAI Chat Completions schema, client applications switch from a laptop Ollama to a cloud vLLM cluster by changing only base_url and model:

from openai import OpenAI

client = OpenAI(
    base_url="http://127.0.0.1:8000/v1",
    api_key="local",
)
resp = client.chat.completions.create(
    model="Qwen/Qwen3-8B",
    messages=[{"role": "user", "content": "Hi"}],
    temperature=0,
)
  • Why identical API schemas still diverge in behavior:
    • Different chat-template Jinja whitespace/BOS tokens shift usage.prompt_tokens and consume context budgets differently.
    • Streaming usage chunks (stream_options), stop string truncation, and structured-output grammar engines vary by server.
    • Batch-size non-determinism: Even at temperature=0, a busy vLLM server groups requests into varying batch shapes, changing floating-point reduction order enough to flip close argmax ties.

Continuous Batching: Eliminating Static Padding Waste

Engine Technique 1

Static batching locks b requests together until the longest generation finishes, wasting GPU slots whenever shorter responses finish early:

  • Iteration-level scheduling (Continuous Batching):
    • At the end of every single decode step, the engine checks for sequences that emitted <eos> or hit max_tokens.
    • Finished sequences exit immediately, freeing their KV-cache blocks, and waiting requests from the queue enter the batch on the very next step.
  • Result on requests of [5, 2, 7, 3] output tokens across 2 slots: Continuous batching finishes all four requests in 9 decode steps instead of 12 (25\% higher utilization).

Simulating a Continuous Batching Scheduler in Code

Executable Scheduler

Ten lines of Python capture the core state machine of an iteration-level continuous batching loop:

  • Step-by-step slot refill:
    • Step 1 starts (5, 2). After 2 steps, the 2-token request finishes ((3,) remaining) and the 7-token request immediately takes slot 2 ((3, 7)).
    • When the first request finishes at step 5, the final 3-token request enters slot 1 ((3, 4)), leaving only 1 single-occupancy tail step at the very end.
from collections import deque

requests = deque([5, 2, 7, 3])  # output tokens requested
capacity = 2
active, timeline = [], []
while requests or active:
    while requests and len(active) < capacity:
        active.append(requests.popleft())
    timeline.append(tuple(active))
    active = [remaining - 1 for remaining in active if remaining > 1]

timeline
[(5, 2), (4, 1), (3, 7), (2, 6), (1, 5), (4, 3), (3, 2), (2, 1), (1,)]

PagedAttention and KV Cache Capacity Planning

Engine Technique 2

  • Contiguous reservation waste (max_len=32,768): Reserves 4.83\text{ GB/seq} out of 55.6\text{ GB} free H100 VRAM, fitting only b = 11 sequences while leaving 93.7\% of reserved KV memory empty at n = 2{,}048.
  • PagedAttention (16-token virtual blocks): Allocates 2.36\text{ MB} blocks on demand (< 0.7\% internal waste), expanding concurrent capacity 16.7\times to b = 184 sequences so the 20\text{ ms} TPOT SLO (b = 167) binds first.

Prefix Caching and Prompt Engineering for Cache Hits

Engine Technique 3

When requests share an identical leading token sequence (system instructions, few-shot examples, or repository context), prefix caching reuses the precomputed KV blocks without re-running prefill:

  • Chained block hashing: Each 16-token block is keyed by \text{hash}(\text{parent\_block\_key}, \text{token\_ids}) because causal self-attention makes token representations depend on every preceding token.
  • 30-turn coding agent (20\text{K} base context + 1\text{K} appended/turn):
    • Uncached prefill computes \sum_{k=0}^{29} (20 + k)\text{K} = \mathbf{1{,}035{,}000\text{ tokens}}.
    • Prefix caching computes only 20\text{K} + 29 \times 1\text{K} = \mathbf{49{,}000\text{ tokens}} (21\times less prefill work).
  • Prompt design rule: Never put a per-second timestamp on line 1 of a system prompt—doing so invalidates the hash chain from block 0. Put volatile metadata at the end of the prompt.

Speculative Decoding and Server Quantization

Engine Technique 4

\mathbb{E}[\text{tokens/round}] = \frac{1 - \alpha^{\gamma + 1}}{1 - \alpha}

  • Draft & parallel verify: A small draft model q (cost c \ll 1) proposes \gamma tokens; one target pass p verifies all \gamma+1 tokens in parallel, preserving the exact target distribution (2.80\times speedup at \alpha=0.8, \gamma=4, c=0.05).
  • Busy-server caveat: Parallel verification is free only while memory-bound; on H100 (I^* \approx 295), any batch b > 295/(\gamma+1) = 59 becomes compute-bound.

Chunked Prefill, Admission Control, and Operations

Production Reliability

  • Chunked prefill: Splits long 16K prompts into fixed step budgets (e.g., 2{,}048 tokens/step) and piggybacks active decode tokens so prefill bursts never spike TPOT.
  • Admission, cancellation & co-pinning: Reject arrivals early when queue depth exceeds the TTFT SLO, abort disconnected HTTP streams, front with a TLS/auth/rate-limit proxy, and co-pin (model_sha, tokenizer, quant, engine).

Concept Check: KV Cache, Batching, and Prefix Reuse

Check Your Understanding

Test your serving systems arithmetic on these three scenarios:

  1. In a retrieval-augmented generation (RAG) service, a shared 2,000-token system prompt is followed by 3 retrieved documents out of a 50-document corpus. Request 1 retrieves [Doc A, Doc B, Doc C] and Request 2 retrieves [Doc B, Doc A, Doc C]. Under block-hashed prefix caching, which KV blocks does Request 2 reuse, and how can you raise cache hits?
  2. On our H100 serving Qwen3-8B (n = 2{,}048 average context, 72\text{ GB} memory budget), the service enforces a \text{TPOT} \le 20\text{ ms} SLO (b_{\max,\text{SLO}} = 167). Under contiguous max_model_len=32768 allocation (b_{\max,\text{mem}} = 11) vs. PagedAttention (b_{\max,\text{mem}} = 184), which constraint binds the batch size in each case?

Answers:

  1. Request 2 reuses only the 2,000-token system prompt. Because Doc B sits at position 2001 instead of Doc A, every block hash from token 2001 onward changes. Ordering retrieved documents in a canonical ID order ([Doc A, Doc B, Doc C]) allows full prefix reuse whenever subsets share leading documents, trading off relevance-order positional bias.
  2. Under contiguous reservation, memory capacity binds first (11 \ll 167, leaving the GPU starved). Under PagedAttention, memory holds 184 sequences, so the 20\text{ ms} TPOT latency SLO binds first at b = 167.

Concept Check: KV Cache, Batching, and Prefix Reuse (cont.)

Check Your Understanding

  1. For speculative decoding with draft cost c = 0.05, acceptance rate \alpha = 0.8, and \gamma = 4 draft tokens, what is the expected speedup over standard batch-1 decoding?

Answer:

  1. Expected tokens per round = (1 - 0.8^5) / (1 - 0.8) = 0.67232 / 0.2 = \mathbf{3.362\text{ tokens}} in time 1 + 4(0.05) = \mathbf{1.20\text{ target steps}}, giving a \mathbf{2.80\times} speedup.

Summary: Model Serving Systems

Key Takeaways

Serving Component Physical / Algorithmic Principle Production Engineering Rule
Prefill vs. Decode Prefill is parallel & compute-bound (sets TTFT); decode is serial & bandwidth-bound (sets TPOT) Optimize prefill with tensor cores & prefix caching; optimize decode with batching & quantization
Batched decode scaling t(b) = (B_w + b \, n \, B_{\text{kv}}) / \beta Batching amortizes weight reads B_w until KV-cache bandwidth b \, n \, B_{\text{kv}} or the TPOT SLO caps b
Continuous batching Retires finished sequences and refills slots at every decode step Eliminates static padding bubbles and raises GPU slot occupancy
PagedAttention Allocates KV cache in on-demand 16-token virtual blocks Eliminates \sim 90\%+ contiguous reservation waste, expanding concurrent batch capacity > 10\times
Prefix caching Reuses KV blocks across matching chained block hashes Place static system prompts and canonical context before dynamic timestamps or user queries
Goodput & admission Overload inflates queues so goodput collapses while raw throughput stays high Use chunked prefill, early TTFT-based admission control, and client cancellation propagation