Chapter 20: Inference Engines and GPU Deployment
Training optimizes parameters; serving applies them under a latency, throughput, quality, and cost contract. Dense autoregressive decode at small batches often waits on weight and KV-cache reads. Larger batches increase weight reuse, long contexts increase attention work, and distributed layouts add communication. Prefill, decode, startup, and scheduling can therefore have different bottlenecks. Use the architecture and roofline analysis to identify the limiting resource for the actual workload.
Concepts from other sections (39)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- FlashAttention: attention computed tile by tile with an online softmax, so the score matrix is never stored. Read more: 22.5 FlashAttention forward in C
- TTFT (time to first token): time from a request’s arrival to its first generated token. Read more: 23.4 Chunked prefill (mixed prefill + decode batches)
- TPOT (time per output token): time between successive tokens of a running request, about one step. Read more: 23.4 Chunked prefill (mixed prefill + decode batches)
- GGUF: llama.cpp’s single-file quantized model container, readable across llama.cpp, candle, mistral.rs, and Zig bindings. Read more: 20.2 Inference Frameworks: The Cross-Language Landscape
- K-quants / i-quants: llama.cpp’s weight quantization schemes for GGUF files; k-quants mix precision per block, and i-quants choose precision guided by an importance matrix measured on sample data. Read more: Chapter 26: Edge and Realtime Inference
- safetensors: a weight format consisting of an 8-byte little-endian header length, a JSON header of tensor names, dtypes, shapes, and offsets, and a flat byte buffer. Read more: 20.3.4 Portability and load triage
- chat template: a Jinja program that renders a list of chat messages into the exact token sequence the model was trained on. Read more: 20.3.4 Portability and load triage
- roofline: the bound on a loop’s speed from peak compute , memory bandwidth , and arithmetic intensity . Read more: 22.3 Cache-blocked, packed, batch-invariant matmul in C
- Service Level Objective (SLO): a target for a defined measure of service behavior over a specified window. Read more: Chapter 13: Engineering Acronyms in Software Engineering
- CUDA graph capture: recording a forward pass’s kernel sequence once per batch size so that each later step replays it with one launch. Read more: 20.6 Inside an Inference Engine: How vLLM and SGLang Run a Model
- MIG: hardware partitioning of one GPU into isolated instances, each requested as its own resource. Read more: 20.7.5 Adapter fleets and operations
- time-slicing: advertising one GPU as several, with no memory isolation between the pods that share it. Read more: 20.7.5 Adapter fleets and operations
- lead time: the delay from an autoscaling decision to a replica serving traffic, including node provisioning and cold start. Read more: 20.7.5 Adapter fleets and operations
- LeaderWorkerSet: a Kubernetes workload that creates, restarts, and scales a multi-pod replica as one unit. Read more: 20.7.5 Adapter fleets and operations
- LoRA: a frozen Linear plus a trainable low-rank update . Read more: 12.6 LoRA: low-rank adaptation with PiSSA initialization and merging
- Mixture of experts (MoE): a layer of many expert MLPs of which a router picks per token. Read more: 13.8 Mixture of Experts
- Grouped-query attention (GQA): query heads share key/value heads, each serving a contiguous group of query heads. Read more: 13.5 Grouped-Query Attention with a Cache Hook, Windows, and Sinks
- Residual connection: computing so that layers learn a residual and gradients flow directly. Read more: Chapter 2: Deep Learning
- Self-attention: a layer in which each position computes a weighted average of all positions’ values, weighted by query-key similarity. Read more: Chapter 2: Deep Learning
- Multi-query attention (MQA): all query heads share one key/value head. Read more: 13.5 Grouped-Query Attention with a Cache Hook, Windows, and Sinks
- ITL: inter-token latency, the gap between consecutive content chunks of a stream. Read more: 23.11 An open-loop load generator
- memory-bound: limited by the rate at which data can be read, not by arithmetic throughput. Read more: 22.7 Fused int4 and int8 dequantize-matmul in C
- block table: a request’s list of the physical KV blocks holding its tokens, used by attention to read the paged cache. Read more: 20.6 Inside an Inference Engine: How vLLM and SGLang Run a Model
- Reference count: the number of sequences holding a block; it returns to the pool at 0. Read more: 21.3 A paged KV cache in Python
- Retrieval-augmented generation (RAG): retrieving relevant evidence at query time and placing it in the context window, so a model answers from fresh, private, citable facts instead of only its parametric memory. Read more: Chapter 27: Retrieval and RAG
- Decode step: a forward pass over one new token against the cache. Read more: 21.2 The KV cache, incremental decoding, and generate
- Perplexity: , the geometric mean of ; the effective number of choices per token. Read more: 17.2 Perplexity, bits per byte, NLL accumulator in Mathematics
- Top-p (nucleus): the smallest set of most likely tokens whose mass reaches , including the crossing token. Read more: 21.1 Sampling and logit processors
- Repetition penalty: a Hugging Face rule that divides positive and multiplies negative logits of seen ids by , once per distinct id. Read more: 21.1 Sampling and logit processors
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0
- all-reduce: every rank ends with the elementwise reduction (sum or mean) of all ranks’ arrays. Read more: 17.2 Collectives over processes: ring all-reduce
- Pipeline bubble: time a stage cannot perform useful work because the schedule has not filled or drained. Read more: 17.4 Parallelism, topology, and the global training batch
- static binary: an executable that needs no C library at run time, produced by Go with
CGO_ENABLED=0. Read more: 10.2 Dockerfiles for the gateway and the engine in Systems Engineering - ISQ (in-situ quantization): mistral.rs’s quantization of weights at load time rather than ahead of time. Read more: 20.2 Inference Frameworks: The Cross-Language Landscape
- device plugin: the node agent that advertises GPUs to Kubernetes as the integer extended resource
nvidia.com/gpu. Read more: 20.7.5 Adapter fleets and operations - KEDA: an operator that scales workloads on external metrics by creating and driving an HPA. Read more: 10.7 Durable and worker images and charts in Systems Engineering
- cold start: the time from scheduling a replica to serving its first request, dominated by fetching and reading weight bytes and then by engine initialization. Read more: 20.3.4 Portability and load triage
- time to first token (TTFT): the time until the first body byte of an answer is ready to send to the client. Read more: 25.3 The SSE streaming proxy
- Scaling laws: empirical power laws relating loss to compute, data, and parameter count. Read more: Chapter 2: Deep Learning
This chapter follows that fight from the model’s architecture to a deployed, load-tested fleet. The opening you are reading surveys the core ideas: the transformer seen from a serving perspective, the two phases of generation, the KV cache, batching, kernels, quantization, decoding tricks, parallelism, deployment, and the metrics that make up a serving contract. The sections that follow go deep on each layer: the quantizers that shrink weights and caches, the frameworks that run models across languages, the mechanics of loading a checkpoint onto a GPU, the capacity math and load testing behind a real deployment, the platforms that sit between an application and a token, what happens inside an engine from startup to each step, the Kubernetes deployment of a GPU fleet, and the producer’s side: packaging, publishing, and sharing a model you trained.
Learning objectives
- Explain why decode is memory-bandwidth bound while prefill is compute bound, and how each phase is optimized.
- Size the KV cache from a model’s architecture and explain how PagedAttention and prefix caching manage it.
- Explain how continuous batching, FlashAttention, quantization, and speculative decoding each improve serving, and which resource (memory, bandwidth, or compute) and which phase each one helps.
- Choose among tensor, pipeline, and expert parallelism given a model’s size and the interconnect available.
- Define TTFT, TPOT, throughput, and goodput, and explain the tension between throughput and per-user latency.
Before you begin
Section titled “Before you begin”This chapter assumes the transformer architecture and attention from Deep Learning; the Foundation Models & Architectures, Neural Architectures & DL History, and Training and Post-Training chapters of this book all feed into it. The deployment material assumes containers and Kubernetes from Cloud Native in Systems Engineering. The primary reference is Vijay Janapa Reddi’s Machine Learning Systems (free online), the systems-level companion to Goodfellow.
The best preparation is practical: serve a real model locally with vLLM before reading the theory, and watch GPU memory, tokens per second, and how batching changes them. As you read, ask of each optimization whether it reduces memory, bandwidth, or compute, and which phase, prefill or decode, it helps. And profile rather than guess: use nvidia-smi, Nsight, and the framework’s own metrics to find the actual bottleneck before optimizing.
In this chapter
Section titled “In this chapter”For a practical start, use the local serving lab. Read architecture constraints, generic runtime controls, and batch invariance before interpreting provider-specific tuning examples.
-
Quantization: Math to Code. The quantizer zoo (GPTQ, AWQ, SmoothQuant, NF4, GGUF k-quants, FP8, QuIP#, and TurboQuant) derived from the math and implemented in C, CUDA, and Rust.
-
Inference Frameworks: The Cross-Language Landscape. The inference stack across C (llama.cpp), Python (vLLM, TGI, SGLang), Rust (candle, mistral.rs), and Zig (ZML), with runnable Rust and Zig examples.
-
Model Loading: Hub to GPU. Hub repo anatomy, the safetensors byte layout, what
from_pretraineddoes, how engines shard weights, cold-start math, and chat templates, with a triage playbook for failed loads. -
Serving, Capacity & Load Testing: Math to Code. The roofline for prefill and decode, memory budgets, SLOs and goodput, parallelism, vLLM and SGLang knobs, load-testing methodology, and cost per token.
-
LLM Serving Platforms: How They Work and When to Use Them. How Anyscale, Ray, vLLM, SGLang, RouteLLM, and OpenRouter work, their use cases and trade-offs, and what reproducibility costs.
-
Inside an Inference Engine: How vLLM and SGLang Run a Model. What happens from
vllm serveto the first token: the processes, reading the architecture, building the model already split per GPU, streaming and slicing weights, profiling memory into KV blocks, CUDA graph capture, one step of the scheduling loop, and what SGLang does differently. -
Deploying LLMs on Kubernetes: GPUs, Replicas, and Rollouts. From the capacity plan to a running fleet: pod shape and replica math, GPU node pools, MIG and time-slicing, getting Hugging Face weights onto nodes, the vLLM Deployment, rollouts, autoscaling with lead time, LeaderWorkerSet, routing, and sizing separate prefill and decode pools.
-
From Training Run to Shared Model: Packaging, Publishing, and Use Cases. How architecture is stored, exporting your own checkpoint, how LoRA runs in training and serving, publishing to the Hub, sharing weights versus adapters versus endpoints, and six practical deployments sized end to end.
-
Architecture choices and performance limits: dense/MoE, MHA/GQA/latent attention, recurrent/hybrid state, and workload-dependent bottlenecks.
-
Runtime controls and inference flags: provider-neutral scheduling, memory, precision, compilation, sampling, and reproducibility mechanisms with versioned mappings.
-
Serving layouts and disaggregation: in-process execution, local HTTP, independent replicas, model parallelism, and prefill/decode pools.
-
Performance experiments and validation: correctness layers, fixed-workload ablations, goodput, errors, cost, and evidence limits.
-
Batch invariance and reproducibility: deterministic execution versus per-request invariance, numerical causes, and a test matrix.
-
Local training, serving, and validation lab: CPU checks, a tiny training loop, vLLM/SGLang/llama.cpp launches, shared API probes, and load testing.
The transformer, seen from serving
Section titled “The transformer, seen from serving”The model being served is a decoder-only stack: an embedding, then transformer blocks (attention, MLP, residual connections, and normalization), then an unembedding. GPT, LLaMA, Mistral, and Qwen all share this shape, recapped here from Deep Learning through an inference lens.
Self-attention computes , which costs in sequence length; this is why long context is expensive. At decode time, every new token attends to all previous tokens’ keys and values, so you must keep them around. That stored state is the KV cache, and its size follows directly from the architecture:
The KV cache size, in turn, dictates how many concurrent requests fit in memory. Several architectural variants change it. Multi-Query Attention (MQA) and Grouped-Query Attention (GQA) shrink the KV cache by sharing K and V heads across query heads. Mixture-of-Experts (MoE) routes each token to a few experts, raising the parameter count without raising per-token FLOPs. Position schemes such as RoPE and ALiBi affect long-context behavior; supported context length and extrapolation quality require validation and sometimes additional training.
The two phases: prefill and decode
Section titled “The two phases: prefill and decode”Generation has two distinct phases with opposite performance profiles, and they are optimized differently.
Prefill processes the entire prompt in one parallel forward pass and populates the KV cache. With enough prompt tokens it often becomes compute-bound, while small inputs or other layers can be limited by overhead or memory. Prefill determines time to first token (TTFT).
Decode generates tokens one at a time, each pass reading all the weights plus the KV cache to produce a single token per sequence. At small dense-model batches it is often memory-bandwidth-bound. Larger batches, long contexts, and communication can change that limit. Decode determines inter-token latency (ITL) and time per output token (TPOT).
A useful mental model is that prefill is a sprint, one big burst of compute, while decode is a slow drip of thousands of tiny memory-bound steps. A serving system must schedule both without one starving the other. Chunked prefill helps by splitting long prompts so that prefill and decode can be interleaved in the same batch, smoothing latency spikes.
The KV cache
Section titled “The KV cache”The KV cache is the central data structure of inference. It stores the key and value tensors for every token already processed, per layer, so future tokens do not recompute them; this turns regeneration into incremental work. It trades memory for compute, and managing it well is what separates toy serving from production throughput.
The cache dominates memory because it grows linearly with sequence length and batch size; for long contexts it can exceed the model weights themselves. Naive serving makes this worse. Contiguous allocation can waste memory through fragmentation and over-reservation. The PagedAttention paper measured substantial waste in its evaluated baselines; the amount depends on the allocator and workload.
PagedAttention, introduced by vLLM, fixes this by managing the KV cache like virtual memory. The cache is stored in fixed-size blocks (pages), referenced through a block table and allocated on demand. Each sequence sees contiguous logical blocks, and the table maps them to whatever physical blocks were free. Tail-block waste and metadata remain, while contiguous over-reservation is greatly reduced, and the design enables copy-on-write sharing of prompt prefixes: two sequences with the same system prompt point at one physical block with a reference count of 2, which is freed only when both finish.
Prefix caching generalizes that sharing across requests, reusing the KV blocks of a shared prompt prefix, such as a system prompt or few-shot examples. It is a large win for chat and RAG. The key result: PagedAttention raised serving throughput 2 to 4 times over prior systems, by reclaiming wasted KV memory and packing more requests into each batch.
Batching strategies
Section titled “Batching strategies”Reclaimed memory pays off only if the scheduler fills it with work, which is the job of batching. Throughput and latency trade off directly through batch size, and the scheduling strategy decides how well that trade is made.
Static batching waits to assemble a fixed batch and runs it to completion. It is simple, but the whole batch waits for its slowest, longest sequence, giving terrible GPU utilization. Continuous (in-flight) batching schedules at the token level instead: as soon as one sequence finishes, it is evicted and a new request is admitted into the freed slot, mid-flight. This keeps the GPU saturated, and production engines commonly expose it through their scheduling controls. Its benefit depends on the length mix, arrival pattern, scheduler, device, and latency constraints; compare it under a fixed workload.
Batch size remains a throughput-versus-latency knob. Bigger batches give more tokens per second and a better cost per token, but higher per-request latency, and a serving SLO picks a point on that curve. Disaggregated prefill and decode goes further by running compute-bound prefill and memory-bound decode on separate GPU pools, so that each pool is sized for its own bottleneck.
Attention and kernel optimization
Section titled “Attention and kernel optimization”Below the scheduler, kernels decide how efficiently each step uses the hardware. FlashAttention computes attention without materializing the full attention matrix in HBM: it tiles the computation in fast SRAM and uses the online-softmax trick. Memory goes from to , and it is faster thanks to better memory locality; FlashAttention-2 and -3 push further with better work partitioning. PagedAttention kernels compute attention reading K and V from non-contiguous paged blocks. Fused kernels combine operations such as layernorm, matmul, and activation to cut kernel-launch overhead and HBM round trips. And CUDA graphs capture the decode step as a graph, eliminating per-step launch overhead in the tiny, memory-bound decode loop.
Quantization and compression
Section titled “Quantization and compression”Quantization trades precision for memory bandwidth and footprint, and it works especially well for inference: fewer bytes per weight mean less memory traffic, which speeds up decode, the bandwidth-bound phase, and leaves more room for KV cache.
There are several flavors. Weight-only quantization to INT8 or INT4 (GPTQ, AWQ) keeps activations in higher precision and quantizes only the weights; AWQ protects salient weights, while GPTQ uses second-order error correction. Weight-plus-activation quantization uses FP8 (native on Hopper and Ada) or INT8, where SmoothQuant migrates activation outliers into the weights to make activations quantizable. KV cache quantization stores the cache in FP8 or INT8 to fit longer contexts and bigger batches. Beyond quantization, distillation, pruning, and small models suited to speculative decoding shrink the model itself.
Warning: Aggressive quantization (INT4) can degrade quality on hard tasks. Always evaluate on your own benchmark, not just on perplexity.
Quantization: Math to Code covers the full quantizer zoo, GPTQ, AWQ, SmoothQuant, NF4, GGUF k-quants, FP8, QuIP#, and TurboQuant, with the underlying math translated into runnable C, CUDA, and Rust (Burn) examples.
Decoding optimizations
Section titled “Decoding optimizations”Decode’s memory-bound single-token steps leave compute idle, and speculative decoding puts it to work. A small, fast draft model proposes tokens, and the big target model verifies them all in one parallel pass, accepting the longest correct prefix. Batch verification can reduce target passes per accepted token. Exact accept/resample rules preserve the target distribution; speed depends on acceptance, draft cost, verification cost, and load. Medusa, EAGLE, and lookahead decoding are self-speculation variants that add lightweight prediction heads instead of a separate draft model.
Other decoding controls shape output rather than speed. Sampling parameters (temperature, top-k, top-p or nucleus sampling, and repetition penalty) change what is generated without changing cost much. Structured or constrained decoding masks logits to force valid JSON or a grammar (Outlines, XGrammar), which is critical for tool-calling reliability.
Multi-GPU and multi-node parallelism
Section titled “Multi-GPU and multi-node parallelism”When the model, or its KV cache, does not fit on one device, you must split it, and each choice has a different communication cost. Tensor parallelism (TP) splits each weight matrix across GPUs, with an all-reduce in every layer. It gives low latency but is communication-heavy, so keep it within one node’s fast NVLink domain. Pipeline parallelism (PP) assigns different layers to different GPUs, with micro-batches flowing through the pipeline. Its communication is cheaper, but it introduces pipeline bubbles; it works better across nodes. Expert parallelism (EP), for MoE models, places different experts on different GPUs and routes tokens to their experts with all-to-all communication. Sequence or context parallelism splits the sequence dimension for very long contexts.
The rule of thumb is TP inside a node (NVLink) and PP or EP across nodes (slower interconnect). At this scale communication becomes the bottleneck, so topology awareness matters.
Serving frameworks and runtimes
Section titled “Serving frameworks and runtimes”All of these techniques are packaged in serving frameworks, each with its own niche. This table summarizes the main ones:
| Framework | Niche | Key feature |
|---|---|---|
| vLLM | General-purpose, high throughput | PagedAttention, continuous batching, broad model support |
| TensorRT-LLM | Max performance on NVIDIA | Compiled kernels, FP8, in-flight batching |
| TGI (HuggingFace) | Production HF ecosystem | Tensor parallel, token streaming, easy deploy |
| SGLang | Complex/structured generation | RadixAttention prefix sharing, fast structured output |
| llama.cpp / Ollama | Local, CPU/edge, GGUF | Runs quantized models on consumer hardware |
| candle / mistral.rs (Rust) | Safe single static binary, edge/WASM | Pure-Rust kernels + runtime, ISQ, OpenAI server |
| ZML / llama.cpp.zig (Zig) | Native compile, minimal deps, C interop | MLIR/XLA multi-vendor, or @cImport over llama.cpp |
| Ray Serve / KServe | Orchestration layer | Autoscaling, multi-model, request routing on top of a runtime |
Inference Frameworks: The Cross-Language Landscape maps the full stack across C (llama.cpp and ggml), Python (vLLM, TGI, SGLang), Rust (candle, mistral.rs, burn, ratchet, luminal), and Zig (ZML, llama.cpp.zig), with runnable Rust and Zig examples. LLM Serving Platforms covers the orchestration, gateway, and routing layers above the engines.
Deployment: GPU clusters and Kubernetes
Section titled “Deployment: GPU clusters and Kubernetes”Serving meets Cloud Native infrastructure when the framework is deployed on a cluster. On Kubernetes, the NVIDIA device plugin exposes nvidia.com/gpu as a schedulable resource, and node selectors, taints, and nodeAffinity pin pods to the right GPU SKU (A100, H100, L40S). GPUs can be shared: Multi-Instance GPU (MIG) partitions one A100 or H100 into isolated slices, while time-slicing shares a GPU across pods for low-traffic models. Multi-node serving uses LeaderWorkerSet or multi-host inference for models spanning nodes, with RDMA or InfiniBand and topology-aware scheduling for the parallelism interconnect.
Autoscaling should key on GPU-aware signals, such as queue depth, tokens per second, and KV-cache utilization, via KEDA or custom metrics, not CPU. Cold starts are brutal, because model weights run to tens or hundreds of gigabytes, so keep warm pools and use fast model loading: streaming from object storage, RDMA, or a local NVMe cache (Model Loading: Hub to GPU does the math). Operators such as KServe, Ray, NVIDIA NIM, or KubeAI manage model deployments declaratively, with canary rollouts and scale-to-zero. The main cost levers are spot or preemptible GPUs with checkpointing, right-sizing the GPU to the model, and bin-packing many small models per GPU with MIG. Deploying LLMs on Kubernetes builds all of this as manifests, with the arithmetic behind each field.
Serving metrics and SLOs
Section titled “Serving metrics and SLOs”Finally, a serving system is judged by a handful of metrics, each driven by a different part of the system:
| Metric | Meaning | Driven by |
|---|---|---|
| TTFT | Time to first token | Prefill speed, queue wait, prompt length |
| TPOT / ITL | Time per output token | Decode speed (memory bandwidth), batch size |
| Throughput | Total tokens/sec across all requests | Batching, KV cache efficiency, hardware |
| Goodput | Throughput that meets SLOs | Scheduling quality under load |
| Utilization | GPU compute/memory busy fraction | Batching, phase mix |
The key tension is that optimizing throughput with big batches hurts TTFT and TPOT for individual users. Serving systems therefore schedule to maximize goodput: throughput subject to latency SLOs. Serving, Capacity & Load Testing turns these definitions into capacity plans and load tests.
Optimization at a glance
Section titled “Optimization at a glance”Each technique in this chapter targets a specific goal, and it works for a specific reason. This table collects them:
| Goal | Technique | Why it works |
|---|---|---|
| Less KV memory waste | PagedAttention | On-demand blocks reduce over-reservation and fragmentation |
| More concurrent users | Continuous batching | Token-level scheduling keeps GPU full |
| Lower attention memory | FlashAttention | Tiled, no n×n matrix in HBM |
| Smaller footprint | Quantization (AWQ/GPTQ/FP8) | Fewer bytes → less bandwidth |
| Smaller KV cache | GQA/MQA, KV quantization | Fewer/cheaper K-V heads |
| Faster decode | Speculative decoding | Parallel verify > serial generate |
| Reuse shared prompts | Prefix / RadixAttention caching | Skip recomputing common prefixes |
| Model too big for 1 GPU | Tensor / pipeline parallelism | Split weights across devices |
Where this leads
Section titled “Where this leads”This chapter connects to much of the rest of the library. The model being served, with its attention, transformers, and scaling laws, comes from Deep Learning. Kubernetes, autoscaling, containers, and GPU scheduling form the deployment substrate in Cloud Native; caching, load balancing, queueing, and SLOs for request routing and capacity planning come from System Design; and tail latency, RED and USE metrics, and profiling for measuring TTFT and TPOT come from Observability, all in Systems Engineering. Quantization as lossy compression, the bits-per-weight versus quality tradeoff, rests on Information Theory in Mathematics. Getting data to and from the model through streaming pipelines and feature serving is the subject of Data Engineering.
These skills are in demand across the industry: at NVIDIA (TensorRT-LLM, kernel optimization, FP8, Triton, MIG); at Anthropic, OpenAI, and Google DeepMind, where inference serving at scale, KV cache management, parallelism, latency SLOs, TPU inference, and cost per token are research-level problems; at Databricks (model serving with vLLM and MosaicML, GPU orchestration); at Meta (LLaMA serving, quantization research, edge inference); and at Together, Fireworks, and Anyscale, which sell high-throughput serving as a product.
Further reading
Section titled “Further reading”- Vijay Janapa Reddi, Machine Learning Systems (free online)
- vLLM documentation
- Lilian Weng, Large Transformer Model Inference Optimization
- The Full Stack LLM Bootcamp
- Hugging Face TGI and NVIDIA TensorRT-LLM documentation
- The PagedAttention (vLLM) and FlashAttention papers, the two most load-bearing systems papers in modern serving
Key terms
Section titled “Key terms”- prefill: the compute-bound forward pass over the whole prompt that populates the KV cache and determines TTFT.
- decode: the memory-bandwidth-bound generation of one token per sequence per forward pass, which determines TPOT.
- KV cache: the stored keys and values of all processed tokens, per layer, that let each new token attend without recomputation.
- PagedAttention: KV-cache management in fixed-size blocks mapped through a block table, like virtual memory.
- continuous batching: token-level scheduling that admits and evicts sequences every step to keep the GPU full.
- speculative decoding: drafting several tokens cheaply and verifying them in one target-model pass, preserving the output distribution.
- tensor / pipeline / expert parallelism: splitting a model across GPUs by weight matrix, by layer, or by MoE expert.
- goodput: throughput that meets the latency SLOs.
Summary
Section titled “Summary”- Small-batch dense decode often depends on weight and KV bandwidth. Larger batches, long contexts, sparse experts, and distributed execution can shift the bottleneck.
- Prefill and decode expose different shapes and resource demands; scheduling affects TTFT, ITL, and goodput.
- The KV cache is the central data structure of serving, and PagedAttention with prefix caching is what makes production throughput possible.
- Throughput and latency trade off through batch size; continuous batching can improve utilization when variable-length requests share a device, subject to latency constraints.
- A model that does not fit on one GPU forces a parallelism choice (tensor, pipeline, or expert), each with a different communication cost.
Review questions
Section titled “Review questions”- Why is decode memory-bandwidth bound while prefill is compute-bound?
Answer
For large enough dense-model prompts, prefill reuses weights across many tokens and can be compute-bound. Small-batch decode has less weight reuse and is often bandwidth-bound; large batches, long-context attention, and communication can change either limit. - Write the KV cache size formula and explain why GQA increases the number of concurrent users.
Answer
$2 \times n_\text{layers} \times n_\text{kv heads} \times d_\text{head} \times \text{seq\_len} \times \text{batch} \times \text{bytes}$, where the 2 counts K and V. GQA shares each K/V head among several query heads, reducing $n_\text{kv heads}$; a smaller cache per token means more sequences fit in the memory left after the weights. - How does PagedAttention reduce memory waste, and how does it let two requests share a system prompt?
Answer
Contiguous per-request allocation can waste memory to fragmentation and over-reservation; the amount depends on the baseline and workload. PagedAttention allocates fixed-size blocks on demand and maps each sequence's logical blocks to arbitrary physical blocks through a block table. Two sequences with the same prefix can point at the same physical block, with a reference count of 2, freed only when both finish. - Why does continuous batching beat static batching on real traffic?
Answer
Under static batching, the whole batch waits for its longest sequence, so finished slots sit idle. Continuous batching evicts a finished sequence and admits a new request into its slot at the next token step, keeping the GPU saturated; the size of the improvement must be measured for the workload and SLO. - Where should tensor parallelism and pipeline parallelism be used, and why?
Answer
Tensor parallelism needs an all-reduce in every layer, so keep it inside one node's fast NVLink domain; it lowers latency. Pipeline parallelism only passes activations between stages, so it tolerates the slower interconnect between nodes, at the cost of pipeline bubbles. - For each of FlashAttention, quantization, and speculative decoding, say which resource it saves and which phase it mainly helps.
Answer
FlashAttention reduces attention memory from $O(n^2)$ to $O(n)$ and HBM traffic through tiling in SRAM, helping long-context attention, especially in prefill. Quantization reduces bytes per weight (and per KV element), saving memory and bandwidth, which mainly speeds up decode and frees room for KV cache. Speculative decoding spends idle compute to verify several tokens per pass, speeding up memory-bound decode.