Serving LLMs: batching, PagedAttention, speculative decoding¶
Serving turns a model into a service that answers thousands of people at once, quickly and cheaply. Because generating a token is limited by memory bandwidth, the whole craft is one idea applied many ways: make every read of the weights serve as many useful tokens as possible, without running out of KV-cache memory or making anyone wait too long.
10,000 ft
Training happens once; inference happens every time anyone uses the model, so for a successful product it dominates lifetime compute and cost. The compute maths page showed the core fact: a decode step reads every weight once, so at batch 1 the GPU's tensor cores sit about 99% idle. The serving stack (vLLM, SGLang, TensorRT-LLM, TGI and the proprietary engines behind every chat product) exists to close that gap. It combines scheduling ideas from operating systems (paging, preemption), queueing theory (latency against utilisation) and probability (speculative decoding's exact rejection sampling). It builds on the KV cache, on quantisation and on tensor parallelism. It is what makes the product decisions in shipping AI products, such as latency budgets, prompt caching and model routing, possible.
2,000 ft
A request arrives, waits in a queue, is admitted when there is KV-cache memory for it, runs prefill over its prompt (compute-bound; sets time to first token), then joins the running batch for decode, one token per step (bandwidth-bound; sets time per output token), and frees its memory when done. The main levers:
- Continuous batching: re-form the batch at every step, so finished sequences leave and new ones join immediately.
- PagedAttention: store each sequence's KV cache in fixed-size blocks allocated on demand, so memory holds real tokens rather than reservations, and more sequences fit.
- Prefix caching: reuse the KV blocks of shared prefixes (system prompts, chat history).
- Chunked prefill, or disaggregating prefill and decode onto different GPUs, so long prompts stop stalling everyone else's tokens.
- Speculative decoding: a cheap draft proposes several tokens and the big model checks them all in one pass, with an output distribution provably identical to the big model's.
Ground level¶
What you are optimising¶
Four numbers describe a serving system:
| Metric | Definition | What sets it |
|---|---|---|
| TTFT, time to first token | arrival → first token | queueing + prefill time |
| TPOT or ITL, time per output token / inter-token latency | gap between streamed tokens | decode step time, and any prefill that interrupts it |
| Throughput | tokens (or requests) per second per GPU | batch size × steps per second |
| Goodput | requests per second that meet both TTFT and TPOT targets | everything above, at the tail |
Users feel TTFT as responsiveness and TPOT as reading speed; a human reads at roughly 4–8 tokens a second, so a TPOT of 30–50 ms already feels fast for chat, while agents and code tools consume tokens as fast as they come. Operators pay for throughput. The two pull against each other: a bigger batch raises throughput and lengthens every step. Goodput, introduced by DistServe, is the honest objective: throughput counted only for requests that met the latency targets, usually at the 90th or 99th percentile.
Little's law ties the pieces together: the average number of requests in the system equals arrival rate × average time in the system. A service receiving 50 requests per second, each taking 8 s to stream its answer, has 400 sequences in flight at all times, and every one of them needs its KV cache resident. Concurrency, not request rate, is what sizes the memory.
Two phases, two bottlenecks¶
From compute maths, for Llama 3 8B in BF16 on one H100:
- Prefill of a 2,000-token prompt is \(2 \times 8\times10^9 \times 2000 = 3.2\times10^{13}\) FLOPs. At 50% of the 989 TFLOP/s peak that is about 65 ms. Arithmetic intensity is about the prompt length, far above the ridge point (~295): compute-bound.
- Decode reads 16 GB of weights per step: at least 4.8 ms per step at 3.35 TB/s, whether the batch holds 1 sequence or 64. Intensity is about the batch size: memory-bound until the batch is in the hundreds.
So the decode step is a bus that leaves every 5 ms or so whether it is full or empty. Throughput comes from filling the seats; the KV cache decides how many seats there are.
Static batching and why it wastes the GPU¶
The obvious approach batches \(B\) requests, runs them to completion, then takes the next \(B\). Output lengths are wildly uneven (a one-word answer next to a 2,000-token essay), so most of the batch finishes early and its slots idle until the longest request ends, while new requests wait in the queue.
Continuous batching: schedule every iteration¶
Orca (Yu et al., OSDI 2022) made the scheduling unit one model iteration instead of one request. After every decode step, finished sequences leave and waiting ones join. The trick that makes it work is selective batching: the matmuls (QKV projections, MLP, output projection) do not care which sequence a token belongs to, so all tokens in flight are flattened into one \((T \times d)\) matrix and pushed through the weights together; only attention, which must see each sequence's own history, runs per sequence. A new request's prefill tokens and running requests' decode tokens can then share the same step. On GPT-3 175B, Orca reported 36.9× the throughput of NVIDIA FasterTransformer at the same latency.
An Anyscale benchmark (Daniel et al. 2023) on OPT-13B and one 40 GB A100 measured up to 8× throughput from continuous batching alone, and up to 23× when combined with vLLM's memory management, against Hugging Face's static batching. The gain grows with the variance of output lengths. Every modern engine does this.
The KV cache becomes the constraint¶
Once batching is continuous, the batch size is limited by how many sequences' KV caches fit. Llama 3 8B needs 128 KiB of cache per token. On an 80 GB H100, after 16 GB of weights and a few GB of working space, about 457,000 tokens of cache fit. A system that reserves the maximum length (say 4,096 tokens) for each request can run only 111 sequences, even if the average request uses 400 tokens. Older engines stored each request's cache contiguously and had to reserve.
Kwon et al. measured where the memory went in such systems: only 20.4–38.2% of KV-cache memory held actual token states; the rest was reserved for future tokens, lost to internal fragmentation (reserved but never used) or to external fragmentation between allocations (vLLM paper, Fig. 2).
PagedAttention: virtual memory for the KV cache¶
vLLM's answer is the operating system's: paging. Split each sequence's KV cache into fixed-size blocks (16 tokens is the default), keep a per-sequence block table mapping logical blocks to physical blocks anywhere in GPU memory, and allocate a new block only when the last one fills. The attention kernel follows the block table, gathering keys and values from scattered blocks (the PagedAttention kernel).
Consequences:
- Waste is at most one partly filled block per sequence: vLLM measured 96.3% of KV memory holding real tokens, against 20–38% before.
- Sharing is free. Two sequences can point at the same physical block. Parallel sampling (several completions of one prompt) and beam search share the prompt's blocks, with copy-on-write when a shared block must diverge. A reference count per block tells the allocator when it is free.
- Preemption is possible. When memory runs out, the scheduler evicts a sequence's blocks, either swapping them to CPU memory or dropping them to be recomputed later (recomputing a prefill is often cheaper than the PCIe transfer).
The paper reports 2–4× the throughput of FasterTransformer and Orca at the same latency, more for long sequences and for parallel sampling. The idea is now standard; even systems that do not use paged kernels (e.g. vAttention, which uses the GPU's own virtual memory instead) adopt the allocate-on-demand principle.
Prefix caching: never prefill the same text twice¶
Most real traffic repeats itself: the same system prompt on every request, the same few-shot examples, a chat history that grows by one turn each time, many agent calls over the same document. With paged blocks, reuse is a lookup. RadixAttention in SGLang (Zheng et al. 2023) keeps a radix tree whose edges are token sequences and whose nodes point at KV blocks; a new request walks the tree to find its longest cached prefix, prefills only the remainder, and least-recently-used leaves are evicted when memory is short. SGLang reported up to 6.4× throughput on agent, few-shot, JSON and multi-turn workloads.
The economics reach the price list: API providers now charge less for cached input tokens than for fresh ones (the exact discounts change, so check current pricing), and they reward you for putting stable content at the start of the prompt, where it can be a shared prefix. That is a design rule in context engineering.
Chunked prefill: stop long prompts stalling everyone¶
When a 30,000-token prompt arrives, its prefill takes a large fraction of a second. If the engine runs it as one step, every running sequence's next token waits: a visible stutter, a generation stall, for hundreds of users. The fix from Sarathi and Sarathi-Serve (Agrawal et al. 2024) is to give each iteration a token budget (for example 512 or 2,048 tokens), always include every running decode (one token each), and fill the rest of the budget with a chunk of pending prefill. Prefill chunks are compute-bound and decodes are bandwidth-bound, so mixing them uses both halves of the GPU at once ("piggybacking"). Under tail-latency targets they reported 2.6× the serving capacity of vLLM for Mistral-7B on one A100 and up to 3.7× for Yi-34B on two. Chunked prefill is now standard in the major engines.
Disaggregation: prefill and decode on different GPUs¶
Chunking makes the two phases share a GPU gracefully; disaggregation gives each phase its own GPUs. DistServe (Zhong et al. 2024) and Splitwise (Patel et al. 2023) run prefill on one pool and decode on another, shipping the KV cache between them. Each pool can then use its own batch size, parallelism and even hardware: decode needs bandwidth, not FLOPs. DistServe reported up to 7.4× more requests served within latency targets, or 12.6× tighter targets. Mooncake, the serving platform behind Moonshot AI's Kimi, goes further and pools CPU DRAM and SSD across the cluster into a distributed KV-cache store (Qin et al. 2024); under real workloads it let Kimi handle 75% more requests.
The cost is moving the cache. For Llama 3 8B a 2,000-token prompt's KV cache is \(2000 \times 128\ \text{KiB} \approx 262\) MB; over a 400 Gb/s (50 GB/s) network link that is about 5 ms, small next to a 65 ms prefill. For a 70B model with long prompts it is larger, and the transfer must be overlapped layer by layer.
Speculative decoding: several tokens per weight read¶
Batching fills the bus with different users. Speculative decoding fills it with future tokens of the same user. Verifying \(\gamma\) proposed tokens with the big model is one forward pass over \(\gamma + 1\) positions, and because decode is bandwidth-bound, that costs almost the same time as generating one token. If most proposals are right, you get several tokens per pass.
The algorithm, discovered independently by Leviathan et al. (2022) and Chen et al. (2023):
- A cheap draft model \(q\) proposes \(\gamma\) tokens autoregressively.
- The target model \(p\) scores all \(\gamma\) positions (plus one more) in one pass.
- Walk the proposals left to right. Accept token \(x\) with probability \(\min(1, p(x)/q(x))\).
- At the first rejection, sample a replacement from the residual distribution \(\propto \max(0, p - q)\) and stop. If all \(\gamma\) are accepted, sample one bonus token from \(p\)'s last position.
The result is exactly a sample from \(p\). The proof is three lines in the maths, and the Build it code checks it empirically. With acceptance rate \(\alpha\) (the probability a draft token survives), the expected number of tokens per target pass is
With \(\alpha = 0.8\) and \(\gamma = 4\), that is 3.36 tokens per pass; if each draft step costs 5% of a target pass, the speed-up is \(3.36 / (1 + 4 \times 0.05) = 2.8\times\). Leviathan et al. measured 2–3× on T5-XXL; Chen et al. 2–2.5× on Chinchilla 70B.
Where the draft comes from has evolved quickly:
- A smaller model of the same family (the original recipe). Needs the same tokenizer and a model worth hosting.
- Prompt lookup / n-gram drafts: copy candidate continuations from the prompt itself. Free, and very effective for editing, summarisation and code, where output repeats input.
- Extra heads on the target: Medusa (Cai et al. 2024) adds heads that predict tokens 2, 3, 4… ahead, and verifies a tree of candidates in one pass with a tree-shaped attention mask.
- Feature-level drafters: EAGLE (Li et al. 2024) trains a small head on the target's own last hidden states (reported 2.7–3.5× latency speed-up on Llama 2-Chat 70B); EAGLE-3 (Li et al. 2025) fuses features from several layers and reports up to 6.5×.
- Draft-free: Lookahead decoding (Fu et al. 2024) uses Jacobi iteration to generate and verify n-grams with the target alone.
The benefit shrinks as the batch grows. At large batch, decode is closer to compute-bound, and the extra verification FLOPs compete with other users' tokens. EAGLE-3 reports 1.38× throughput at batch 64 in SGLang, far below its batch-1 speed-ups. Speculative decoding is therefore mainly a latency tool, strongest for single-user, interactive and long-output workloads.
Parallelism for serving¶
A model that does not fit on one GPU, or a latency target one GPU cannot meet, needs parallelism:
- Tensor parallelism splits each weight matrix across GPUs in a node. Each GPU reads \(1/t\) of the weights per step, so decode latency falls almost \(t\)-fold, at the price of two all-reduces per layer. The tiny decode activations make those latency-bound, so NVLink matters. This is the standard way to serve a 70B model on 2–8 GPUs.
- Pipeline parallelism places layers on different GPUs or nodes. It adds latency, and needs many sequences in flight to keep every stage busy, but works over slower links.
- Expert parallelism spreads the experts of a mixture-of-experts model across GPUs, with all-to-all exchanges routing tokens to their experts.
- Data parallelism: independent replicas behind a load balancer. A prefix-aware router sends a conversation back to the replica that already holds its cache.
Kernels and the rest of the engine¶
Three engine pieces sit beside the scheduler:
- Attention for decode. With one query per sequence, FlashAttention's parallelisation over queries leaves most of the GPU idle at small batch. Flash-Decoding also splits the keys and values into chunks processed in parallel, then merges them with a log-sum-exp reduction. On CodeLlama-34B it gave up to 8× faster generation at very long contexts (PyTorch blog). FlashInfer (Ye et al. 2025) packages such kernels for paged and ragged KV layouts.
- CUDA graphs record a decode step's hundreds of kernel launches once and replay them, which removes CPU launch overhead that would otherwise dominate small-batch steps.
- Constrained decoding for JSON and grammars masks the logits at each step using a finite state machine (structured outputs). Good implementations precompute masks so the constraint costs almost nothing.
What it costs¶
Put the pieces together for Llama 3 8B on one H100 with the bandwidth model. Batch 64 at a 4,096-token context gives about 4,250 output tokens/s, which is roughly USD 0.13 per million output tokens at an assumed USD 2 per GPU-hour (compute maths). Each lever moves that number: quantised weights and FP8 KV caches cut bytes; paging and prefix caching raise the batch; speculative decoding raises tokens per weight read; disaggregation stops prefill from eating decode capacity. Real deployments land 2–3× above the floor because of prefill, idle capacity kept for traffic spikes, and tail-latency targets.
First principles¶
Why batching works, and where it stops. A decode step costs \(\max(\text{bytes}/\beta,\ \text{FLOPs}/P)\). The weight bytes are shared by every sequence in the batch; the FLOPs and the KV bytes are not. Batching amortises the weights, and nothing else. Throughput therefore rises with batch size until either the KV reads dominate (throughput then tends to \(\beta/(s\,k)\), set by context length \(s\) and KV bytes per token \(k\)) or compute does (intensity reaches the ridge). Reducing \(k\) with GQA, MLA or KV quantisation raises the first ceiling; FP8 compute raises the second.
Why memory management decides throughput. The KV cache is per-sequence state whose final size is unknown when the request starts. Any allocator that must commit memory up front either over-reserves (and caps concurrency) or under-reserves (and fails mid-generation). Paging is the classic answer to unknown sizes: commit memory in small fixed units as needed and keep an indirection table. It needs a kernel that can follow the indirection, which is what PagedAttention adds.
Why latency explodes near full utilisation. A server is a queue. In the simplest model (random arrivals and service times, M/M/1) the mean time in the system is \(1/(\mu - \lambda)\) for service rate \(\mu\) and arrival rate \(\lambda\): twice the bare service time at 50% utilisation, ten times at 90%. LLM servers are kinder than M/M/1 because batching lets \(\mu\) grow with load, but the shape holds. Operators run below full utilisation to protect tail latency, and that headroom is part of the real cost per token.
Why speculative decoding cannot change the output. Rejection sampling is a classical way to draw from \(p\) using proposals from \(q\). Speculative sampling is a variant in which a rejected proposal is not wasted: the replacement comes from exactly the probability mass \(q\) under-covered. Correctness does not depend on how good the draft is, only speed does. A bad draft is slow, never wrong. (With greedy decoding the rule reduces to: accept while the draft's token equals the target's argmax.)
Why prefill and decode interfere. Both phases use the same GPU, but a prefill step's duration is set by its prompt length while decode users need a steady cadence. Any scheduler that runs a long prefill as one step must stall decodes; one that defers prefill hurts TTFT. Chunking bounds the size of every step, and disaggregation removes the shared resource. Both trade a little efficiency for predictability.
The maths¶
Step time and capacity. With weight bytes \(W\), KV bytes per token \(k\), batch \(B\), mean context \(s\), bandwidth \(\beta\), peak \(P\) and \(N\) parameters:
\(M\) is device memory and \(M_{\text{act}}\) the working space. Paging raises \(B_{\max}\) by replacing the reserved length \(s_{\max}\) with the actual \(s\) (plus at most one block per sequence).
Little's law. For any stable queue, \(L = \lambda W\): mean number in the system = arrival rate × mean time in the system. With \(\lambda = 50\) requests/s and \(W = 8\) s, \(L = 400\) concurrent sequences, each holding \(s\,k\) bytes of cache.
Derivation: speculative sampling returns exactly p
Draft \(x \sim q\). Accept with probability \(\min(1, p(x)/q(x))\); otherwise draw from \(r(x) = \dfrac{(p(x) - q(x))_+}{\sum_y (p(y) - q(y))_+}\).
The probability of accepting the draft and it being \(x\) is \(q(x)\min(1, p(x)/q(x)) = \min(p(x), q(x))\). The total acceptance probability is \(\alpha = \sum_x \min(p(x), q(x))\). Since \(\sum_x p = \sum_x q = 1\),
So the probability of emitting \(x\) is
Note also \(\alpha = 1 - \tfrac12\sum_x |p(x) - q(x)| = 1 - \mathrm{TV}(p, q)\): the acceptance rate is one minus the total-variation distance between draft and target.
Derivation: expected tokens per target pass
Assume each of the \(\gamma\) drafted tokens is accepted independently with probability \(\alpha\), stopping at the first rejection. Let \(K\) be the number accepted: \(P(K = j) = \alpha^j(1 - \alpha)\) for \(j < \gamma\) and \(P(K = \gamma) = \alpha^\gamma\). Every pass emits \(K + 1\) tokens (the accepted ones plus a correction or bonus token), so
If a draft step costs a fraction \(c\) of a target pass, a round costs \(\gamma c + 1\) target passes, so the speed-up over plain decoding is \(\dfrac{1 - \alpha^{\gamma+1}}{(1-\alpha)(\gamma c + 1)}\) (Leviathan et al., §3). The optimal \(\gamma\) grows with \(\alpha\) and shrinks with \(c\). With \(\alpha = 0.6\) there is little point drafting more than 4 tokens; with \(\alpha = 0.9\), 8 still pays.
Waste under paging. With block size \(b\), a sequence of length \(s\) uses \(\lceil s/b \rceil\) blocks and wastes fewer than \(b\) token slots. The expected waste is about \(b/2\) slots per sequence, so the fraction wasted is about \(b/(2s)\): 0.6% for \(b = 16\) and \(s = 1{,}300\). A contiguous allocator reserving \(s_{\max}\) wastes \(1 - s/s_{\max}\): 68% for \(s = 1{,}300\), \(s_{\max} = 4{,}096\).
Build it¶
Two NumPy experiments. The first simulates 2,000 requests on one H100 serving Llama 3 8B, using the step-time model above. It compares static batching, continuous batching with max-length reservations, and continuous batching with paged (actual-size) memory, for a chat workload with short prompts and a RAG workload with long ones.
import numpy as np
rng = np.random.default_rng(0)
# Llama 3 8B on one H100: the bandwidth-bound decode model from the compute-maths page
N, W_BYTES, KV_TOK, BW, PEAK = 8.03e9, 16.1e9, 131072, 3.35e12, 989e12
KV_TOKENS = int((80e9 - W_BYTES - 4e9) / KV_TOK) # ~457k tokens of cache (4 GB kept free)
decode_s = lambda live_tokens: (W_BYTES + live_tokens * KV_TOK) / BW # weights + every live KV
prefill_s = lambda p: 2 * N * p / (0.5 * PEAK) # compute-bound at 50% utilisation
MAX_LEN = 4096 # what a contiguous allocator reserves
def run(policy, prompt, out):
n, t, made, i, live = len(prompt), 0.0, 0, 0, [] # live: [context, remaining]
def admit(ok):
nonlocal t, i
while i < n and ok():
live.append([prompt[i], out[i]]); t += prefill_s(prompt[i]); i += 1
while i < n or live:
if policy == "paged": # admit while actual tokens fit (10% slack)
admit(lambda: sum(c + r for c, r in live) + prompt[i] + out[i] < 0.9 * KV_TOKENS)
elif policy == "continuous" or not live: # fixed slots, max length reserved each
admit(lambda: len(live) < KV_TOKENS // MAX_LEN)
t += decode_s(sum(c for c, r in live if r > 0))
for s in live:
if s[1] > 0: s[0] += 1; s[1] -= 1; made += 1
if policy != "static" or all(r == 0 for _, r in live):
live = [s for s in live if s[1] > 0] # static: only clear when all are done
return made / t
n = 2000
out = np.minimum(rng.lognormal(5.0, 1.0, n).astype(int) + 1, 2048) # skewed output lengths
print(f"outputs: mean {out.mean():.0f}, median {np.median(out):.0f}, max {out.max()} tokens; "
f"{KV_TOKENS // MAX_LEN} slots if each reserves {MAX_LEN} tokens")
for name, lo, hi in [("chat, prompts 20-300", 20, 300), ("RAG, prompts 200-2000", 200, 2000)]:
prompt = rng.integers(lo, hi, n)
r = {p: run(p, prompt, out) for p in ("static", "continuous", "paged")}
print(f"{name:22s} " + " ".join(f"{p} {v:6.0f} tok/s" for p, v in r.items()))
outputs: mean 234, median 144, max 2048 tokens; 111 slots if each reserves 4096 tokens
chat, prompts 20-300 static 2987 tok/s continuous 10530 tok/s paged 16053 tok/s
RAG, prompts 200-2000 static 1997 tok/s continuous 3833 tok/s paged 4190 tok/s
Read the two rows carefully. For chat, continuous batching gives 3.5× over static and paging another 1.5×, because short contexts mean the weights dominate the bytes moved, so a bigger batch amortises more. For RAG the gains are smaller. Long prompts make (a) prefill a large share of total time (the model runs prefills one at a time, without chunking) and (b) KV reads dominate each decode step, and KV reads are not amortised by batching. Both point to the next levers: chunked prefill, prefix caching for the shared documents, and a smaller KV cache.
The second experiment implements speculative sampling, checks that its output is distributed exactly as the target, and checks the expected-tokens formula.
import numpy as np
rng = np.random.default_rng(0)
V = 50 # toy vocabulary
def softmax(z): e = np.exp(z - z.max()); return e / e.sum()
def speculative_step(p, q):
"""One draft token from q, verified against target p. Returns the emitted token."""
x = rng.choice(V, p=q)
if rng.random() < min(1.0, p[x] / q[x]): # accept with prob min(1, p/q)
return x, True
resid = np.maximum(p - q, 0); resid /= resid.sum() # otherwise resample from (p - q)+
return rng.choice(V, p=resid), False
logits = rng.normal(0, 2, V)
p = softmax(logits) # the big model
q = softmax(logits + rng.normal(0, 1.0, V)) # a draft that roughly agrees
alpha = np.minimum(p, q).sum() # predicted acceptance = 1 - TV(p, q)
draws = [speculative_step(p, q) for _ in range(200_000)]
tokens = np.array([d[0] for d in draws]); acc = np.mean([d[1] for d in draws])
emp = np.bincount(tokens, minlength=V) / len(tokens)
print(f"acceptance: predicted {alpha:.3f}, measured {acc:.3f}")
direct = np.bincount(rng.choice(V, size=len(tokens), p=p), minlength=V) / len(tokens)
tv = lambda a, b: 0.5 * np.abs(a - b).sum()
print(f"TV(speculative output, p) = {tv(emp, p):.4f} vs TV(direct samples of p, p) = {tv(direct, p):.4f}"
f" vs TV(q, p) = {tv(q, p):.4f}")
# Tokens emitted per target forward pass with gamma drafted tokens, i.i.d. acceptance alpha
for a in (0.6, 0.8, 0.9):
for g in (2, 4, 8):
sim = []
for _ in range(20_000):
k = 0
while k < g and rng.random() < a: k += 1 # accepted prefix length
sim.append(k + 1) # +1: correction or bonus token
formula = (1 - a ** (g + 1)) / (1 - a)
speed = formula / (g * 0.05 + 1) # draft costs 5% of a target pass
print(f"alpha={a} gamma={g}: {np.mean(sim):.2f} tokens/pass (formula {formula:.2f}), "
f"speed-up {speed:.2f}x")
acceptance: predicted 0.560, measured 0.561
TV(speculative output, p) = 0.0039 vs TV(direct samples of p, p) = 0.0041 vs TV(q, p) = 0.4395
alpha=0.6 gamma=2: 1.96 tokens/pass (formula 1.96), speed-up 1.78x
alpha=0.6 gamma=4: 2.30 tokens/pass (formula 2.31), speed-up 1.92x
alpha=0.6 gamma=8: 2.49 tokens/pass (formula 2.47), speed-up 1.77x
alpha=0.8 gamma=2: 2.45 tokens/pass (formula 2.44), speed-up 2.22x
alpha=0.8 gamma=4: 3.35 tokens/pass (formula 3.36), speed-up 2.80x
alpha=0.8 gamma=8: 4.31 tokens/pass (formula 4.33), speed-up 3.09x
alpha=0.9 gamma=2: 2.70 tokens/pass (formula 2.71), speed-up 2.46x
alpha=0.9 gamma=4: 4.09 tokens/pass (formula 4.10), speed-up 3.41x
alpha=0.9 gamma=8: 6.13 tokens/pass (formula 6.13), speed-up 4.38x
The speculative output is as close to \(p\) as 200,000 direct samples from \(p\) are, even though the draft itself is far from \(p\) (TV 0.44). Only the speed depends on the draft.
Things to try
- Add chunked prefill to the simulator: give each step a token budget of 2,048, charge the step \(\max(\text{decode bytes}/\beta,\ 2N \times \text{tokens}/P)\), and spread each prompt over several steps. How does RAG throughput change? Track the worst inter-token gap as well.
- Add prefix caching to the RAG workload: assume 80% of each prompt is one of 20 shared documents and skip its prefill on a cache hit.
- Store the weights at 4.25 bits (
W_BYTES = 8.03e9 * 4.25 / 8) and halveKV_TOK(FP8 cache). Which workload gains more, and why? - In the speculative script, make the draft worse (
rng.normal(0, 3.0, V)) and confirm the output distribution is still exact while acceptance drops. - Find the best \(\gamma\) for \(\alpha = 0.7\) and draft costs \(c\) = 0.02, 0.1 and 0.3.
In practice¶
| Engine (as of 2026) | Notes |
|---|---|
| vLLM | PagedAttention's home; continuous batching, chunked prefill, prefix caching, speculative decoding, many quantisation formats; the common default |
| SGLang | RadixAttention prefix caching, fast constrained decoding, strong on agent and multi-call workloads |
| TensorRT-LLM | NVIDIA's engine; compiled kernels, FP8/FP4 on Hopper and Blackwell |
| Text Generation Inference | Hugging Face's server |
| llama.cpp, MLX, Ollama | single-user and local serving; see on-device AI |
- Benchmark with your traffic. Throughput numbers depend heavily on prompt and output length distributions, prefix overlap and concurrency. Replay real request logs or realistic synthetic ones, and report goodput at your latency targets, not peak tokens/s.
- Size memory for concurrency. Use Little's law on expected peak load, multiply by mean context × KV bytes per token, and add headroom. If that exceeds memory, shrink the KV cache (FP8, a GQA/MLA model) before adding GPUs.
- Order prompts for caching. Stable content (system prompt, tools, documents) first, per-request content last. Keep the stable part byte-identical: a timestamp at the top of the system prompt defeats every prefix cache.
- Watch tail latency, not averages. Long-prompt stalls, preemptions and recomputation show up at p99 first.
- Use speculative decoding for latency-sensitive, low-concurrency paths (interactive coding, single-user agents). Prompt-lookup drafts are free for edit-style tasks.
Common misconceptions¶
\"Throughput and latency are the same goal.\"
Larger batches raise throughput and slow every user's tokens; speculative decoding speeds one user up and may lower total throughput at high load. Choose a latency target, then maximise throughput under it: goodput.
\"Speculative decoding is an approximation.\"
With the rejection rule above, the output distribution is exactly the target model's, up to floating-point effects. A poor draft costs speed, never quality. (Some "lossy" variants relax the acceptance rule. Those do change outputs, and say so.)
\"More GPU memory just means a bigger model fits.\"
For serving, spare memory is KV cache, and KV cache is concurrency. The same model on a 141 GB GPU can hold several times as many simultaneous conversations as on an 80 GB one. That is often the bigger win.
\"Prefill is cheap because it happens once.\"
At long prompt lengths (RAG, agents re-sending tool histories), prefill can be most of the GPU time, and attention's quadratic cost makes it worse. Prefix caching and chunking exist because of this.
Check yourself¶
A service receives 30 requests/s; each streams 600 tokens at 40 tokens/s after a 0.5 s TTFT. How many sequences are in flight, and how much KV cache do they need on Llama 3 8B (128 KiB/token) at a mean context of 2,000 tokens?
Time in system = 0.5 + 600/40 = 15.5 s, so by Little's law \(L = 30 \times 15.5 = 465\) sequences. KV: \(465 \times 2000 \times 128\) KiB ≈ 122 GB, more than one H100's free memory (~60 GB). You need two or more replicas, or an FP8 cache (61 GB) on one larger GPU.
Why does continuous batching need 'selective batching' to work with transformers?
Requests in flight have different lengths and are at different stages (some in prefill, most in decode). The matmuls are token-wise, so all tokens can be concatenated into one matrix regardless of sequence. Attention is not: each token must attend to its own sequence's keys and values. Orca batches the token-wise operations and splits only attention per sequence; PagedAttention kernels later made that per-sequence attention efficient over paged memory.
With block size 16, what is the worst-case KV waste per sequence under paging, and why not use block size 1?
At most 15 token slots, in the last partly filled block. Block size 1 would waste nothing but would make the block table as long as the sequence. The attention kernel would gather every token from a random address, losing coalesced memory access and adding table-lookup overhead. Blocks of 16–32 balance fragmentation against kernel efficiency.
Draft acceptance is 0.7 and a draft step costs 10% of a target pass. Compare γ = 3 and γ = 6.
γ = 3: tokens per pass \((1 - 0.7^4)/0.3 = 2.53\), cost 1.3, speed-up 1.95×. γ = 6: \((1 - 0.7^7)/0.3 = 3.06\), cost 1.6, speed-up 1.91×. Longer drafts add little once \(\alpha^\gamma\) is small, and their cost keeps growing; γ ≈ 3–4 is about optimal here.
Why does speculative decoding help less at batch 128 than at batch 1?
At batch 1, verifying 5 positions costs about the same as 1, because the step is bandwidth-bound and the extra FLOPs are free. At batch 128 the step already does \(128 \times 2N\) FLOPs per pass, closer to the compute ridge; verifying 5 positions per sequence multiplies the FLOPs by about 5 and the step is no longer free. Rejected tokens are then wasted compute that other users could have used.
Hard: in a disaggregated system, when does shipping the KV cache cost more than recomputing the prefill on the decode GPU?
Transfer time ≈ \(s \cdot k / \text{link bandwidth}\); recompute ≈ \(2Ns/(P \cdot \text{MFU})\). Both are linear in \(s\) (ignoring attention's quadratic term), so the ratio is \(k\,P\,\text{MFU} / (2N \cdot \text{link})\). For Llama 3 8B (\(k\) = 128 KiB) at 50% MFU on an H100 and a 50 GB/s link: \(131072 \times 989\times10^{12} \times 0.5 / (2 \times 8\times10^9 \times 50\times10^9) \approx 0.08\). Transfer is about 12× cheaper. It flips only with very slow links, or with large KV per parameter (no GQA). Recomputation also wastes decode-GPU compute that disaggregation was meant to protect.
Hard: explain why throughput saturates at β/(s·k) in the bandwidth model, and name three ways to raise the ceiling.
Each step reads \(W + B s k\) bytes and produces \(B\) tokens, so throughput is \(B\beta/(W + Bsk) \to \beta/(sk)\) as \(B \to \infty\): the cache, read in full every step, dominates. Raise it by shrinking \(k\) (GQA/MQA/MLA architectures, FP8 or 4-bit KV quantisation), by shrinking the effective \(s\) (prefix sharing so common blocks are stored once, though each sequence still reads them; sliding-window or sparse attention; KV eviction), or by raising \(\beta\) (HBM3e GPUs, more GPUs via tensor parallelism).
Go deeper¶
Papers
- Orca: A Distributed Serving System for Transformer-Based Generative Models — Yu et al., OSDI 2022. Iteration-level scheduling and selective batching: continuous batching's origin.
- Efficient Memory Management for Large Language Model Serving with PagedAttention — Kwon et al., SOSP 2023. Read §3 (where the memory goes) and §4 (blocks, sharing, preemption).
- SGLang: Efficient Execution of Structured Language Model Programs — Zheng et al., 2023. RadixAttention prefix caching and compressed FSMs for constrained decoding.
- Taming Throughput-Latency Tradeoff in LLM Inference with Sarathi-Serve — Agrawal et al., OSDI 2024. Chunked prefill and stall-free scheduling.
- DistServe — Zhong et al., OSDI 2024. Disaggregation and the goodput objective.
- Mooncake: A KVCache-centric Disaggregated Architecture for LLM Serving — Qin et al., 2024. A production system (Kimi) built around the KV cache.
- Fast Inference from Transformers via Speculative Decoding — Leviathan et al., 2022. The algorithm, its proof and the speed-up analysis (§3).
- Accelerating Large Language Model Decoding with Speculative Sampling — Chen et al., 2023. The same idea found independently at DeepMind, on Chinchilla 70B.
- EAGLE-3 — Li et al., 2025. The current shape of high-acceptance drafters.
Videos and lectures
- Fast LLM Serving with vLLM and PagedAttention — the vLLM team, Anyscale. The Berkeley vLLM team explains the design and implementation.
- Deep Dive: Optimizing LLM inference — Julien Simon. KV cache, continuous batching, speculative decoding and more in one sitting.
- CS336: Language Modeling from Scratch — Stanford, 2025. The inference lecture covers this page's arithmetic and algorithms.
Articles and blog posts
- How continuous batching enables 23x throughput in LLM inference — Daniel et al., Anyscale, 2023. The clearest picture of static versus continuous batching, with measurements.
- All About Transformer Inference — How to Scale Your Model, Google DeepMind. Latency and throughput rooflines for inference, worked carefully.
- Large Transformer Model Inference Optimization — Lilian Weng, 2023. A wide survey of the techniques.
- Flash-Decoding for long-context inference — Dao, Haziza, Massa and Sizov, 2023. Why decode attention needs its own kernel.
- Looking back at speculative decoding — Google Research. The inventors on how the idea reached production.
Code
- vllm-project/vllm — Read the scheduler and the block manager to see this page as code.
- sgl-project/sglang — The radix-tree cache is a compact, readable data structure.
- SafeAILab/EAGLE — Reference EAGLE-½/3 drafters.
Where this leads¶
- Shipping AI products: latency budgets, routing between models, caching and cost as product decisions.
- Quantisation: the most direct way to cut both weight and KV-cache bytes.
- On-device AI: serving one user on a laptop or phone, where batch 1 is all there is.
- KV cache, FlashAttention, MQA/GQA/MLA: architecture changes that shrink \(k\), the term that caps throughput.
- MLOps: running all this as a reliable service, with monitoring and rollouts.