Maps to: UC Berkeley EE 290/194 Scalable AI, Fall 2026 Lecture 18 (slides not public when these notes were written) and Spring 2026 Lecture 18, Fundamentals and Overview of High-Performance Inference Frameworks: serving stacks for reasoning, agentic, multimodal, and long-context models (slides
lecture_18.pdf). Recommended reading:
- Engines: Kwon et al., Efficient Memory Management for Large Language Model Serving with PagedAttention (vLLM, SOSP 2023); Yu et al., Orca: A Distributed Serving System for Transformer-Based Generative Models (OSDI 2022); Agrawal et al., Taming Throughput-Latency Tradeoff in LLM Inference with Sarathi-Serve (OSDI 2024); the vLLM team’s Inside vLLM: Anatomy of a High-Throughput LLM Inference System (blog, 2025).
- Metrics and goodput: Zhong et al., DistServe (OSDI 2024) §2; Pope et al., Efficiently Scaling Transformer Inference (MLSys 2023).
- Caching: vLLM’s Automatic Prefix Caching design document; Zheng et al., SGLang (RadixAttention; Lecture 23).
Code:
code/lecture22/contains:
step_model.py(the cost of one engine step),kv_alloc.py(contiguous and paged KV managers with prefix caching),serve_sim.py(an iteration-level serving simulator);tiny_engine.py: a real engine on the CPU, with continuous batching, chunked prefill, a paged KV cache, prefix caching and preemption, serving Lecture 21’s parent model;- five demos: prefill vs decode, KV memory, batching and scheduling, prefix caching, the real engine.
Reading time: ~2.5 hours for the prose; ~1.5 minutes to run all demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Decompose a serving stack into API, router, scheduler, executor, kernels, KV manager and caches, and say which one a symptom points to.
- Explain prefill vs decode: why one is compute-bound and the other memory-bound, and how that shapes TTFT, TPOT and batching.
- Do KV-cache accounting and turn it into a concurrency limit.
- Explain paged KV memory: blocks, block tables, sharing, copy-on-write, preemption, and the admission rules that keep it stable.
- Compare schedulers (static, continuous, chunked prefill), choose a token budget, and read a latency–throughput frontier and goodput under an SLO.
- Use prefix caching, and know what it speeds up and what it does not.
0.2 Prerequisites and scope
- Prerequisites:
- Lecture 2: the roofline;
- Lecture 4: GQA and the KV cache;
- Lecture 21: what deployment preparation does to a decode step.
- Scope: one engine (one model replica): how it turns a stream of requests into steps on one GPU or one tensor-parallel group.
- Not in scope:
- many replicas, routers and disaggregated prefill/decode, CUDA graphs and engine internals in practice: Lecture 23;
- decode-specialized hardware: Lecture 24.
0.3 Section → code map
| Section | Idea | Code in code/lecture22/ |
|---|---|---|
| §2 | prefill vs decode, TTFT and TPOT | step_model.py, 01_prefill_vs_decode.py |
| §3 | KV-cache accounting | 01_prefill_vs_decode.py Part C |
| §4 | paged KV memory, sharing, preemption | kv_alloc.py, 02_kv_memory.py |
| §5 | batching and scheduling | serve_sim.py, 03_batching_and_scheduling.py |
| §6 | prefix caching | kv_alloc.py, 04_prefix_caching.py |
| §7 | anatomy of an engine | tiny_engine.py, 05_tiny_engine.py |
0.4 What is modelled and what is measured
step_model.pyis a model. A step’s time is max(FLOPs / (60% of peak), bytes / (80% of bandwidth)) + 1 ms of fixed per-step overhead, for Llama-3-8B on one H100.serve_sim.pydrives it with Poisson arrivals and log-normal lengths: prompts with median 1,000 tokens, outputs with median 200. Its numbers show mechanisms and orderings, not a real cluster’s milliseconds.tiny_engine.pyis real. It serves Lecture 21’s 1.3M-parameter parent on this CPU. Every output it produced in every demo was checked token for token against plain greedy decoding: 420 of 420 in Demo 05 alone. Its wall-clock numbers are this laptop’s.
1. Why serving is a hard systems problem
The slide’s opening point: the serving problem has changed. Early serving was single-turn chat on a dense model. Today’s traffic is different:
- reasoning models, which write long outputs;
- agents, which re-send long contexts and tool traces every turn;
- long-context assistants and multimodal inputs;
- sparse MoE models.
The resulting asymmetries are long prompts, bursty completions and requests that revisit old context. In the slide’s words, “memory movement, KV reuse, queueing policy and routing matter as much as raw kernel speed”. The model is only one piece of the product; the real system is an inference factory.
The serving stack has layers:
| layer | job | lecture |
|---|---|---|
| frontend / API | OpenAI-compatible endpoints, validation, tokenization, streaming | §7 |
| router / gateway | which replica gets the request (cache affinity, load, phase) | 23 |
| scheduler | which requests get tokens in this step, how many, and who is preempted | §5 |
| KV manager | blocks, tables, sharing, eviction, offload | §4, §6 |
| executor / runtime | input preparation, kernels, CUDA graphs, sampling, collectives | §7, 23 |
| cache tiers | HBM → host memory → SSD → remote KV stores | 23 |
The slide’s diagnostic rule runs through this lecture: when performance is poor, don’t say “the model is slow”. Ask which subsystem is slow: admission, scheduling, routing, memory residency, transport, kernel execution or post-processing.
2. Two phases: prefill and decode
2.1 What each phase does
Every request goes through two phases (Lecture 2 introduced them; here they become the central fact):
- Prefill processes all prompt tokens in parallel and writes their keys and values into the KV cache. It is a big matmul over many tokens, typically compute-bound, and it dominates time to first token (TTFT).
- Decode generates one token per step per sequence, reusing the cached keys and values. Each step reads all weights and the whole KV cache to do a little arithmetic, typically memory-bound, and it dominates inter-token latency (ITL) and streaming smoothness.
Demo 01 Part A prices one engine step of n tokens (Llama-3-8B, H100):
| step | tokens | ms | tokens/s | bound |
|---|---|---|---|---|
| decode, batch 1 | 1 | 7.04 | 142 | memory |
| decode, batch 32 | 32 | 8.56 | 3,739 | memory |
| decode, batch 256 | 256 | 19.5 | 13,111 | memory |
| prefill chunk of 256 | 256 | 7.50 | 34,126 | compute |
| prefill chunk of 4,096 | 4,096 | 112 | 36,581 | compute |
A lone decode token costs as much as a 256-token prefill chunk. Batching 256 decodes buys 92× the tokens per second of one.
- The knee. Below about 237 tokens per step the GPU waits on memory; above it, on math.
- Two reasons decode stays memory-bound. Decode tokens of different sequences share the weight reads, but each reads its own KV cache. So even 256 decodes stay memory-bound, and a prefill chunk crosses the knee sooner.
Everything an engine does (batching decodes, chunking prefills, mixing the two) fills steps toward that knee without hurting latency.
2.2 Per-request latency
The slide decomposes the two latencies:
- TTFT = t_queue + t_tokenize + t_prefill + t_sample + t_first-byte;
- ITL ≈ t_decode-step + t_sample + t_stream-flush.
TPOT (time per output token) is the average ITL of a request after its first token: (t_last − t_first)/(n − 1).
A request alone on the GPU (Demo 01 Part B):
- A 32K-token prompt costs about 1.3 s of TTFT on Llama-3-8B, while each later token takes 8.6 ms.
- TTFT grows with the prompt (prefill is compute-bound). TPOT grows with the context only through the KV reads.
2.3 Fleet metrics, tails, goodput
Operators track more than per-request latency:
- output throughput: tokens per second across the fleet;
- useful work per GPU: tokens/s/GPU, or revenue-generating tokens per GPU-hour;
- SLO compliance: p50 / p95 / p99 of TTFT and ITL, by traffic class;
- cache efficiency: prefix hit rate;
- admission stability: queue depth, rejections, timeouts.
Goodput combines the two views: the rate of requests that meet all their SLOs. DistServe argued for it because throughput alone rewards a server that is fast on average and terrible for some users.
Users rarely complain that a prompt took 20% too many FLOPs. They complain that “my stream stalled”, that “tool calling is jittery”, or that “some requests are 10× slower than others”. So the tail matters, not the median.
3. The KV cache is the working set
3.1 Accounting
For one sequence of T resident tokens:
KV bytes ≈ T · 2 · L · H_kv · d_h · b
- the factor 2 counts K and V;
- L = layers, H_kv = KV heads (not query heads, under GQA/MQA), d_h = head dimension;
- b = bytes per element.
The slide’s worked example: L = 80, H_kv = 8, d_h = 128, BF16 gives 2 · 80 · 8 · 128 · 2 = 320 KiB per token. One 8K-token request takes 2.5 GiB, and 32 of them take 80 GiB, before any weights.
| model | KV per token | one 8K sequence | 32 × 8K |
|---|---|---|---|
| Llama-2-7B (MHA, 32 KV heads) | 512 KiB | 4.0 GiB | 128 GiB |
| Llama-3-8B (GQA, 8 KV heads) | 128 KiB | 1.0 GiB | 32 GiB |
| Llama-3-8B, FP8 cache | 64 KiB | 0.5 GiB | 16 GiB |
| Llama-3-70B (GQA) | 320 KiB | 2.5 GiB | 80 GiB |
3.2 Capacity is concurrency
On one H100, Llama-3-8B’s BF16 weights take 16 GB. With 90% of HBM usable, 56 GB is left for KV: 52 sequences of 8K tokens, or 104 with an FP8 cache. Throughput comes from batching, and the batch is capped by KV memory long before compute. Everything that shrinks the KV cache raises the ceiling:
- GQA and MLA (Lecture 4);
- KV quantization (Lecture 21);
- hybrid models with fewer attention layers (Lecture 15).
Hence the slide’s line: “If your workload is long multi-turn sessions, the memory system is your real product surface”.
4. Managing KV memory: paging
4.1 The problem with reservations
A request’s KV cache grows by one token per decode step, up to a length nobody knows in advance. Early serving systems reserved each request’s maximum (prompt + max_tokens) as one contiguous region:
- internal fragmentation: the reserved tail holds tokens that will never be generated;
- external fragmentation: holes between reservations of different sizes.
The vLLM paper measured that only 20–38% of the KV memory reserved by earlier systems held actual token states.
Demo 02 Part A fills Llama-3-8B’s 427K KV slots with requests halfway through their outputs:
| allocator | requests running | utilization of what it holds |
|---|---|---|
| contiguous, reserve prompt + 2,048 | 125 | 44% |
| paged, 16-token blocks, on demand | 293 | 99.5% |
On a served trace at 20 requests/s both keep up with the load: about 4,300 output tokens/s each. But the reservations cap how many requests run at once, so newcomers queue. TTFT p50 is 2.50 s with contiguous reservations against 0.13 s with paging.
4.2 PagedAttention
vLLM borrowed the operating system’s answer:
- blocks: split the KV cache into fixed-size blocks of, for example, 16 tokens;
- block tables: map each sequence’s logical positions to physical blocks;
- on-demand allocation: allocate a block only when the previous one is full.
Waste is then at most one partly filled block per sequence. The attention kernel must gather each sequence’s keys and values through its block table instead of reading one contiguous array; that is the “PagedAttention” kernel. tiny_engine.py does exactly this, in Python: K and V for a token go to slot table[pos // B] · B + pos % B, and attention gathers a sequence’s slots.
Block size (Demo 02 Part B):
- 16-token blocks waste 0.49% of slots;
- 2,048-token blocks would waste 42%;
- 1-token blocks need a table entry per token.
vLLM defaults to 16.
4.3 Sharing and copy-on-write
Blocks carry reference counts, so several sequences can point at the same physical block. Parallel sampling (n completions of one prompt) shares the prompt’s blocks. When a completion writes into a shared, partly filled block, that block is first copied (copy-on-write).
Demo 02 Part C: four 500-token completions of one 2,010-token prompt need 628 blocks as private copies and 253 shared. Copy-on-write copied the last, partly filled prompt block 3 times; the last writer keeps the original. Beam search and prefix caching (§6) reuse the same mechanism.
4.4 When memory runs out: preemption
On-demand allocation can run out: every running sequence wants one more block and none is free. The scheduler must preempt a victim. vLLM takes the most recently admitted request, frees its blocks, and requeues it. The victim’s KV can be restored in one of two ways:
- recompute: prefill again, prompt + generated tokens. This costs GPU compute: 1.3 s for a 32K-token victim on Llama-3-8B (Demo 02 Part D).
- swap to host memory and back over PCIe: 134 ms for the same victim, plus 4.3 GB of host RAM, and it competes for the host link.
vLLM V1 recomputes, and prefix caching often turns the recompute into a cache hit.
Demo 02 Part E runs the real engine with a 32-block pool. It preempted 52 times and recomputed 324 extra tokens, and all 24 outputs still equal the reference: preemption costs time, never correctness.
Plan vs reality: a livelock. The first versions of both the simulator and the engine admitted new requests whenever the token budget allowed, regardless of free memory. Under pressure, a newcomer took the blocks a running request needed. The running request was preempted, re-admitted, and preempted again, and a 32-block run never finished. The fix is vLLM’s rule, now in both:
- admit a request only if the blocks for its first chunk are free now;
- admit nobody in a step that had to preempt.
Preemptions in the engine’s self-test fell from 28 to 7. Scheduling policy is part of correctness, not just speed.
5. Batching and scheduling
5.1 Static vs continuous batching
Static batching forms a batch, runs prefill for all of it (padded to the longest prompt), and decodes until its longest output is done. Nobody joins or leaves early:
- finished sequences keep computing padding;
- new requests wait for the whole batch.
Continuous batching (Orca’s iteration-level scheduling) reconsiders the batch at every step:
- finished sequences leave immediately;
- new ones join as soon as the token budget and KV space allow;
- requests can be at different generation steps.
The bookkeeping is harder (sequence lengths, pages, masks), but the hardware stays busy. Every modern engine works this way.
Demo 03 Part A, 600 requests at 8/s:
| scheduler | output tok/s | TTFT p50 | TPOT p50 | worst stall p99 |
|---|---|---|---|---|
| static batches of up to 64 | 368 | 187 s | 25.3 ms | 35 ms |
| continuous, prefill priority | 1,963 | 0.04 s | 12.7 ms | 565 ms |
| chunked prefill, budget 512 | 1,969 | 0.05 s | 9.9 ms | 17 ms |
Static batching cannot even keep up with 8 requests/s here. Each batch runs as long as its longest output, about 2,000 tokens, so the queue grows without bound.
5.2 The stall, and chunked prefill
Continuous batching in its first form (Orca, vLLM’s first engine) was prefill-priority: when new prompts arrive, a step prefills them whole, and every running decode waits for that step. One long prompt freezes every other user’s stream. That is the 565 ms stall above; the slide calls it “decode starvation by long prefills”.
Chunked prefill (Sarathi-Serve; on by default in vLLM V1) splits prompts into chunks and gives each step a token budget:
- first one token for every running decode;
- then prefill chunks fill the rest of the budget.
Decodes never stall behind a prompt, and the step stays near the knee of §2.1.
The budget is a trade-off (Demo 03 Part B, 12 requests/s):
| budget (tokens/step) | worst stall p99 | TTFT p99 | output tok/s |
|---|---|---|---|
| 128 | 10 ms | 15.6 s | 2,230 |
| 256 | 11 ms | 0.71 s | 2,787 |
| 512 | 17 ms | 0.35 s | 2,782 |
| 2,048 | 65 ms | 0.33 s | 2,767 |
| 8,192 | 233 ms | 0.37 s | 2,765 |
A tiny budget protects inter-token latency, but prompts take so many steps (each paying the per-step overhead) that prefill throughput collapses and requests queue. A huge budget behaves like prefill priority. The slide: “chunk too aggressively → more scheduler overhead, less prefill throughput; chunk too little → long prompts destroy tail ITL”.
Plan vs reality. My first test compared chunked prefill with a 2,048-token budget against prefill priority on p99 inter-token latency, and chunked lost. At light load the long-prompt stalls are rare, below the 99th percentile, while every 2,048-token chunk makes a moderately slow step. The budget is what bounds the stall, so the comparison must choose it; Part B sweeps it.
5.3 What the scheduler decides
Per engine step, the slide lists six decisions:
- which waiting requests to admit;
- how much of the token budget goes to decode vs prefill;
- whether long prefills are chunked;
- whether speculative drafts fit in the token and page budget;
- whether offloaded or reusable KV should be reloaded;
- whom to preempt under pressure.
“A scheduler tuned for benchmark throughput can be terrible for chat responsiveness, and one tuned for median latency can be terrible for cost. Scheduling is where business objectives meet systems constraints.”
5.4 The frontier and goodput
Raise the arrival rate (Demo 03 Part C; SLO: TTFT ≤ 1 s and TPOT ≤ 30 ms):
| arrivals/s | chunked: TTFT p99 / TPOT p99 / meet SLO | prefill priority: TTFT p99 / TPOT p99 / meet SLO |
|---|---|---|
| 8 | 0.27 s / 12 ms / 100% | 0.25 s / 22 ms / 100% |
| 16 | 0.58 s / 15 ms / 100% | 0.41 s / 55 ms / 23% |
| 20 | 0.82 s / 15 ms / 100% | 2.2 s / 97 ms / 2% |
| 28 | 5.3 s / 15 ms / 12% | 10 s / 159 ms / 0% |
Throughput rises with load until the GPU saturates; then the queue, and with it TTFT, explodes. The highest rate at which 90% of requests meet the SLO is 20/s with chunked prefill and 12/s with prefill priority: the scheduler, not the hardware, set the capacity. Benchmarks at infinite load report only the right end of this table. The slide warns that such a benchmark “tells you almost nothing about the experience of an interactive product”.
5.5 The batch cap
max_num_seqs moves the operating point along the frontier (Demo 03 Part D, 24 requests/s):
- a cap of 16 gives the best TPOT (9.1 ms), but only 1,631 tokens/s, and requests queue (TTFT p99 69 s);
- 128 or more gives 4,354 tokens/s at a TPOT of 14.5 ms.
How much per-token latency to trade for capacity is a product decision as much as a systems one.
6. Prefix caching
6.1 Mechanism
If two requests share a prompt prefix, the KV of that prefix is the same, because attention is causal. So it can be computed once and reused. vLLM’s automatic prefix caching does this in four steps:
- Key every full block by a hash of (the previous block’s hash, this block’s tokens). The chain makes a block’s key depend on everything before it.
- Keep freed blocks that carry a hash in the cache, evictable in least-recently-used order.
- Look up a new request’s prompt block by block. Hits are referenced instead of recomputed. At least one prompt token is always recomputed, because the model must run on the last prompt token to produce the first output.
- Publish newly computed full blocks under their hashes.
kv_alloc.PagedAllocator implements exactly this, and the real engine uses it.
6.2 What it buys
Demo 04 Part A gives every request the same system prompt:
- with 4,096 shared tokens, caching cuts prefill work from 2.67M to 0.21M tokens;
- without it, 12 requests/s demand 53K prefill tokens/s against about 37K/s of prefill capacity. The GPU cannot keep up: TTFT p50 is 15 s, against 23 ms with caching. A cache can decide whether a GPU keeps up at all;
- TPOT barely moves (15.0 → 13.5 ms). The slide says it plainly: prefix caching “reduces prefill cost and therefore TTFT; it does not speed up decode”. Each decode step still reads the whole cache, shared or not.
Multi-turn chat is prefix-heavy by construction, because every turn re-sends the conversation (Demo 04 Part B, 200 conversations × 5 turns):
- 93% of prompt blocks are hits;
- prefill work falls from 1.70M to 0.12M tokens;
- TTFT p50 falls from 60 to 12 ms.
Agent loops that re-emit large structured contexts are the same.
6.3 What it needs
- Capacity. With a 60K-token KV pool instead of 427K, conversations’ blocks are evicted between turns: the hit rate falls to 59% (Demo 04 Part C). Hierarchical caches (host memory, SSD, remote stores: HiCache, LMCache, Dynamo’s KV block manager) extend the cache beyond HBM (Lecture 23).
- Routing. “A router that sends related requests to different workers wastes the cache” (Lecture 23’s KV-aware routing).
- Identical bytes. A prompt template that changes one early token (a timestamp, a reordered tool list) invalidates every block after it. The slide lists “prefix cache invalidation from prompt template mismatches” as a failure mode.
On the real engine (Demo 04 Part D), 32 requests sharing a 96-token system prompt reuse 2,304 cached tokens, so the engine computes 2,011 tokens instead of 4,315. The outputs are unchanged. The wall-clock gain is small on this CPU, where a prefill token is ~50× cheaper than a decode token.
7. Anatomy of a modern engine
7.1 The parts, and the tiny engine’s version of each
| component (vLLM) | what it does | in tiny_engine.py |
|---|---|---|
| API server, tokenizer, detokenizer | OpenAI-compatible endpoints, request validation, streaming | (requests are token lists) |
| scheduler | admission, token budget, chunked prefill, preemption | _schedule() |
| KV cache manager | blocks, tables, prefix hashes, eviction | kv_alloc.PagedAllocator |
| model runner: input preparation | flatten all scheduled tokens into one batch with positions and slot indices | start of forward() |
| model runner: forward | linear layers on the flat batch; attention kernels reading through block tables | forward() (per-sequence or batched decode attention) |
| sampler | logits processors, temperature/top-p, guided decoding masks | greedy argmax |
| executor, distributed | TP/PP/EP workers, collectives, CUDA graphs | (one CPU process) |
| metrics | queue depth, KV usage, TTFT/ITL histograms (Prometheus) | run() returns them |
7.2 One step, end to end
tiny_engine.step() is the whole loop of a modern engine in about 60 lines:
- schedule under the budget;
- flatten the work into one (T, d) batch;
- run every linear layer once on that batch, so the weights are read once for all tokens;
- write each token’s K and V into its slot;
- attend by gathering each sequence’s slots;
- sample the last token of each finished chunk.
Batching works on the CPU too (Demo 05 Part A). Serving 48 requests together gives about 11× the output tokens/s of serving them one at a time, with identical outputs.
7.3 Kernels and host overhead
Two measurements show why engines are more than schedulers.
- The engine is only as batched as its slowest kernel. With one attention call per sequence, a 64-sequence decode step costs 25.9 ms. One batched call over all 64 costs 3.2 ms (Demo 01 Part D), and the full engine shows the same gap (Demo 05 Part A). Attention backends such as FlashInfer and FlashAttention’s paged kernels are the GPU versions of that batched call.
- There is a fixed per-step tax. Forward time per step fits ≈ 0.96 ms + 0.06 ms per sequence. A decode token needs only ~2.6 MFLOP here, so the fixed part is not arithmetic: it is issuing 528 PyTorch operations from Python, plus index building (Demo 05 Part C). At batch 1, over 90% of the step is this tax.
The vLLM guest lecture (Lecture 23) gives the GPU version: decode steps take 5–10 ms, so “just 1 ms extra CPU overhead can cut performance by 20%”. That is why engines move input preparation onto the GPU, schedule one step ahead, and capture the forward in CUDA graphs.
8. Operating a service
8.1 Benchmark honestly
The slide’s five rules:
- use a realistic request mix: prompt and output lengths, concurrency, tool/JSON traffic;
- distinguish throughput mode from latency-constrained mode (§5.4);
- measure per-request metrics (TTFT, ITL percentiles) and fleet metrics (tokens/s/GPU, achieved concurrency, rejection rate);
- warm caches and graphs, but also benchmark cold-cache and cache-miss cases;
- test the feature combination you will ship: quantization + guided decoding + speculation + disaggregation, not each alone.
8.2 What to watch
| category | example metrics | why |
|---|---|---|
| admission / queueing | waiting requests, rejections, queue age | overload shows here before the GPU does |
| latency | TTFT, prefill time, decode time, TPOT, p95/p99 histograms | direct SLO health |
| KV memory | cache usage, reusable blocks, offload / reload rates | whether long-context traffic is sustainable |
| workload shape | prompt / output length, hit rate by prompt family | separates product changes from engine regressions |
| distributed health | all-to-all latency, transport errors, KV-transfer rate | TP / EP / PD bottlenecks (Lecture 23) |
| business | tokens/s/GPU, cost per request | turns systems wins into economics |
“Without telemetry, inference tuning degenerates into superstition.”
8.3 Capacity planning and the p99 killers
Capacity planning is no longer “how many replicas?”:
- classify traffic (short chat, long RAG, agent loops, structured output, multimodal);
- estimate prompt and output length distributions and the cache-reuse rate for each class;
- convert those into prefill capacity, decode capacity, active KV footprint and an acceptable queue;
- decide between a unified pool and disaggregated prefill/decode (Lecture 23);
- add margin for bursts, canaries and degradation.
The usual p99 killers, mostly fixed by scheduling, routing and phase separation rather than faster kernels:
- a long prompt admitted at the wrong time;
- a cache miss on a large prefix;
- MoE expert imbalance;
- speculative settings that eat the token budget;
- transport retries;
- host-side grammar or tool logic stalling the stream.
Debugging, symptom → subsystem (from the slide):
| symptom | likely bottleneck | first questions |
|---|---|---|
| high TTFT, stable ITL | prefill, tokenization, cache misses | longer prompts? hit rate fell? prefill saturated? |
| good medians, awful p99 ITL | scheduler interference or transport stalls | long prefills interrupting decodes? collectives spiking? |
| OOM or low concurrency | KV footprint, fragmentation, offload policy | resident context exploding? block size or reuse wrong? |
| speculation gives nothing | poor acceptance or budget pressure | acceptance rate? drafts eating the budget? |
| disaggregation regresses | transfer or routing overhead | KV transfer fast enough? requests placed with affinity? |
8.4 Three deployment recipes
- Small or medium model, straightforward traffic: one engine pool with continuous batching, prefix caching and good metrics.
- Long-context interactive assistant: chunked prefill, strong prefix caching, maybe a remote KV tier, and careful p99 monitoring.
- Large reasoning or MoE service at scale: expert parallelism with data-parallel attention, disaggregated prefill and decode, a cache-aware router, separate pools, and rigorous KV and transport accounting (Lecture 23).
“PD, remote KV and complex gateways add operational surface. Use them when the workload demands it, not because they look good on a diagram.”
9. Summary
- Prefill is compute-bound, decode memory-bound. A step turns compute-bound above a few hundred tokens (237 for Llama-3-8B on an H100 here). Batching decodes and chunking prefills both aim at that knee.
- TTFT is prefill plus queueing; TPOT is decode-step time. Users feel tails and stalls, so serve against p99 SLOs and measure goodput.
- The KV cache is the working set. Bytes per token = 2·L·H_kv·d_h·b. KV memory, not compute, caps concurrency.
- Paging (blocks, tables, on-demand growth, reference counts, copy-on-write) wastes at most a block per sequence. Here it ran 293 requests where reservations ran 125. Preemption by recompute handles overflow, but admission must check free blocks, or the scheduler can livelock.
- Continuous batching with chunked prefill is the modern default. It removes static batching’s head-of-line blocking and prefill priority’s stalls. The token budget trades stalls against TTFT, and the scheduler sets the capacity under an SLO (20/s vs 12/s here).
- Prefix caching saves prefill (TTFT), not decode. It needs capacity, cache-aware routing and byte-identical prefixes.
- An engine is scheduler + KV manager + model runner + sampler + metrics, and its kernels and host overhead decide whether batching pays.
10. Common pitfalls
- Benchmarking at infinite load with perfect reuse and reporting it as interactive performance.
- Reserving max length per request. Concurrency, not FLOPs, is the first casualty.
- Comparing schedulers without fixing the token budget, or reading only p99 when stalls are rarer than 1%. Look at each request’s worst gap.
- Admitting work without checking free blocks: preemption thrash or livelock.
- Expecting prefix caching to speed up decoding. It makes TTFT faster; TPOT stays.
- Changing an early token of a prompt template (a timestamp, a reordered tool list) and losing every cached block after it.
- Counting the model’s FLOPs and forgetting the host. At small batch, per-step overhead can be most of the step (Demo 05 Part C).
- Tuning one feature at a time. Speculation, guided decoding, quantization and chunking interact through the same budget (Lecture 23).
11. Exercises
-
KV accounting. Llama-3-70B (80 layers, 8 KV heads, head dim 128) on 8 H100s with FP8 weights (70 GB) and an FP8 cache. With 90% of HBM usable, how many 32K-token sequences fit?
Answer
KV per token in FP8 = 2·80·8·128·1 = 163,840 B. Free = 0.9·640 GB − 70 GB = 506 GB. Per 32K sequence: 32,768 · 163,840 = 5.37 GB → 94 sequences. In BF16 KV it would be 47. -
The knee. At what decode batch does a Llama-3-8B decode step at context 1,000 turn compute-bound on an ideal H100 (989 TFLOP/s, 3.35 TB/s, no efficiencies)? Ignore attention FLOPs.
Answer
Bytes ≈ 16 GB + B·1,000·131 KB = 16e9 + 1.31e8·B. FLOPs ≈ 16e9·B. Equal times: 16e9 B/989e12 = (16e9 + 1.31e8 B)/3.35e12 → 1.62e-5 B = 4.78e-3 + 3.9e-5 B. Since 3.9e-5 > 1.62e-5, there is no solution. At context 1,000 the KV reads grow faster with B than the math does, so decode never turns compute-bound. Only short contexts (or MLA-sized caches) reach the knee. This is why Demo 01 shows 256 decodes still memory-bound. -
Static batching’s waste. A static batch of 8 requests has outputs of 50, 60, 70, 80, 90, 100, 110 and 2,000 tokens. What share of decode-slot-steps is padding?
Answer
Steps = 2,000, slots = 8 → 16,000 slot-steps. Useful = 50+60+…+110 + 2,000 = 560 + 2,000 = 2,560. Padding = 84%. Continuous batching would let seven other requests use those slots. -
Choosing a token budget. With step time ≈ 7 ms + 0.027 ms per prefill token, and a TPOT SLO of 30 ms, what is the largest budget that keeps every step (and so every ITL) under the SLO? What does it cost a 10,000-token prompt?
Answer
7 + 0.027·b ≤ 30 → b ≤ 850 tokens. The prompt takes ⌈10,000/850⌉ = 12 steps ≈ 12 × 30 ms = 0.36 s of TTFT, plus waiting, instead of one 277 ms step that would stall everyone. -
Prefix cache hit rate. A 2,000-token system prompt is followed by a 300-token user part, with 16-token blocks. What fraction of each prompt’s blocks can hit? And if a timestamp is inserted at token 10?
Answer
Full shared blocks: ⌊2,000/16⌋ = 125 of ⌈2,300/16⌉ = 144 → 87%. With a timestamp at token 10, block 0 differs between requests, and because the hashes are chained, every later block differs too: 0%. Put variable content at the end of the prompt. -
Recompute or swap? Llama-3-8B on an H100: recomputation runs at ~37K tokens/s, and PCIe moves 64 GB/s per direction at 128 KiB of KV per token. Per token, which is faster, and why might an engine still recompute?
Answer
Recompute: 27 µs per token. Swap out + in: 2 × 131 KB / 64 GB/s = 4.1 µs. Swap is ~6× cheaper per token, but it needs host memory, contends with other transfers, and adds complexity, while recompute can hit the prefix cache (often a large part of the victim) and uses an otherwise-saturated GPU only when memory frees up. vLLM V1 chose recompute. -
Goodput. Two configurations: A serves 4,000 tok/s with 70% of requests meeting the SLO; B serves 3,500 tok/s with 98%. Average output: 200 tokens. Which has the higher goodput?
Answer
A: 4,000/200 = 20 req/s × 0.70 = 14 req/s. B: 17.5 × 0.98 = 17.2 req/s. B wins on goodput despite lower throughput. -
Why does chunked prefill lower TPOT, not only stalls? In Demo 03 Part A, the TPOT p50 is 9.9 ms with chunking vs 12.7 ms with prefill priority. Explain.
Answer
TPOT averages every gap of a request. Under prefill priority some of those gaps are whole prefill steps (tens to hundreds of ms), which raise the mean even when they are rare. With chunking every gap is one mixed step, bounded by the budget. Chunking also mixes prefill tokens into decode steps, filling the memory-bound decode steps with compute that is almost free there.
12. The related assignment (concepts only)
Assignment 4 (Inference and Serving) exercises exactly these mechanisms. Typical tasks are to measure TTFT and TPOT under load, explain a latency–throughput curve, and reason about KV memory, batching and caching.
The concepts to bring:
- every number needs a load level and a percentile;
- compute KV bytes per token before choosing batch sizes;
- separate prefill and decode costs when explaining any latency;
- check that an optimization keeps outputs identical (the tiny engine’s contract).
No solutions are given here.
13. Research directions
- SLO-aware scheduling: per-request deadlines; schedulers that maximize goodput rather than throughput; fairness between tenants.
- Predicting output lengths: shortest-job-first approximations without knowing the length; preemption policies that use predictions.
- Memory hierarchies for KV: what to keep in HBM, host memory or SSD, and when to prefetch (agents with tool calls of known duration; Lecture 23).
- Batch-invariant kernels: engines whose outputs do not depend on what else is in the batch (Lecture 19’s nondeterminism problem, at serving time).
- Hybrid and sparse attention (Lecture 15): new cache shapes (Mamba states, sliding windows) need allocators that mix block types without fragmentation. vLLM’s hybrid allocator reports 0–12% waste.
14. Further reading
- Kwon et al. 2023 (vLLM) §3–§4 for paging, sharing and preemption; Yu et al. 2022 (Orca) for iteration-level scheduling; Agrawal et al. 2024 (Sarathi-Serve) for chunked prefill and stall-free schedules.
- The vLLM docs on the V1 scheduler, automatic prefix caching, and metrics; TensorRT-LLM’s performance-tuning guide.
- Pope et al. 2023 for the inference cost model at scale (latency vs throughput across partitioning choices).
15. Next lecture
Lecture 23, Inference Engines in Practice, opens up the real engines: vLLM’s CPU-overhead work (async scheduling, CUDA graphs), SGLang’s RadixAttention, TensorRT-LLM’s wide expert parallelism and its guided + speculative decoding case study, and Dynamo’s distributed control plane. That plane covers disaggregated prefill and decode, KV-aware routing, KV offload tiers and an SLO-driven planner. It takes this lecture’s single engine to a fleet.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| serving stack / inference engine | 推理服务栈 / 推理引擎 |
| prefill / decode | 预填充 / 解码 |
| time to first token (TTFT) / time per output token (TPOT) | 首词元时延 / 每输出词元时间 |
| inter-token latency (ITL) / stall | 词元间隔时延 / 卡顿 |
| throughput / goodput / SLO | 吞吐量 / 有效吞吐 / 服务等级目标 |
| tail latency / p99 | 尾延迟 / 第 99 百分位 |
| KV cache / working set / concurrency | 键值缓存 / 工作集 / 并发数 |
| internal / external fragmentation | 内部 / 外部碎片 |
| PagedAttention / block / block table | 分页注意力 / 块 / 块表 |
| reference count / copy-on-write | 引用计数 / 写时复制 |
| preemption / recompute / swap | 抢占 / 重算 / 换出 |
| admission control / livelock | 准入控制 / 活锁 |
| static batching / continuous batching / iteration-level scheduling | 静态批处理 / 连续批处理 / 迭代级调度 |
| prefill priority / head-of-line blocking | 预填充优先 / 队头阻塞 |
| chunked prefill / token budget | 分块预填充 / 词元预算 |
| latency–throughput frontier | 延迟–吞吐前沿 |
| prefix caching / hash chain / LRU eviction / hit rate | 前缀缓存 / 链式哈希 / LRU 淘汰 / 命中率 |
| scheduler / KV manager / model runner / sampler | 调度器 / 键值缓存管理器 / 模型执行器 / 采样器 |
| input preparation / host overhead | 输入准备 / 主机端开销 |
| capacity planning / observability | 容量规划 / 可观测性 |