AS·166
LLM Inference
How LLMs are served efficiently, from one token to millions of users: prefill and decode as compute-bound and memory-bound phases with roofline arithmetic, the KV cache and its memory budget, latency metrics (TTFT, inter-token latency, end-to-end) and throughput, the latency–throughput trade-off and concurrency, static vs continuous batching simulated step by step, PagedAttention's block tables, chunked prefill and prefill–decode disaggregation, prefix caching and provider prompt caching, speculative decoding in serving, tensor, pipeline, expert and data parallelism for inference, quantised and multi-LoRA serving, the engines (vLLM, SGLang, TensorRT-LLM, llama.cpp, Ollama and others) and managed inference APIs, benchmarking methodology, and capacity planning with worked numbers.
Start here: what happens when a model answers
A model generates text one token at a time, and each step needs the whole model. Serving it well comes down to understanding two phases and one cache.
Two phases
- Prefill: the model reads your whole prompt at once. All prompt tokens are processed in parallel, so this is fast per token and keeps the hardware busy.
- Decode: the model produces the answer one token at a time; each new token depends on the previous one, so steps can't run in parallel for one user.
Users feel them as two numbers: time to first token (TTFT, mostly prefill) and time per output token (TPOT, the decode step). In the lab, prefilling 120 prompt tokens took 7 ms (0.06 ms per token), while each decoded token took about 2 ms: per token, decoding was over 30 times slower.
The KV cache
At every step, attention needs the keys and values of all earlier tokens. Recomputing them each step wastes work; storing them is the KV cache. In the lab, generating 96 tokens took 549 ms without a cache and 161 ms with one (3.4× faster), with identical output. The price is memory: for a large 70-billion-parameter-class model the cache is about 320 KB per token, so a 32,000-token conversation needs about 10 GB of cache on top of the weights.
Batching: serving many users at once
Because a decode step is limited by reading the weights from memory, serving several users in the same step costs little extra. In the lab, 1 user got 437 tokens/s; 32 users together got 4,792 tokens/s in total, while each user's step time rose only from 2.3 to 6.7 ms. Continuous batching adds new requests to the running batch as soon as others finish, instead of waiting for the slowest one.
How deep to go in LLM inference
Volume 17 defines six mastery levels; for LLM inference they look like this:
| Level | You can… |
|---|---|
| L1 | explain prefill, decode, TTFT, TPOT and the KV cache |
| L2 | run a model with an inference engine and measure its latency and throughput |
| L3 | explain continuous batching, PagedAttention, prefix caching and speculative decoding |
| L4 | diagnose slow TTFT, poor throughput or out-of-memory errors from engine metrics |
| L5 | plan capacity and choose engines, hardware, precision and parallelism for a workload |
| L6 | run multi-model, multi-tenant inference fleets with autoscaling and cost targets |
Two phases
Every generation request runs in two phases (chapter 156):
| Prefill | Decode | |
|---|---|---|
| Work | Process all P prompt tokens at once; write their K/V into the cache; produce the first output token | Generate one token per step for each sequence, reading the whole KV cache |
| Parallelism | High: a big matrix multiply over P tokens | Low per sequence: one token at a time |
| Bottleneck | Compute (FLOPs) | Memory bandwidth (reading weights and KV cache) |
| User-visible metric | Time to first token (TTFT) | Inter-token latency (ITL) / time per output token (TPOT) |
Roofline arithmetic
A forward pass over T tokens of an N-parameter dense model costs about 2·N·T FLOPs and must read the weights once (2N bytes in BF16), plus the KV cache.
- Prefill of 2,000 tokens on an 8B model: 2 × 8e9 × 2000 = 3.2e13 FLOPs. On a GPU sustaining ~400 TFLOP/s effective: ≈ 80 ms.
- Decode of one token for one sequence: weights 16 GB must stream through at, say, 3.35 TB/s (H100 HBM3): ≥ 4.8 ms per token → at most ~200 tokens/s for a single sequence, whatever the FLOPs.
- Batching decode across B sequences reads the weights once per step for all of them: per-step time grows slowly until compute (or KV-cache reads) becomes the limit. That's why serving throughput depends on batching.
The KV cache
Each layer stores K and V for every past token of every active sequence (chapter 154):
KV bytes per token = 2 × layers × kv_heads × head_dim × bytes_per_value
For a Llama-3-8B-like model (32 layers, 8 KV heads, head_dim 128, BF16): 2 × 32 × 8 × 128 × 2 = 128 KiB per token. 100 concurrent conversations of 8,000 tokens: 100 × 8000 × 128 KiB ≈ 105 GB, far more than the 16 GB of weights. KV-cache capacity, not weights, usually limits concurrency. Levers: GQA/MLA architectures, FP8/INT8 KV cache, shorter contexts, prefix sharing, offloading cold KV to CPU memory or SSD.
Latency and throughput metrics
| Metric | Definition | Who cares |
|---|---|---|
| TTFT | Request arrival → first output token (queueing + prefill) | Interactive users: perceived responsiveness |
| ITL / TPOT | Time between successive output tokens during streaming | Reading speed; voice agents need it steady |
| End-to-end latency | TTFT + (output tokens − 1) × ITL | Non-streaming APIs, agents chaining calls |
| Throughput | Output (or total) tokens per second across all requests | Cost per token, capacity |
| Goodput | Throughput of requests that meet their latency SLOs | The metric that matters in production |
| Concurrency | Requests in flight simultaneously | Capacity planning |
Report percentiles (p50, p95, p99), not averages, under a realistic workload (prompt and output length distributions, arrival rates).
The trade-off: bigger batches raise throughput (cheaper tokens) but each decode step takes longer (higher ITL) and new requests wait (higher TTFT). Serving configuration picks a point on this curve per use case: chat (low TTFT/ITL), batch jobs (max throughput), agents (end-to-end latency).
Batching
Static batching
Group requests, run them together until all finish. Short requests wait for the longest; slots sit idle after sequences finish; new requests wait for the whole batch. Poor utilisation for variable-length generation.
Continuous (in-flight) batching
Schedule per step: after each decode iteration, finished sequences leave and waiting requests join immediately (Orca, 2022). GPU slots stay full; throughput improves several-fold over static batching for chat workloads. Every modern engine does this.
import random
def simulate(requests, max_batch=4, continuous=True):
"""requests: list of (arrival_step, output_tokens). Returns mean latency (steps) and total steps."""
pending = sorted(requests); running = {}; t = 0; done = {}
rid = 0; queue = []
while len(done) < len(requests):
while pending and pending[0][0] <= t: # arrivals
queue.append((rid, pending.pop(0))); rid += 1
can_admit = continuous or not running # static: only when batch is empty
while can_admit and queue and len(running) < max_batch:
i, (arr, n) = queue.pop(0); running[i] = [arr, n]
for i in list(running): # one decode step for everyone running
running[i][1] -= 1
if running[i][1] == 0:
done[i] = t + 1 - running[i][0]; del running[i]
t += 1
return round(sum(done.values()) / len(done), 1), t
random.seed(0)
reqs = [(random.randint(0, 40), random.choice([5, 10, 20, 200])) for _ in range(40)]
simulate(reqs, continuous=False), simulate(reqs, continuous=True)
# static: mean latency 437.5 steps, 1,282 steps total · continuous: 187.8 and 672 for the same work
Chunked prefill and disaggregation
A long prefill (say 30k tokens) stalls every decoding sequence in the same batch, causing ITL spikes. Chunked prefill splits it into pieces interleaved with decode steps, smoothing latency. Prefill–decode disaggregation runs the two phases on separate GPU pools (compute-optimised for prefill, memory-optimised for decode), transferring KV caches between them; adopted in large-scale serving (e.g. DistServe-, Mooncake- and Dynamo-style systems) to meet TTFT and ITL targets independently.
PagedAttention
Early servers reserved contiguous KV memory for each sequence's maximum length: most of it wasted (fragmentation and over-reservation). PagedAttention (vLLM, 2023) borrows virtual memory: the KV cache is split into fixed-size blocks (e.g. 16 tokens); each sequence has a block table mapping logical blocks to physical blocks allocated on demand. Waste drops to under one block per sequence, so many more sequences fit; blocks can be shared copy-on-write between sequences with a common prefix (parallel sampling, beam search, shared system prompts).
class BlockAllocator:
def __init__(self, num_blocks, block_size=16):
self.free = list(range(num_blocks)); self.block_size = block_size
self.refcount = {}; self.tables = {}; self.lengths = {}
def append_token(self, seq):
table = self.tables.setdefault(seq, []); n = self.lengths.get(seq, 0)
if n % self.block_size == 0: # current block full (or none yet) → allocate
if not self.free: raise MemoryError("KV cache full: preempt or queue")
b = self.free.pop(); table.append(b); self.refcount[b] = 1
self.lengths[seq] = n + 1
def fork(self, parent, child): # share prefix blocks (parallel sampling)
self.tables[child] = list(self.tables[parent]); self.lengths[child] = self.lengths[parent]
for b in self.tables[child]: self.refcount[b] += 1
def release(self, seq):
for b in self.tables.pop(seq):
self.refcount[b] -= 1
if self.refcount[b] == 0: self.free.append(b); del self.refcount[b]
self.lengths.pop(seq)
alloc = BlockAllocator(num_blocks=100)
for _ in range(40): alloc.append_token("A") # 40 tokens → 3 blocks
alloc.fork("A", "B") # B shares A's 3 blocks
len(alloc.free), alloc.tables["A"] == alloc.tables["B"] # (97, True)
(A real implementation copies the last, partially filled block on the first divergent write.)
Prefix caching and prompt caching
Many requests share long prefixes: the same system prompt and tool definitions, the same document across questions, the earlier turns of a conversation, agent loops re-sending growing histories. Prefix caching keeps the KV blocks of previously seen prefixes (keyed by hashes of block contents chained from the start) and reuses them, skipping that part of prefill: lower TTFT and compute.
- Engine level: vLLM's automatic prefix caching, SGLang's RadixAttention (a radix tree of cached prefixes with LRU eviction).
- Provider level: prompt caching in APIs: mark (or automatically detect) a stable prefix; cached input tokens are billed at a large discount and processed faster; caches expire after minutes of inactivity (some providers offer longer lifetimes at a cost).
- Design for it: put stable content first (system prompt, tools, reference documents) and variable content last; avoid timestamps or random ids at the top of prompts; keep tool definitions in a stable order.
import hashlib
def block_hashes(token_ids, block=16):
"""Chained hashes of full blocks: a block's key depends on all tokens before it."""
h, out = b"", []
for i in range(0, len(token_ids) - len(token_ids) % block, block):
h = hashlib.sha256(h + bytes(str(token_ids[i:i + block]), "utf8")).digest()
out.append(h.hex()[:12])
return out
system = list(range(64)) # 64 tokens of shared system prompt
q1, q2 = system + [900, 901, 902], system + [777] * 20
shared = [a == b for a, b in zip(block_hashes(q1), block_hashes(q2))]
shared # first 4 blocks identical → reuse their KV
Speculative decoding in serving
Chapter 157 described the algorithm: a cheap draft proposes k tokens; the target verifies them in one pass. In serving it pays off most at low batch sizes (memory-bound decode with spare compute); at high batch sizes the GPU is already busy and gains shrink. Draft options: a small model from the same family, EAGLE-style heads trained on the target's hidden states, n-gram / prompt lookup (great for editing and RAG where outputs copy inputs), and multi-token prediction heads built into some models. Engines expose it as configuration.
Parallelism for inference
| Strategy | Splits | Use in inference |
|---|---|---|
| Tensor parallelism (TP) | Each layer's matrices across GPUs (column/row split), all-reduce per layer | Model too big for one GPU, or to cut per-token latency; needs fast interconnect (NVLink) within a node |
| Pipeline parallelism (PP) | Consecutive layers on different GPUs/nodes | Very large models across nodes; adds latency per stage; needs micro-batching to keep stages busy |
| Expert parallelism (EP) | MoE experts across GPUs; tokens routed with all-to-all | Large MoE models (chapter 153) |
| Data parallelism (replicas) | Whole model copies behind a load balancer | Scale throughput; simplest |
| Context/sequence parallelism | Long sequences across GPUs | Very long prompts |
Typical deployment: a 70B BF16 model with TP = 4 on one 8-GPU node (two replicas), or TP = 2 with FP8 weights; large MoE models with EP + TP across nodes; small models with many replicas.
Serving quantised models and many adapters
- Quantised weights (FP8, AWQ/GPTQ INT4, chapter 165) cut memory and raise decode speed; FP8 W8A8 also speeds prefill on supporting GPUs. Validate quality per model.
- FP8 KV cache roughly doubles KV capacity.
- Multi-LoRA serving (chapter 163): one base model, hundreds of adapters; requests for different adapters batch together with specialised kernels (Punica/S-LoRA-style).
Engines and services
| Engine | Strengths |
|---|---|
| vLLM | Widely used open-source server: PagedAttention, continuous batching, prefix caching, speculative decoding, quantisation, multi-LoRA, TP/PP/EP, OpenAI-compatible API, broad model and hardware support |
| SGLang | RadixAttention prefix reuse, fast structured outputs, strong performance on agentic/multi-call workloads and large MoE models |
| TensorRT-LLM (NVIDIA) | Highly optimised kernels and FP8/FP4 on NVIDIA GPUs; with Triton Inference Server / NVIDIA Dynamo for orchestration and disaggregation |
| Hugging Face TGI | Production server integrated with the HF ecosystem |
| llama.cpp | C/C++ inference on CPUs, Apple silicon, consumer GPUs, edge; GGUF quantisation (chapter 165); llama-server with OpenAI-compatible API |
| Ollama, LM Studio | Developer-friendly local model management built on llama.cpp-style engines |
| MLX-LM | Apple-silicon-native inference and fine-tuning |
| ONNX Runtime GenAI, ExecuTorch, MLC LLM | Cross-platform, mobile and browser deployment |
| Managed inference APIs | Frontier model providers, and hosted open-model platforms (cloud AI services, Together, Fireworks, Groq, Cerebras and others): no GPU operations, pay per token, provider-side batching and caching; check data handling, rate limits and SLAs |
# vLLM: OpenAI-compatible server with tensor parallelism, FP8 KV cache and prefix caching
vllm serve Qwen/Qwen3-32B --tensor-parallel-size 2 --max-model-len 32768 \
--kv-cache-dtype fp8 --enable-prefix-caching --gpu-memory-utilization 0.90
# SGLang
python -m sglang.launch_server --model-path Qwen/Qwen3-32B --tp 2 --port 30000
# llama.cpp: local server on a laptop with a 4-bit GGUF
llama-server -m qwen3-8b-q4_k_m.gguf -c 16384 -ngl 99 --port 8080
# Any of them: the same client code
curl http://localhost:8000/v1/chat/completions -H "Content-Type: application/json" \
-d '{"model": "Qwen/Qwen3-32B", "messages": [{"role": "user", "content": "Hello"}], "stream": true}'
Benchmarking
- Define the workload: prompt/output length distributions from production logs, arrival pattern (Poisson at a target rate, or bursts), share of cacheable prefixes, streaming or not.
- Sweep request rate or concurrency; record TTFT, ITL, end-to-end latency percentiles and throughput; find the knee where latency SLOs break.
- Compare configurations (TP degree, quantisation, max batch tokens, chunked prefill, speculative decoding) at equal SLOs (goodput), not just peak throughput.
- Tools: engine-provided benchmark scripts (
vllm bench serve, SGLang's bench_serving), GenAI-Perf, LLMPerf, k6/Locust with streaming clients. - Measure on the target hardware and model version; results don't transfer across GPUs or models.
Capacity planning
def decode_tokens_per_s_upper_bound(params_b, bytes_per_param, hbm_tb_s, batch):
"""Memory-bound upper bound: each step streams all weights once (ignores KV reads and overheads)."""
step_s = params_b * 1e9 * bytes_per_param / (hbm_tb_s * 1e12)
return batch / step_s
def kv_capacity_tokens(gpu_mem_gb, weights_gb, kv_bytes_per_token, utilisation=0.9, overhead_gb=4):
return int(((gpu_mem_gb * utilisation) - weights_gb - overhead_gb) * 1e9 / kv_bytes_per_token)
kv_per_token = 2 * 32 * 8 * 128 * 2 # 8B-class GQA model, BF16 KV = 131,072 B
tokens = kv_capacity_tokens(80, 16, kv_per_token) # tokens of KV that fit on one 80 GB GPU
tokens, tokens // 8000 # ≈ 397k tokens ≈ 49 concurrent 8k-token sequences
decode_tokens_per_s_upper_bound(8, 2, 3.35, batch=1), decode_tokens_per_s_upper_bound(8, 2, 3.35, batch=48)
# ≈ 209 tok/s for one sequence; ≈ 10k tok/s aggregate at batch 48 (real numbers are lower: KV reads, kernels, scheduling)
From measured goodput per replica and expected peak load (requests/s × tokens per request), compute replicas needed, add headroom for spikes and failures, and autoscale on queue depth and KV-cache utilisation rather than CPU (chapter 179).
Lab: KV cache, prefill, decode and batching on a tiny GPT
Setup. PyTorch on 2 CPU threads; chapter 156's GPT (4 layers, d = 192, 6 heads, 128-token context) with a hand-written KV-cache forward pass using the same weights. Greedy decoding. Scope: a CPU and a 2 M-parameter model; the shapes of the curves carry over to GPUs and large models, the absolute numbers don't.
Experiment 1: the KV cache
| Method | 96 tokens from a 32-token prompt | Per token |
|---|---|---|
| recompute the whole sequence every step | 549 ms | 5.72 ms |
| KV cache | 161 ms | 1.68 ms |
The outputs were identical token for token (checked), so the cache is a pure optimisation. Without a cache, each step's cost grows with the sequence length; with one, each step processes one new token against stored keys and values. The cache here costs 2 (K and V) × 4 layers × 192 × 4 bytes = 6 KB per token; a 70B-class model with grouped-query attention (80 layers, 8 KV heads of 128, fp16) needs 2 × 80 × 8 × 128 × 2 = 320 KB per token, so 32,000 tokens ≈ 10.5 GB per conversation.
Experiment 2: prefill vs decode
| Prompt tokens | Prefill | Per prompt token | One decode step |
|---|---|---|---|
| 16 | 3.93 ms | 0.245 ms | 1.74 ms |
| 64 | 5.81 ms | 0.091 ms | 2.65 ms |
| 120 | 7.02 ms | 0.058 ms | 2.08 ms |
Prefill time grew far more slowly than prompt length: more tokens per pass means the fixed cost of reading the weights is shared. A decode step cost about as much as prefilling 30 prompt tokens. That asymmetry is why long outputs dominate latency and cost, why APIs price output tokens higher than input tokens, and why engines schedule prefill and decode carefully (chunked prefill, or separate prefill and decode machines).
Experiment 3: batching decode
| Concurrent sequences | Total tokens/s | Step time (each user's inter-token latency) |
|---|---|---|
| 1 | 437 | 2.29 ms |
| 2 | 774 | 2.58 ms |
| 4 | 1,561 | 2.56 ms |
| 8 | 2,451 | 3.26 ms |
| 16 | 2,967 | 5.39 ms |
| 32 | 4,792 | 6.68 ms |
| 64 | 6,381 | 10.03 ms |
Up to 4 sequences, batching was nearly free; at 64, throughput was 14.6× higher while each user's tokens arrived 4.4× slower. Every serving system chooses a point on this curve: an SLO on time per output token caps the batch size, and KV-cache memory caps it too.
Experiment 4: static vs continuous batching (simulation)
A simulation using Experiment 3's measured step times: 400 requests arriving together, output lengths uniformly 10–299 tokens, 16 slots.
| Scheduler | Total time | Throughput | Mean completion time | Slot utilisation |
|---|---|---|---|---|
| static batches of 16 (wait for the longest) | 38.4 s | 1,685 tok/s | 19.9 s | 0.57 |
| continuous batching (refill each step) | 22.0 s | 2,933 tok/s | 11.1 s | 0.96 |
Static batching wasted 43% of its slots on requests that had already finished. Continuous (iteration-level) batching, introduced by Orca and now standard in vLLM, TGI, TensorRT-LLM and SGLang, keeps the batch full; PagedAttention makes that practical by allocating KV-cache memory in small blocks instead of one maximum-length slab per request.
Try it yourself
- Add a prefix cache: precompute the KV for a shared 64-token system prompt and measure TTFT with and without it.
- Implement speculative decoding with a 2-layer draft model and measure accepted tokens per step.
- Quantise the KV cache to int8 and measure the change in validation loss.
- Extend the simulation with Poisson arrivals and find the arrival rate at which mean TTFT exceeds 1 second.
Revision sheet: LLM inference
Key ideas
- Prefill (parallel over the prompt, compute-bound) and decode (one token per step, memory-bandwidth-bound).
- Metrics: TTFT, TPOT / ITL, end-to-end latency, throughput (tokens/s, requests/s), goodput under SLOs.
- KV cache: 2 × layers × KV heads × head dim × bytes per token; reduced by GQA/MQA, KV quantisation, sliding windows.
- Continuous batching + PagedAttention (block-allocated KV cache) keep GPUs busy without wasting memory.
- Prefix / prompt caching reuses KV for shared prefixes (system prompts, documents); chunked prefill and prefill–decode disaggregation balance the phases.
- Speculative decoding: a cheap draft proposes tokens, the big model verifies several in one pass; output distribution unchanged.
- Parallelism: tensor (within layers), pipeline (across layers), expert (MoE), data (replicas).
- Engines: vLLM, SGLang, TensorRT-LLM, TGI, llama.cpp, Ollama; benchmark with realistic prompt/output length distributions.
Numbers to remember
- Lab: KV cache 3.4× faster for 96 tokens, identical output.
- Lab: prefill 0.058 ms/token vs decode ≈ 2 ms/step.
- Lab: batch 64 → 14.6× throughput, 4.4× per-user step time.
- Simulation: continuous batching 0.96 slot utilisation vs 0.57 static.
- 70B-class GQA model: ≈ 320 KB of KV cache per token in fp16.
Pitfalls
- Benchmarking with fixed short prompts and outputs.
- Reporting throughput without latency percentiles (or the reverse).
- Forgetting KV-cache memory when sizing batch and context.
- Not reusing shared prefixes.
- Ignoring the cold-start time of loading weights.
Glossary
- TTFT / TPOT: time to first token / time per output token.
- KV cache: stored attention keys and values.
- PagedAttention: paged allocation of KV-cache blocks.
- Continuous batching: scheduling at the level of individual decode steps.
- Speculative decoding: draft-and-verify generation.
- GQA: grouped-query attention; several query heads share one KV head.