Lecture 23 · Inference Engines in Practice: vLLM, SGLang, TensorRT-LLM, Dynamo

Scalable AI: Bridging Theory, Understanding, and Practice · Lecture 23。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: UC Berkeley EE 290/194 Scalable AI:

  • Fall 2026 Lectures 19–20 (slides not public when these notes were written);
  • Spring 2026 Lecture 19, two guest lectures from NVIDIA: TensorRT LLM (Jun Yang, on behalf of the TensorRT-LLM team; lecture_19_1.pdf) and Inference at Scale (NVIDIA Dynamo; lecture_19_2.pdf);
  • Spring 2026 Lecture 20, first part: vLLM: Efficient LLM Inference Engine (Woosuk Kwon, Inferact; lecture_20_1.pdf). The second part’s slides were not downloadable.

Recommended reading:

  • Engines: the vLLM V1 and Anatomy blogs; Zheng et al., SGLang: Efficient Execution of Structured Language Model Programs (RadixAttention, NeurIPS 2024); the TensorRT-LLM blogs Scaling Expert Parallelism in TensorRT LLM (parts 1–3) and Combining Guided Decoding and Speculative Decoding.
  • Distributed serving: Zhong et al., DistServe (OSDI 2024); Patel et al., Splitwise (ISCA 2024); Qin et al., Mooncake (FAST 2025); the NVIDIA Dynamo docs.
  • Structured output: Dong et al., XGrammar (arXiv:2411.15100).
  • MoE serving: DeepSeek-AI, DeepSeek-V3 §3.4 (deployment, EPLB).

Code: code/lecture23/ contains:

  • radix.py (a radix-tree prefix cache and a block-hash cache), fleet_sim.py (replicas, routers, disaggregated pools), grammar.py (grammar → token masks, guided + speculative decoding);
  • six demos: host overhead and CUDA graphs, RadixAttention, KV-aware routing, disaggregation, MoE and EPLB, guided + speculative decoding.

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:

  1. Place each framework in the stack: runtime engines (vLLM, SGLang, TensorRT-LLM), control planes (Dynamo, gateways) and KV tiers (LMCache, HiCache, Dynamo’s KV block manager).
  2. Explain why CPU overhead matters at decode speed, and what asynchronous scheduling, GPU-side input preparation and CUDA graphs (full and piecewise) do about it.
  3. Explain RadixAttention and cache-aware scheduling, and when token-level reuse matters.
  4. Design routing for replicas with prefix caches: why load balancing wastes caches, why pure affinity creates hot spots, and what a KV-aware cost does.
  5. Decide when to disaggregate prefill and decode: interference vs transfer, rate matching, link budgets, per-phase parallelism.
  6. Reason about MoE serving: wide expert parallelism, all-to-all, load imbalance, EPLB.
  7. Combine features correctly: guided decoding with speculative decoding and CUDA graphs.

0.2 Prerequisites and scope

  • Prerequisites:
    • Lecture 22: one engine, its scheduler, paged KV, prefix caching;
    • Lecture 21: speculative decoding;
    • Lectures 4–6: MoE, expert and tensor parallelism.
  • Scope: what production engines add on top of Lecture 22’s single engine, and how many engines become a fleet.
  • Not in scope: hardware built for decode (Lecture 24); context engineering for applications (Lecture 25).

0.3 Section → code map

SectionIdeaCode in code/lecture23/
§2vLLM: CPU overhead, CUDA graphs, parallelism01_host_overhead_and_graphs.py
§3SGLang: RadixAttention, cache-aware schedulingradix.py, 02_radix_cache.py
§4Dynamo: routing, planning, KV tiersfleet_sim.py, 03_kv_aware_routing.py
§5disaggregated prefill and decodefleet_sim.py, 04_disaggregation.py
§6TensorRT-LLM: wide EP and EPLB05_moe_and_eplb.py
§7feature combinations: guided + speculative decodinggrammar.py, 06_guided_and_speculative.py

0.4 What is modelled and what is measured

  • Fleet and MoE numbers are computed. They come from Lecture 22’s step model, which now includes tensor-parallel all-reduces (two per layer, 8 µs + bytes / 450 GB/s), and its engine simulator, run as many replicas on one clock.
  • Some numbers are measured on this CPU:
    • the radix-tree and block-cache hit rates on synthetic token streams (exact counts);
    • the host-overhead measurements;
    • guided + speculative decoding with Lecture 21’s real parent and draft models.

1. The landscape: engines, control planes, cache tiers

The Spring 2026 framework lecture’s summary: “The serving problem is not faster kernels; it is orchestrating prefill, decode, routing and KV memory under variable workloads.” The stack has split into layers that evolve separately. The TensorRT-LLM lecture draws the ecosystem in three levels:

levelexamplesjob
serving / control planeNVIDIA Dynamo, Triton Inference Server, Shepherd Model Gateway, llm-drouting, planning, autoscaling, multi-node orchestration, KV tiers
enginevLLM, SGLang, TensorRT-LLMone replica’s scheduler, KV manager, model runner
librarycuBLAS/cuDNN, DeepGEMM, DeepEP, FlashMLA, FlashInfer, NCCL, NIXL, Mooncake transfer enginekernels and communication

And the frameworks, as the Spring 2026 lecture compares them:

stackthink of it asstrengthstypical fitwatch-outs
vLLMgeneral open engineportability, community, many model familiesresearch to productionmay not be peak on one vendor’s path
SGLangoptimized serving stackMoE, PD, gateway, structured output, HiCachefrontier deployments, agentic trafficecosystem evolving; large operational surface
TensorRT-LLMNVIDIA-specialized runtimepeak NVIDIA performance, overlap scheduler, quantizationNVIDIA-only productionfeature-combination caveats, less portable
Dynamodistributed control planeresource planning, smart routing, KV tieringmulti-node reasoning servingneeds a runtime engine underneath
LMCacheKV layerlong-context reuse, offload, cross-engine KVcache-heavy or PD systemsonly helps if the workload has reusable KV

The design pattern is composable: specialized engines inside a larger serving and KV-management architecture. “Clients → gateway / smart router → prefill pool and decode pool, with a control plane (autoscaling, planning) and a KV tier (HBM + host + remote).”


2. vLLM: a clean core with zero CPU overhead

2.1 Why the CPU matters

The vLLM lecture names four ways the engine optimizes inference:

  1. minimizing CPU overheads;
  2. efficient GPU kernels;
  3. model parallelism;
  4. memory management and caching.

The first is the least obvious:

  • “In LLM inference, each step is very fast: just 5–10 ms (100–200 tok/s); in training, each step is 100 ms–1+ s. Even a small overhead matters: just 1 ms extra CPU overhead can cut performance by 20%. Unfortunately, 1 ms overhead is pretty easy to hit in Python.”
  • And: “Python/PyTorch overhead takes up to 50% of overall latency.”

Demo 01 Part A prices it (Llama-3-8B decode on an H100, context 2,000):

  • at batch 1 the GPU’s work is 6.1 ms per step;
  • 1 ms of synchronous CPU work (scheduling, preparing inputs) leaves the GPU idle 14% of the time; 2 ms, 25%;
  • at batch 256 the step is 31 ms and the same 1 ms costs 3%.

Host overhead matters most exactly where latency matters most, at small batch.

2.2 The fixes

  • Rewrite the API server in Rust (tokenization, HTTP, streaming), off the engine’s critical path.
  • Asynchronous scheduling: schedule and prepare step N+1 while the GPU executes step N (the idea of NanoFlow). As long as the CPU’s part is shorter than the GPU’s, it disappears from the critical path (Demo 01 Part A: 0% idle with async). vLLM ensures zero synchronization, so the GPU is never stalled by the CPU.
  • Asynchronous detokenization.
  • GPU-native input preparation (“MRV2”). Building the flat batch, block tables, positions and sampling parameters used to be many small PyTorch ops on the CPU; it is now custom Triton kernels. A side benefit: the preparation kernels can read the result of the previous step’s rejection sampling on the GPU, which makes async scheduling compatible with speculative decoding.
  • CUDA graphs: record a whole sequence of kernel launches once, then replay it with a single launch.

Lecture 22’s tiny engine shows the same tax on a CPU. Its forward time per step is ~0.96 ms + 0.06 ms per sequence; the fixed part is issuing ~500 PyTorch operations, not arithmetic (Lecture 22, Demo 05). Here (Demo 01 Part C) one tiny eager operation costs about 0.9 µs and a forward issues ~500 of them.

2.3 Full vs piecewise CUDA graphs

A full CUDA graph captures the entire model: minimal CPU overhead, but static shapes and no CPU work during execution. LLM inference is dynamic:

  • every step mixes prefills and decodes differently;
  • kernel heuristics are decided at run time (cascade attention for shared prefixes);
  • CPU offloading needs CPU operations mid-forward.

With full graphs the options were “abandon CUDA graphs (sacrificing performance) or write special GPU kernels to work around it (sacrificing simplicity)”.

vLLM’s answer is piecewise CUDA graphs:

  • torch.compile splits the model at the attention op;
  • the token-wise, stateless parts (projections, MLP, norms) run as captured graphs;
  • attention, which is dynamic, stateful and complex, runs in eager PyTorch.

The lecture’s measurements (input 4K, output 50, H100): piecewise is 6–39% faster than eager, 2–7% slower than a full graph in the worst case, and 0–2% slower for batch ≥ 8.

Demo 01 Part B models one decode step’s 419 kernels (from Lecture 2’s roofline) under stated launch costs:

batchGPU workeagerpiecewisefull graph
14.88 ms6.90 ms5.62 ms4.90 ms
649.93 ms11.69 ms10.42 ms9.94 ms

The model reproduces the shape. Eager is worst at small batch, where kernels are shorter than launches, and graphs matter less as kernels grow, so vLLM captures one graph per batch-size bucket. With my assumed 15 µs per graph replay, piecewise is 14.7% over full at batch 1; with 5 µs launches, 4.7%, inside the slide’s measured range. The launch costs are assumptions, so trust the measured gap.

Plan vs reality: torch.compile on a CPU. Compiling the parent’s forward with torch.compile here took 10.6 s the first time (2.1 s once cached). It produced a forward that is slower than eager (1.89 vs 1.18 ms). On a GPU, compilation’s value comes mostly from fusing memory-bound ops and capturing graphs, which a CPU run cannot show. Measure on the target.

2.4 Kernels

vLLM delegates complex, performance-critical kernels to libraries:

  • attention backends behind an AttentionBackend abstraction (FlashInfer, FlashAttention, FlashMLA);
  • MoE behind a FusedMoE abstraction;
  • memory-bound glue (RMSNorm, RoPE) fused automatically by torch.compile or written by hand.

The lecture’s example is DeepSeek-V3.2, whose many small ops are fused into a few kernels. Lecture 22’s measurement makes the general point: an engine is only as batched as its slowest kernel. One attention call per sequence made a 64-sequence decode step 8× slower than one batched call.

2.5 Parallelism at serving time

The vLLM lecture’s summary of the options:

parallelismwhat is split+−
data (DP)replicas, requestsno communicationno memory saving, no latency reduction
tensor (TP)weights of each linear layerlower latency if the network is fast; KV split tooheavy communication (needs NVLink); limited by the number of KV heads
expert (EP)MoE expertskernel-friendly, less communication than TPonly for MoE layers (attention needs another scheme, e.g. DP); load imbalance
context (CP)the sequence dimensionbalances KV of very long sequencesno parameter saving; requests must be balanced
pipeline (PP)layersleast communicationhigher latency, stage imbalance

The networks differ by 36×: NVLink 1.8 TB/s, InfiniBand 50 GB/s. Large models mix the schemes. The lecture’s case study, Kimi K2.5 in NVFP4 on GB200 with 8K input and 1K output:

  • high throughput: disaggregated, with prefill as 10 × DEP4 (DP attention + EP over 4 GPUs) and decode as 1 × DEP24;
  • low latency: colocated TEP4.

vLLM’s hybrid memory allocator serves models that mix full attention with sliding-window or linear attention (Gated DeltaNet; Qwen3.5, GPT-OSS). Instead of statically partitioning memory per layer type, it partitions dynamically and adjusts block sizes; the lecture reports 0–12% waste for all open models.


3. SGLang: RadixAttention and cache-aware scheduling

3.1 The radix tree

SGLang keeps the KV of every request (prompt and output) in a radix tree: a compressed trie whose edges are token sequences and own their KV slots.

  • A new request walks down from the root as far as its tokens match. That path’s KV is reused, and the rest is computed and inserted, splitting an edge where the request diverges.
  • Running requests lock their path; eviction removes least-recently-used unlocked leaves.

Shared system prompts, few-shot examples, multi-turn histories, parallel samples and tree-of-thought branches all become shared paths, automatically. radix.py implements exactly this: split on match, insert, lock/unlock, LRU leaf eviction.

3.2 Measured on four workload shapes (Demo 02)

With an unlimited cache:

workloadradix hit16-token block hit
multi-turn chat92.7%92.1%
few-shot (fixed order)93.2%91.8%
tree of thought86.5%85.0%
agent loop (system prompt + tool schemas + growing trajectory)90.5%90.3%

Three lessons:

  • These workloads are mostly reuse. Agents and chat re-send their whole context every step.
  • Token vs block granularity moves hit rates by at most 1.5 points, but the remaining work is small, so the radix tree computes 2–17% fewer prompt tokens. Most for few-shot, whose shared parts end mid-block: each block-matched request recomputes up to 15 tokens. The bigger wins of RadixAttention are structural: outputs, branches and the scheduler.
  • Prefixes must be identical. Shuffling the few-shot examples per request drops the hit rate from 93% to 40%. Prompt construction is a performance decision: fixed order, variable parts last.

3.3 Cache-aware scheduling

When the cache is smaller than the working set, the order in which requests run decides what is still cached. SGLang’s longest-prefix-match (LPM) policy sorts the queue by how much of each request is already cached, so requests sharing a prefix run together, before it is evicted. With a cache holding 20% of the distinct tokens (Demo 02 Part C):

workloadFCFS hitLPM hit
multi-turn chat50.0%68.5%
agent loop54.6%69.2%
tree of thought86.5%83.7%

LPM is not free:

  • it can lose: on tree-of-thought, reordering changed which prefixes were evicted, for the worse;
  • it can starve requests that match nothing.

A real scheduler needs a fairness bound. The scheduler and the cache are one design.

3.4 Beyond one GPU’s memory

SGLang’s HiCache (and LMCache, and Dynamo’s KV block manager, §4.4) extends the cache hierarchically: hot pages in HBM, warm pages in host memory, colder history on disk or a remote store. The Spring 2026 lecture quotes HiCache at up to 6× throughput and large TTFT reductions in long sessions. The challenge is to preserve reuse without letting rehydration latency destroy TTFT or ITL.


4. NVIDIA Dynamo: the control plane

4.1 Goals

The Dynamo lecture opens with the inference Pareto frontier: throughput vs inverse latency vs quality. Its message is “good model + good system == success”. It then sets three principles:

  1. KV should not be recomputed: routing, KV block management, KV transfer.
  2. Scale with real-time load: autoscaling, modelling prefill and decode performance, fast model start.
  3. Tolerate faults in any component: discovery, removal, high availability.

4.2 Architecture

  • an OpenAI-compatible API server;
  • a KV-aware router;
  • an SLO-based planner;
  • disaggregated serving: context (prefill) and generation (decode) workers, each running vLLM, SGLang or TensorRT-LLM;
  • a KV block manager (KVBM) with tiers G1 GPU memory, G2 host memory, G3 local disk/SSD, G4 external storage;
  • NIXL, a transfer library with backends for UCX, GPUDirect Storage, POSIX, 3FS and Mooncake, picked automatically;
  • Grove, Kubernetes gang scheduling with topology-aware placement for multi-node replicas;
  • Model Express: weights served from a GPU memory service, so a restarting worker re-attaches instead of reloading from disk.

4.3 KV-aware routing (Demo 03)

A traditional load balancer (nginx, round robin, least connections) “doesn’t know where the KV is”. Dynamo’s router keeps an index of every worker’s cached blocks (from KV events the workers publish). It scores each worker by prefix overlap against load. The slide’s example: worker 1 has a 50% match and 40% load, worker 3 a 90% match and 97% load.

With cost = (share of the prompt to compute) + w × load (Demo 03 Part A):

  • w = 0 picks worker 3;
  • w = 1 picks worker 1.

The weight is a policy: how much recomputation one unit of load is worth.

Eight Llama-3-8B replicas with prefix caches serve 1,200 multi-turn conversations from 8 tenants (each with a 2,000-token system prompt), 30 new conversations per second:

routerprompt-token hitprefill computedTTFT p99
round robin89%1.33M66 ms
least loaded80%2.43M68 ms
session (sticky by conversation)94%0.70M66 ms
cache affinity only95%0.59M19 ms
KV-aware (cache + queued prefill)95%0.63M19 ms

Round robin caches the tenants’ system prompts everywhere and the conversation histories nowhere. Session stickiness keeps conversations together, but hashing ignores the tenant: a conversation’s first turn finds its system prompt cached only by chance, and those cold prefills set the p99. Least-loaded is the worst: it actively spreads related requests apart.

Then give one tenant half of all traffic (Part C). Pure cache affinity piles that tenant onto the replica holding its prompt:

  • load spread 4.95× the mean;
  • TTFT p99 16 s;
  • its hit rate even falls to 89%, as the overloaded replica evicts.

The KV-aware cost’s queue term copies the hot prompt to more replicas: spread 1.71, TTFT p99 22 ms, hit rate 95%. An LLM router must see inside the engines, both caches and queues. Generic load balancing throws away the cache; pure affinity throws away the balance.

Multimodal inputs break naive prefix caching: image placeholder tokens are identical token IDs for different images. Dynamo adds a multimodal hash to the cache key (lookup(tokens, mm_hash)), and can disaggregate encode, prefill and decode (E/P/D) with an embedding cache.

4.4 Planning, KV tiers, agents

  • The planner autoscales prefill and decode pools against TTFT and TPOT SLOs. It uses a load predictor (ARIMA/Prophet), an interpolator over profiled performance, and correction factors. The slide reports Alibaba’s results: 80% fewer TTFT breaches and 75% fewer TPOT breaches with 5% fewer GPUs. In the lecture’s sinusoidal-load experiment (Qwen3-32B on H20, TTFT SLO 1 s, ITL 30 ms), tuned correction factors further cut breaches.
  • The KV block manager: with real KV pressure, offloading to host memory (G2) and reusing it instead of recomputing lowered TTFT (the slide shows −31% on a Mooncake trace with Qwen3-32B on H100). Cheaper tiers (G3 disk, G4 file store) extend it further. “KVBM needs real KV pressure to shine.”
  • Agents give structure to exploit. An agent’s LLM call is followed by a tool call of known kind and roughly known duration (the slide: 30 s). The engine can offload the KV to host memory during the tool call and prefetch it back before the next call, instead of evicting and recomputing it.
  • Fault tolerance: request migration at the token level, so a failed decode worker loses no request; average worker pod recovery ~3 min, sped up by peer-to-peer transfer of weights and CUDA-graph caches.

4.5 A worked deployment

The lecture’s tutorial starts from one engine and adds Dynamo features one at a time: Qwen3-32B, vLLM backend, 16 GPUs, a Mooncake conversation trace. Its AIConfigurator searches configurations against an SLA in under 30 s. It recommended aggregated 8 × TP2, or disaggregated 8 prefill workers at TP1 + 1 decode worker at TP8. In the slide’s results, the KV router helps both layouts’ latency, and disaggregation improved goodput by 32% on this workload. The trade-off is TTFT vs ITL.


5. Disaggregated prefill and decode

5.1 Why split the phases

Prefill is compute-bound and throughput-oriented; decode is memory-bound and latency-sensitive (Lecture 22). Run in the same engine, a prefill step stalls every decode stream; chunked prefill bounds the stall but does not remove it. Disaggregation runs the phases on different worker pools:

  • independent scaling of prefill and decode capacity;
  • per-phase parallelism and placement: TP1 prefill replicas for throughput, a TP8 decode replica for latency;
  • stronger control of the tail ITL.

The cost: every request’s KV must cross a link, once.

The slide’s inequality:

PD helps if Δt(interference avoided) > t(KV transfer) + t(orchestration) + t(placement mistakes).

PD is attractive when:

  • prompts are long and variable;
  • decode latency matters (chat, agents, voice);
  • concurrency is high enough for specialization to pay off;
  • the interconnect is fast.

5.2 The terms, measured (Demo 04 Part A)

For Llama-3-70B with FP8 weights on TP4, 64 decodes at a 4,000-token context:

  • a decode-only step takes 17.2 ms;
  • a 512-token prefill chunk adds 7.1 ms, and a 2,048-token chunk 66.6 ms.

That interference is paid on every step a prefill shares. The transfer is paid once per request. A 4,000-token prompt’s KV is 1.31 GB:

  • 3 ms over NVLink;
  • 26 ms over 400 Gb/s InfiniBand;
  • 105 ms over 100 GbE;
  • 1.05 s over 10 GbE.

5.3 Four ways to use 8 GPUs (Demo 04 Part B)

Long prompts (median 4,000 tokens); SLO: TTFT ≤ 2 s and TPOT ≤ 15 ms.

req/slayoutTTFT p99TPOT p99meet SLO
4colocated 4 × TP21.13 s25.2 ms0%
4colocated 2 × TP40.91 s16.1 ms90%
4disagg 2 × TP2 prefill + 1 × TP4 decode1.42 s13.1 ms100%
6colocated 2 × TP41.03 s21.5 ms23%
6disagg 2 × TP2 + 1 × TP43.01 s15.0 ms82%
6disagg 3 × TP2 + 1 × TP2 (mismatched)1.13 s213 ms (64 preemptions)0%
8colocated 2 × TP41.57 s22.7 ms7%
8disagg 2 × TP2 + 1 × TP413.3 s15.2 ms5%
  • Disaggregation gives the best per-token latency at every load. Its decode GPUs never run a prefill, and the layout gets a TP4 decode replica with TP2 prefill replicas.
  • Its weakness is the fixed split. Only 4 GPUs prefill, so when traffic grows the prefill pool saturates and TTFT explodes.
  • A mismatched split is worse. The 3 + 1 × TP2 layout has a decode pool too small for its prefill pool: it runs out of KV memory, preempts, and thrashes.

Rate matching P:D to the traffic is the whole game. TensorRT-LLM’s methodology computes the speed-of-light (SOL) throughput of each phase separately, sets the P:D ratio so the prefill request rate is at least the decode rate, then measures end to end and targets ≥90% of the rate-matched SOL. Dynamo’s planner moves GPUs between pools as the mix changes.

The link (Part C). The pause between a user’s first token (from the prefill pool) and second token (from the decode pool, after the transfer and a wait for a decode slot) has a p99 of:

  • 41 ms over NVLink;
  • 106 ms over InfiniBand;
  • 3.1 s over 10 GbE, where only 48% of requests meet the SLO.

“Don’t discuss PD disaggregation without discussing KV layout compatibility and transfer budget.” Production transports (NIXL, Mooncake, UCX) and layer-by-layer streaming of KV during prefill shrink this.

Short prompts (Part D). With 300-token prompts the interference PD removes is small. Colocated 2 × TP4 matches it (TPOT p99 10.1 vs 10.4 ms, both 100% within SLO). PD is for long, variable prompts with tight decode latency, not a default.

Plan vs reality. My first comparison used Llama-3-8B on 8 TP1 GPUs and found no win for disaggregation at all. Chunked prefill with a 512-token budget already piggybacks prefill tokens on memory-bound decode steps almost for free. The win appeared only with a large model, long prompts, a tight TPOT SLO, and per-phase parallelism, which needed tensor-parallel communication in the cost model. That is the regime in which DistServe, Dynamo and the TensorRT-LLM team report gains.


6. TensorRT-LLM: peak performance and wide expert parallelism

6.1 Principles and methodology

TensorRT-LLM’s design principles:

  • performance first;
  • modularization, to try performance ideas quickly;
  • usability and robustness, to collect production feedback.

The PyTorch backend has been the default since version 1.0.

Its performance methodology is the Pareto curve: throughput per GPU vs tokens/s per user, from the max-throughput end through throughput at a latency target to the low-latency end. Every optimization is judged by where it moves the curve. “The best optimizations come from understanding where the bottleneck moves on the Pareto curve.”

6.2 Wide expert parallelism

With small EP, MoE layers all-gather hidden states to every GPU, although at most top-k need each token. With wide EP (EP 32 and more on a GB200 NVL72 rack), hidden states go only to the ranks holding the selected experts. That is an all-to-all-v pattern, which the rack’s multi-node NVLink keeps fast.

The team’s performance study found where the gain comes from:

  • not memory capacity: there was “no benefit from GB200 memory capacity”;
  • but the expert GroupGEMM time, which is memory-bandwidth-bound in the middle of the Pareto curve and shrinks as each GPU holds fewer experts;
  • with the all-to-all kept close to small-EP cost.

The slide’s results: EP32 vs EP4 gives up to 8× speedup at 36 tokens/s/user and 2.7× at 30.

Demo 05 models a DeepSeek-V3-like layer: 256 experts, top-8, FP8, 256 decode tokens per GPU, B200 with 900 GB/s NVLink.

  • Memory per GPU. Each GPU’s expert weights fall from 82 GB (EP 8) to 10 GB (EP 64), freeing HBM for KV.
  • Speed. The MoE layer time falls from 225 µs (EP 8) to 116 µs (EP 32), while the all-to-all stays 49 µs.
  • Then imbalance wins. With skewed expert popularity, the busiest rank gets 1.23× the mean load at EP 8 but 2.51× at EP 64, and EP 64 is slower than EP 32 (150 µs). The layer waits for its slowest rank.

6.3 Scaling every kernel, and balancing the experts

Two lessons from the slides:

  • Every kernel must scale with EP. As expected, MoE GEMM time decreased and attention scaled, but communication and some MoE kernels did not. Before the MoE GEMMs, M tokens are expanded to M × top-k rows; on average only 1/EP of them are routed to this rank. Kernels that launched thread blocks for all rows wasted most of them: 98% idle at EP 64 (Demo 05 Part C). The fix launches blocks only for valid tokens, with persistent blocks so the data-dependent count stays CUDA-graph compatible.
  • Expert load imbalance. Hot experts differ by layer, by iteration and by dataset, and the slowest rank delays all the others. The fix is an expert-level load balancer: replicate hot experts and re-place them by load. It updates a few layers per iteration, so the whole model is re-balanced over several iterations.

vLLM and DeepSeek do the same (EPLB). On the vLLM slide’s example, rank loads of 14K vs 2K tokens become 8K and 8K.

Demo 05 Part B: with 32 replicas of the hottest experts placed by load, EP 64’s imbalance falls from 2.51 to 1.07 and its MoE layer from 150 to 92 µs (1.63×), so wide EP keeps paying. But at EP 8 EPLB is a loss (0.91×). Imbalance was mild there, and every extra replica is more weights for memory-bound GEMMs to read. A placement is also only as good as its loads: after the expert mix shifts, the old placement’s imbalance is 1.70 again. Hence periodic, layer-by-layer re-balancing.


7. Feature combinations: guided decoding + speculative decoding + CUDA graphs

7.1 Guided decoding

Production models must produce JSON, tool calls and function arguments that conform to a schema. Guided decoding (constrained decoding, structured generation) enforces a grammar:

  1. compile the grammar to an automaton and, for every automaton state, the set of tokens that keep the output in the grammar (a mask table);
  2. at every step, advance the grammar state by the last token, look up its mask, and set disallowed logits to −∞ before sampling.

Steps 1–2 are CPU work. XGrammar’s co-design hides it: launch the model forward, compute the grammar advance and mask on the CPU meanwhile, then synchronize and apply the mask before sampling.

7.2 Combining it with speculative decoding

The TensorRT-LLM case study combines guided decoding with speculative decoding. Two problems arise.

Grammar state tracing. Every drafted token advances the grammar, and every rejected one must roll it back.

  • The target’s masks at the k + 1 verified positions follow the drafts before each position. Any draft that breaks the grammar has target probability 0 and is forcibly rejected, which is correct but hurts acceptance.
  • Constraining the drafter with the same grammar avoids proposing such tokens.

Demo 06 runs this for real with Lecture 21’s parent and draft models and a grammar of ’+‘-only arithmetic (“12 + 7 = 19 .”), a strict subset of what the model writes:

configuration (k = 4, T = 1)tokens per target passacceptanceillegal draftsoutputs breaking the grammar
no grammar (plain speculative)3.680.874–24 / 24
target guided, drafter free3.220.7798.9%0 / 24
target and drafter guided3.610.8490.0%0 / 24
  • Without a grammar, every one of the 24 samples breaks the format: the speedup must be measured with the constraint on.
  • Guiding the drafter too recovers almost all the acceptance.
  • Exactness. Under greedy decoding, speculative + guided output equals guided decoding alone in 24 of 24 prompts with either drafter: advancing and rolling back the grammar state keeps the result exact.
  • Cost. The mask table here has 18 states and compiles in 5 ms; a lookup costs 0.4 µs. For real JSON schemas over a 128K vocabulary both are far larger, which is why mask generation must overlap the GPU.

CPU–GPU synchronization is the second problem. Grammar advance and mask generation must happen between the model forward and sampling, inside a CUDA graph that replays without the CPU. TensorRT-LLM’s solution is capturable grammar computation: the grammar work is launched as CUDA host callbacks on a dedicated stream, so the graph captures forward and grammar together. The troubleshooting list is instructive: data races between host and callback, and a deadlock between Python’s GIL and the CUDA mutex.

The wrap-up: “Feature combinations are where production inference stacks become much harder than isolated benchmarks.”


8. Choosing and composing

The Spring 2026 framework lecture’s deployment recipes:

  1. Small or medium model, straightforward traffic: one vLLM or SGLang pool with continuous batching, prefix caching and good metrics.
  2. Long-context interactive assistant: chunked prefill, strong prefix caching, possibly a remote KV tier, careful p99 monitoring.
  3. Large reasoning or MoE service at scale: EP + DP attention, PD disaggregation, a cache-aware router, separate prefill and decode pools, rigorous transport and KV accounting.

The benchmark-and-tune runbook:

  1. start from one engine with realistic traffic traces;
  2. measure TTFT, ITL, queue depth, active KV and tokens/s/GPU;
  3. enable the cheap wins first: continuous batching, prefix caching, chunked prefill, CUDA graphs and overlap;
  4. if MoE: evaluate EP backends and expert locality;
  5. if long prompts dominate: evaluate PD disaggregation and host or remote KV;
  6. re-benchmark with the exact feature combination you will ship.

Discussion prompts from the lecture, worth answering with this lecture’s demos:

  • When should we prefer chunked prefill over full PD disaggregation?
  • How should a cache-aware router value a worker with a hot prefix against one that is slightly less loaded?
  • For sparse MoE, where is the true bottleneck: compute, dispatch, all-to-all or KV?
  • How do we benchmark guided decoding without fooling ourselves?

9. Summary

  1. The stack is modular: engines (vLLM, SGLang, TensorRT-LLM), control planes (Dynamo, gateways) and KV tiers (LMCache, HiCache, KVBM) evolve separately and compose.
  2. At decode speed the CPU is on the critical path. Async scheduling, GPU-side input preparation and CUDA graphs remove it. Piecewise graphs keep attention flexible at a few percent cost.
  3. RadixAttention stores prompts and outputs in a tree. Real workloads (chat, agents, few-shot, branching) are ~90% reuse if prefixes are identical, and cache-aware scheduling decides what survives under memory pressure.
  4. Routing must see inside the engines. Round robin wastes caches, pure affinity creates hot spots, and a cost of prefill-to-compute plus queued work does both jobs.
  5. Disaggregation buys decode latency and per-phase parallelism for a KV transfer and a fixed P:D split. It wins for long prompts and tight TPOT SLOs when rate-matched, and loses when mismatched or on slow links.
  6. Wide EP speeds up memory-bound expert GEMMs and frees memory, until imbalance dominates. EPLB fixes the imbalance at wide EP but costs at narrow EP, and every kernel must scale with EP.
  7. Feature combinations (guided + speculative + graphs) are correct only with careful state tracing, and fast only if the drafter shares the constraint.

10. Common pitfalls

  • Comparing frameworks by one kernel benchmark. Production performance is kernels + scheduler + memory format + transport + feature interactions.
  • Adding disaggregation because it looks good on a diagram: without rate matching and a fast link it loses to colocated chunked prefill (Demo 04).
  • A cache-aware router without a load term (hot spots), or a load balancer without cache awareness (wasted prefill).
  • Building prompts with variable content first: every cached block after it is lost.
  • Measuring speculative speedup without the production constraints (grammar, temperature, batch).
  • Assuming EPLB always helps: at narrow EP replicas cost more than imbalance (Demo 05 Part B).
  • Trusting torch.compile or CUDA graphs without measuring on the target (Demo 01 Part C).

11. Exercises

  1. CPU overhead. A decode step takes 8 ms on the GPU and the scheduler needs 1.5 ms of CPU. Throughput loss with synchronous scheduling? With asynchronous scheduling? When does async stop hiding it?

    AnswerSync: step = 9.5 ms, 16% fewer tokens/s. Async: step = max(8, 1.5) = 8 ms, no loss. Async stops hiding the overhead when the CPU part exceeds the GPU part (CPU ≥ 8 ms): then the CPU sets the pace, and you need less host work (Rust, GPU-side preparation) rather than more overlap.
  2. Graph buckets. CUDA graphs need static shapes, so vLLM captures graphs for batch sizes 1, 2, 4, 8, …, 512 and pads each batch up to the next bucket. A batch of 33 decodes runs which graph, and what does padding cost at small batch vs large batch?

    AnswerThe 64 bucket (or 40 or 48 if those are captured). The 31 padded slots do matmul work but read no extra weights. At small batch the step is weight-bandwidth-bound, so padding is nearly free. At large batch (compute-bound) padding wastes up to ~2× compute, so buckets are spaced more finely there.
  3. Radix vs blocks. A workload has 1,000 requests sharing a 1,037-token prefix. How many prompt tokens does a 16-token block cache recompute per request beyond the radix tree’s?

    AnswerBlocks reuse ⌊1,037/16⌋·16 = 1,024 tokens; the radix tree reuses 1,037. That is 13 extra tokens per request, 13,000 in total: negligible for prefill throughput, but avoidable with page size 1 (SGLang's default) or prefix padding to block boundaries.
  4. The router’s weight. Two workers: A has 80% of a 3,000-token prompt cached and 4,000 queued prefill tokens; B has 0% cached and nothing queued. With cost = tokens to prefill + w × queued tokens, which wins at w = 0.5 and w = 1? Which is better for this request’s TTFT if the GPU prefills 30K tokens/s?

    AnswerA: 600 + w·4,000; B: 3,000. At w = 0.5, A = 2,600 < 3,000, so A wins. At w = 1, A = 4,600 > 3,000, so B wins. TTFT ≈ (queued + own) / 30K: A = (4,000 + 600)/30K = 153 ms, B = 3,000/30K = 100 ms. So w = 1 is right for this request: queued tokens delay it exactly as much as its own do. But routing to B also leaves B without the hot prefix for the next request, which a myopic cost ignores.
  5. Rate matching. Prefill throughput is 37K tokens/s per GPU; a decode GPU sustains 60 concurrent requests at 15 ms per step. Requests have 4,000-token prompts and 300-token outputs. On 8 GPUs, what P:D ratio balances the pools?

    AnswerA prefill GPU serves 37K/4,000 = 9.25 req/s. A decode GPU finishes 60 requests every 300 × 15 ms = 4.5 s, i.e. 13.3 req/s. Balance: 9.25·P = 13.3·D with P + D = 8 → P ≈ 4.7, D ≈ 3.3. So 5P:3D (or 4:4 if the TTFT SLO is loose). Demo 04's 4 + 4 layout is close to this; its 6 + 2 layout (3 × TP2 + 1 × TP2) starved decode.
  6. KV transfer budget. Llama-3-70B at 320 KiB per token of KV, 8,000-token prompts, 10 requests/s. What sustained bandwidth must the prefill→decode link carry, and is 100 GbE enough?

    Answer8,000 × 327,680 B × 10/s = 26 GB/s. 100 GbE is 12.5 GB/s, not enough. 400 Gb/s InfiniBand (50 GB/s) is enough with headroom; an FP8 KV cache halves the requirement.
  7. EPLB arithmetic. 8 ranks, 64 experts. One expert gets 30% of all routed tokens, the rest share 70% evenly. What is the max/mean rank load with contiguous placement (8 experts per rank), and with that expert replicated on all 8 ranks?

    AnswerThe rank holding the hot expert gets 30% + 7 × (70%/63) = 37.8%; the mean is 12.5%, so the imbalance is 3.0. Replicated 8 ways, the hot expert's 30% splits as 3.75% per rank, and each rank gets 3.75% + its share of the rest (≈ 8.75%) ≈ 12.5%, balanced at ~1.0. The cost is 7 extra copies of one expert's weights.
  8. Illegal drafts. A drafter proposes k = 4 tokens; each independently breaks the grammar with probability 10%, and legal drafts are accepted with probability 0.9. Expected tokens per target pass, unconstrained vs constrained drafter?

    AnswerUnconstrained: per-draft acceptance = 0.9 × 0.9 = 0.81, so E = (1 − 0.81⁵)/(0.19) = 3.42. Constrained: 0.9, so E = (1 − 0.9⁵)/0.1 = 4.10. Demo 06 measured 3.22 vs 3.61 (its drafts are correlated, so the gap is smaller).

Assignment 4 (Inference and Serving) asks you to serve and benchmark a model. The concepts from this lecture:

  • report the Pareto curve, not one point;
  • check CPU overhead (GPU idle time in a profile) before tuning kernels;
  • measure cache hit rates and their dependence on prompt construction and routing;
  • treat disaggregation, EP and guided decoding as hypotheses to test against a colocated, chunked-prefill baseline.

No solutions are given here.


13. Research directions

  • Control planes that learn: predicting the prefill/decode mix and moving GPUs before SLOs break; joint routing and autoscaling.
  • KV as a distributed object: placement across HBM, host, SSD and remote tiers; prefetch policies for agents with tool calls of known duration; cross-request deduplication.
  • Partial disaggregation: attention-FFN disaggregation (Lecture 24), layer-wise KV streaming, prefill and decode sharing GPUs at a finer grain.
  • Batch-invariant, deterministic engines: same output whatever else is in the batch (Lecture 19’s RL problem, at serving time).
  • Structured output at scale: grammar compilation for large schemas, mask generation on the GPU, and grammar-aware drafters.
  • Expert placement for dynamic routing distributions; MoE-aware routers that send similar requests to the same experts.

14. Further reading

  • vLLM docs: V1 architecture, CUDA graphs and torch.compile integration, expert parallelism, disaggregated prefill; Inferact’s blog.
  • SGLang docs: RadixAttention, cache-aware load balancer, HiCache, large-scale EP.
  • TensorRT-LLM blogs: wide EP (parts 1–3), disaggregated serving, guided + speculative decoding.
  • NVIDIA Dynamo docs: KV router, planner, KVBM, NIXL, Grove; AIConfigurator.
  • DistServe, Splitwise and Mooncake papers for the theory and practice of disaggregation.

15. Next lecture

Lecture 24, Decode-Specialized Hardware: Groq 3 LPX, follows the decode bottleneck down to the silicon. If decode is a memory-bandwidth and latency problem, what if the weights lived in on-chip SRAM, the execution were scheduled by a compiler cycle by cycle, and a rack of such chips handled the per-token work next to GPU racks? That is attention–FFN disaggregation, one step beyond prefill–decode disaggregation.


术语表 (Glossary, English → 中文)

English中文
inference engine / control plane / KV tier推理引擎 / 控制平面 / 键值缓存层
host (CPU) overhead / asynchronous scheduling主机端开销 / 异步调度
GPU-native input preparationGPU 原生输入准备
CUDA graph / full graph / piecewise graphCUDA 图 / 整图 / 分段图
graph capture / replay / batch-size bucket图捕获 / 重放 / 批大小档位
kernel launch overhead内核启动开销
attention backend / fused MoE注意力后端 / 融合 MoE 算子
hybrid memory allocator混合显存分配器
RadixAttention / radix tree / lock reference基数注意力 / 基数树 / 锁引用
cache-aware scheduling / longest prefix match缓存感知调度 / 最长前缀匹配
hierarchical KV cache / offload / rehydrate分层键值缓存 / 卸载 / 回填
KV-aware routing / cache affinity / hot spot键值缓存感知路由 / 缓存亲和 / 热点
SLO-based planner / autoscaling基于 SLO 的规划器 / 自动扩缩容
disaggregated serving / prefill pool / decode pool分离式服务 / 预填充池 / 解码池
KV transfer / rate matching / speed of light (SOL)键值传输 / 速率匹配 / 理论上限
per-phase parallelism按阶段配置并行
wide expert parallelism / all-to-all大规模专家并行 / 全对全通信
expert load balancer (EPLB) / redundant experts专家负载均衡器 / 冗余专家
Pareto curve / throughput at latency帕累托曲线 / 给定延迟下的吞吐
guided decoding / grammar mask / rollback引导解码 / 语法掩码 / 回滚
feature combination / capturable computation特性组合 / 可捕获计算
request migration / fault tolerance请求迁移 / 容错
← 返回课程目录