Contents
Key concepts
Prefill vs decode and the latency metrics
Prefill runs the whole prompt in one parallel pass (large matmuls, compute-bound) and determines time-to-first-token (TTFT). Decode generates one token per step per sequence, reading all weights and the KV cache each step (memory-bound) and determines inter-token latency (ITL/TPOT). Throughput (tokens/s across users) and per-user latency pull in opposite directions; SLOs are usually stated as p95 TTFT and p95 ITL at a target concurrency.
Decoding strategies
Greedy takes the argmax; beam search keeps the k best partial sequences (good for short, single-answer tasks such as translation, prone to bland repetition in open-ended text). Sampling divides logits by temperature T then truncates: top-k keeps the k most likely tokens, top-p keeps the smallest set whose probability mass reaches p, min-p keeps tokens with probability at least p times the top token’s. Practical defaults: JSON extraction uses T=0 or very low plus constrained decoding against a schema; creative writing uses T≈0.8–1.0 with top-p≈0.9–0.95 or min-p≈0.05–0.1; code completion uses low T (0–0.3), with higher T only when sampling many candidates to test. Hosted reasoning models increasingly fix sampling: from API version 2026-10-21 Claude rejects temperature, top_p and top_k, so consistency there comes from prompts, structured outputs, validation and caching.
Why temperature 0 is not deterministic
Floating-point addition is not associative, and production kernels (matmul, attention, RMSNorm) choose reduction orders that depend on batch size and chunking. Because server load changes the batch a request lands in, logits differ in the last bits and a near-tie argmax can flip, after which the continuation diverges. MoE routing, speculative decoding, provider-side model or kernel updates and prefix-cache hits add further variation. Remedies: batch-invariant kernels where available, fixed seeds and pinned model versions, caching results when exact replay matters, and evals that tolerate variation.
Static vs continuous batching
Static batching waits for a whole batch to finish, so short requests idle behind long ones and new requests queue. Continuous (iteration-level) batching, introduced by Orca, schedules at every decode step: finished sequences leave and new ones join immediately. Remaining problems: KV-cache pressure and preemption, long prefills stalling everyone’s decode (mitigated by chunked prefill or disaggregating prefill and decode onto separate GPUs), fairness and head-of-line blocking, and tuning max batch size against ITL SLOs.
Flow · 5 stepsStatic vs continuous batching
- Requests arrive Requests arrive and either enter a static batch or the continuous decode loop.
- Static batching Static batching waits for a whole batch to finish, so short requests idle behind long ones and new requests queue.
- Continuous batching Continuous (iteration-level) batching, introduced by Orca, schedules at every decode step.
- Leave and join Finished sequences leave and new ones join immediately at every decode step.
- Remaining problems KV-cache pressure and preemption, long prefills stalling decode, fairness and head-of-line blocking, and tuning max batch size against ITL SLOs.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Requests arrive | Requests arrive and either enter a static batch or the continuous decode loop. |
| 2 | Static batching | Static batching waits for a whole batch to finish, so short requests idle behind long ones and new requests queue. |
| 3 | Continuous batching | Continuous (iteration-level) batching, introduced by Orca, schedules at every decode step. |
| 4 | Leave and join | Finished sequences leave and new ones join immediately at every decode step. |
| 5 | Remaining problems | KV-cache pressure and preemption, long prefills stalling decode, fairness and head-of-line blocking, and tuning max batch size against ITL SLOs. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| Requests arrive | Input | |
| Static batch | Static | waits for the whole batch |
| Short requests idle | Static | new requests queue |
| Decode step | Continuous | Orca, every step |
| Finished sequences leave | Continuous | |
| New sequences join | Continuous | immediately |
| Remaining problems | Limits | KV pressure, preemption, prefill stalls |
Source: This page's text
Quantisation choices
Weight-only INT4 (GPTQ uses approximate second-order information; AWQ protects activation-salient channels via scaling) cuts bytes per weight ~4× versus bf16, which directly speeds memory-bound decode at small batch but dequantisation overhead limits gains at large batch. FP8 weights and activations (W8A8) use FP8 tensor cores on Hopper/Blackwell and help compute-bound prefill and large batches; 4-bit floating formats (NVFP4/MXFP4) extend this on Blackwell. KV-cache quantisation (FP8/INT8) raises concurrency and long-context capacity. Accept a quantised model only after task evals, long-context and multilingual slices, and output-distribution checks (e.g. KL or token agreement against the bf16 model), not just perplexity.
Speculative decoding
A cheap drafter proposes k tokens; the target model scores all k+1 positions in one forward pass and accepts each draft token with probability min(1, p_target/p_draft), resampling from the residual distribution on the first rejection. This provably preserves the target’s output distribution. Drafters include a small model, n-gram/prompt lookup, extra heads (Medusa), feature-level drafters (EAGLE) and built-in multi-token-prediction heads. It helps because a decode step is bandwidth-bound, so verifying k tokens costs about the same as generating one; it helps little at high batch (already compute-bound), with low acceptance (high temperature, domain shift) or when the drafter is expensive. Since 2026, parallel drafters (P-EAGLE, block-diffusion DFlash, DeepSeek’s DSpark) propose a whole block in one forward pass, so drafting cost no longer grows with speculation length.
Parallelism and deployment shape
Tensor parallelism splits each matmul across GPUs (cuts latency, needs NVLink-class bandwidth); pipeline parallelism splits layers (crosses nodes, adds bubbles); data parallelism replicates for throughput; expert parallelism spreads MoE experts. Choose the smallest TP that fits weights plus the KV budget, then scale out with replicas.
Edge and CPU inference
On phones and laptops the ceiling is memory bandwidth and RAM. A 3B model at 4-bit is ~1.7–2 GB; with ~60 GB/s of LPDDR5X bandwidth the decode ceiling is roughly 30 tokens/s before overheads. Prefill is compute-bound on the CPU/NPU, so long prompts hurt TTFT; thermal throttling, memory pressure from other apps and tokenizer/runtime overhead matter as much as the model.
Worked examples
Decode throughput ceiling for an 8B model on one H100
An 8B dense model runs on an H100 SXM (3.35 TB/s HBM, ~989 dense bf16 TFLOP/s). Estimate the single-stream decode ceiling in bf16 and INT4, and the batch size at which decode stops being bandwidth-bound (ignore KV reads at first).
bf16, batch 1: each token reads all weights, 8e9 × 2 B = 16 GB. 3.35e12 / 16e9 ≈ 209 tokens/s upper bound; real systems reach perhaps 60–75% of this.
INT4 weights: ~0.5 B/param plus scales ≈ 4.5 GB → 3.35e12 / 4.5e9 ≈ 740 tokens/s ceiling, which is why weight-only quantisation is the first lever for interactive latency.
When does batching stop helping? Per step, FLOPs ≈ 2 × params × batch, bytes ≈ 2 × params (bf16 weights read once). Arithmetic intensity ≈ batch FLOPs/byte. The H100 ridge point is 989e12 / 3.35e12 ≈ 295 FLOPs/byte, so the weight matmuls stay memory-bound until a batch of roughly 300.
Caveat: KV reads grow with batch × context and are not amortised, so at long context the attention part stays bandwidth-bound and the practical batch limit is KV memory, not FLOPs.
CalculatorDecode throughput ceiling for an 8B model on one H100
- Single-stream decode ceiling
- 209 tokens/s
- Ridge point
- 295 FLOPs/byte
- Batch limit
- 295 sequences
Single-stream decode ceiling = HBM bandwidth × 1000 ÷ Weight bytes = 209 tokens/s
Ridge point = Dense bf16 compute ÷ HBM bandwidth = 295 FLOPs/byte
Batch limit = Ridge point × Weight bytes ÷ 16 = 295 sequences
| Case | HBM bandwidth (TB/s) | Dense bf16 compute (TFLOP/s) | Weight bytes (GB) | Single-stream decode ceiling | Ridge point | Batch limit |
|---|---|---|---|---|---|---|
| bf16, batch 1 | 3.35 | 989 | 16 | 209 tokens/s | 295 FLOPs/byte | 295 sequences |
| INT4 weights | 3.35 | 989 | 4.5 | 744 tokens/s | 295 FLOPs/byte | 83 sequences |
Expected speed-up from speculative decoding
A drafter costs c = 0.05 of a target forward pass and proposes k = 4 tokens. Using the standard i.i.d. acceptance model, estimate the speed-up for acceptance rates α = 0.8 and α = 0.5.
Expected tokens produced per target pass (accepted drafts plus the one the target always adds): E = (1 − α^(k+1)) / (1 − α). Cost per round in target-pass units: k × c + 1 = 4 × 0.05 + 1 = 1.2.
α = 0.8: E = (1 − 0.8^5) / 0.2 = (1 − 0.32768) / 0.2 = 3.36 → speed-up ≈ 3.36 / 1.2 ≈ 2.8×.
α = 0.5: E = (1 − 0.5^5) / 0.5 = 0.96875 / 0.5 = 1.94 → speed-up ≈ 1.94 / 1.2 ≈ 1.6×.
Acceptance dominates: domain shift or high temperature can erase most of the gain, and at large batch the “free” verification no longer holds. Tune k per workload and measure at the production concurrency, not at batch 1.
Temperature and top-p by hand
Logits for four tokens are [2.0, 1.0, 0.5, −1.0]. Compute probabilities at T = 1 and T = 0.5, then the candidate set and renormalised probabilities for top-p = 0.9 at T = 1.
T = 1: exp → [7.389, 2.718, 1.649, 0.368], sum 12.124 → p = [0.610, 0.224, 0.136, 0.030].
T = 0.5 (logits ÷ 0.5 = [4, 2, 1, −2]): exp → [54.60, 7.39, 2.72, 0.135], sum 64.84 → p = [0.842, 0.114, 0.042, 0.002]. Lower temperature sharpens towards the argmax.
Top-p 0.9 at T = 1: cumulative mass 0.610 → 0.834 → 0.970. The smallest prefix reaching 0.9 is the first three tokens. Renormalise by 0.970: [0.628, 0.231, 0.140]; the −1.0 token can no longer be sampled.
Order matters in implementations: most libraries apply temperature before top-k/top-p, and min-p at 0.1 here would keep tokens above 0.1 × 0.610 = 0.061, giving the same three tokens.
What changed recently
Claude's API drops temperature, top_p and top_k
From API version 2026-10-21, a Claude request that sends temperature, top_p or top_k is rejected with a 400 error; requests sample with the defaults (temperature 1.0), and Claude 4.7 and later models already accepted only defaults. Anthropic’s migration guide says no other setting replaces a lowered temperature, so consistency now comes from prompts, schemas, validation and caching. Interviewers probe whether you know which knobs a hosted model still exposes and what that means for determinism and evals.
Parallel drafting for speculative decoding
A new class of speculators (P-EAGLE, block-diffusion DFlash and DeepSeek’s DSpark, which adds a confidence head that forwards only likely-accepted tokens) proposes a whole block of draft tokens in one forward pass instead of one token per pass as EAGLE-3 does. Drafting cost no longer grows with speculation length, so drafters can be larger and easier to tune under changing load, and vLLM reports clear gains over EAGLE-3. Expect questions on acceptance length, verification cost and why gains shrink at high batch.
llm-d: Kubernetes-native disaggregated serving
Red Hat, Google and IBM engineers launched llm-d, which runs vLLM behind the Kubernetes Inference Gateway with prefix-cache-aware and load-aware routing, prefill/decode disaggregation over vLLM’s KV connector (NIXL transport) and KV-cache tiering. It made cache-aware routing and disaggregation standard components of open serving stacks, which system-design interviews now expect you to place correctly.
NVIDIA Dynamo and disaggregated prefill/decode
NVIDIA’s open-source Dynamo framework splits compute-bound prefill and bandwidth-bound decode onto separate GPUs, with a planner that rebalances them against TTFT and inter-token-latency targets, a router that sends requests to GPUs already holding matching KV cache, KV offload to cheaper tiers and the NIXL transfer library. Its projections (up to 30× more requests for DeepSeek-R1 on GB200 NVL72) are vendor numbers, but the architecture is now a common reference design for serving large reasoning models.
EAGLE-3: drafters that scale with data
EAGLE-3 stopped predicting target-model features and predicts draft tokens directly from fused low-, mid- and high-level features, trained with a ‘training-time test’ that simulates multi-step drafting, so the drafter keeps improving with more training data. It reported up to 6.5× speed-up but about 1.38× throughput at batch 64 in SGLang, a good illustration of why speculative decoding gains depend on batch size.
Pitfalls
- Claiming temperature 0 (or a fixed seed) guarantees identical outputs from a production endpoint.
- Saying speculative decoding trades quality for speed; with correct rejection sampling the output distribution is unchanged.
- Expecting speculative decoding or weight-only INT4 to help at large batch, where decode is closer to compute-bound.
- Judging a quantised model on perplexity or a single benchmark instead of task evals and long-context slices.
- Benchmarking throughput at batch 1 or with uniform synthetic prompt lengths, then promising it in production.
- Using beam search for open-ended chat and getting repetitive, generic text.
How interviewers probe it
- Pick decoding settings for JSON extraction, creative writing and code completion, and justify each.
- A stakeholder insists temperature 0 must be deterministic; explain the cause and the options.
- Why does static batching waste GPU capacity, how does continuous batching fix it, and what breaks next (prefill interference, preemption)?
- Halve serving cost without retraining: rank quantisation, speculative decoding, batching and caching, and the quality risks you would measure.
- Coding: implement temperature, top-k and top-p sampling over a logits vector with a seed, then vectorise for per-row parameters.
- Leadership framing: which latency and cost levers exist, and what does each trade away?
Quiz
Three questions from this guide. Answer each in your head or out loud, show the model answer, then rate yourself. The cards join your practice deck and come back when they are due.
Explain greedy decoding, beam search, temperature, top-k, top-p and min-p. Which settings would you pick for (a) a JSON extraction endpoint, (b) a creative-writing feature, (c) code completion — and why?
Model answer, written in a candidate's voice
- Temperature scales logits before softmax; lower T sharpens towards greedy, higher T flattens; top-k keeps k highest-probability tokens; top-p keeps smallest set with cumulative probability >= p; min-p keeps tokens above a fraction of the top token’s probability.
- Greedy picks argmax each step; beam search keeps B highest-likelihood partial sequences and is good for short constrained outputs like translation/ASR but bland/repetitive and costly for open-ended text.
- (a) JSON extraction: greedy or very low temperature plus schema-constrained/structured decoding, stop sequences, max tokens, validation/retry.
- (b) Creative writing: moderate temperature with top-p (or min-p), repetition penalty, stop sequences, max tokens; avoid greedy.
- (c) Code completion: low temperature/greedy, optionally best-of-n samples ranked by tests/static checks/self-consistency, with stop sequences and max tokens.
Given a logits vector, implement sampling with temperature, top-k and top-p and a fixed seed. Then explain how you would vectorise it across a batch where each row has different parameters.
Model answer, written in a candidate's voice
- Stable softmax: subtract row max; temperature 0 handled as argmax
- Top-k via argpartition/kthvalue; top-p via descending sort and cumulative mass, keeping the crossing token and at least one token, then renormalise
- Fixed-seed RNG; sample via inverse CDF from cumulative probabilities
- Batch: per-row T,k,p; mask with -inf rather than slicing; one sort/topk plus rank/cumulative masks; GPU-friendly
- Tests: many-draw distribution sanity; p=1, k=1, T=0, ties; reproducibility
A stakeholder insists outputs must be identical because temperature is 0, yet your logs show different answers to the same prompt. Explain why and say what you would do.
Model answer, written in a candidate's voice
- Temperature 0 is greedy, not bitwise deterministic; floating-point reductions are non-associative, so batch size/composition and kernel choice change reduction order and can flip near-tied logits, causing the continuation to diverge.
- Other causes: MoE routing effects, different replicas/hardware, speculative decoding implementations, silent provider model updates, and prompts that are not actually identical (timestamps, retrieved documents, tool outputs).
- Mitigations: pin model snapshots, use seed parameters where offered as best-effort, cache responses for identical inputs, and use batch-invariant kernels if self-hosting.
- Design tests/evals to tolerate variation with semantic/structural checks instead of exact match; determinism is not correctness.
You have finished this topic.
Reading
- How to generate text: using different decoding methods for language generation with TransformersHands-on walkthrough of greedy, beam, temperature, top-k and top-p sampling.
- The Curious Case of Neural Text DegenerationWhy likelihood-maximising decoding degenerates and the case for nucleus (top-p) sampling.
- Orca: A Distributed Serving System for Transformer-Based Generative ModelsThe original iteration-level scheduling paper behind continuous batching.
- Fast Inference from Transformers via Speculative DecodingDerives the acceptance rule and the expected speed-up formula used in interviews.
- AWQ: Activation-aware Weight Quantization for LLM Compression and AccelerationExplains why a few salient channels dominate weight-only quantisation error.
- Defeating Nondeterminism in LLM InferenceShows that batch-size-dependent kernels, not just concurrency, make temperature-0 outputs vary.
- Inside vLLM: Anatomy of a High-Throughput LLM Inference SystemOne walk-through of a modern engine: continuous batching scheduler, paged KV, chunked prefill, prefix caching, speculative decoding and disaggregated prefill/decode.
- Taking vLLM Apart: A Practical Guide to Disaggregated ServingMeasured cases where splitting prefill and decode helps or hurts, including the cost of moving the KV cache.
Practise this topic
- Explain greedy decoding, beam search, temperature, top-k, top-p and min-p. Which settings would you pick for (a) a JSON extraction endpoint, (b) a creative-writing feature, (c) code completion — and why?
- Given a logits vector, implement sampling with temperature, top-k and top-p and a fixed seed. Then explain how you would vectorise it across a batch where each row has different parameters.
- A stakeholder insists outputs must be identical because temperature is 0, yet your logs show different answers to the same prompt. Explain why and say what you would do.
- Why does static batching waste GPU capacity for LLMs, how does continuous batching fix it, and what new problems appear?
- Compare weight-only INT4 (GPTQ/AWQ), FP8 weights-and-activations and KV-cache quantisation. How would you decide a quantised model is acceptable for production?
- How does speculative decoding speed up generation without changing the output distribution, and when does it not help?
- Design, and partly code, a single-GPU inference service that batches incoming requests up to a maximum batch size while each caller waits synchronously for its own result. How do you trade latency against throughput?
- How would you get a 3B-parameter LLM running interactively on a phone-class Arm CPU, and where are the bottlenecks?
- You must halve serving cost for a large model without retraining it from scratch. Discuss quantisation (INT8/FP8/4-bit), speculative decoding and batching: what each buys you and which quality risks you would measure.
- What levers do you have for cutting LLM latency and cost, and what does each trade away?
- Write the attention formula. Explain the time and memory complexity in sequence length, why scaling by √d matters, and how a KV cache changes decoding cost.
- What limits LLM decode throughput, and how do continuous batching, paged KV cache, quantisation and speculative decoding help?
- For three weeks users have complained that your hosted model ‘got worse’, yet your benchmarks, safety evals and canary deployments are all green. Reports are inconsistent across regions and cloud platforms. How do you investigate?
- You are asked to serve a hybrid model with 48 layers: 36 Gated DeltaNet (linear-attention) layers and 12 full-attention layers with 2 KV heads of dimension 256. Estimate KV memory per token in bf16, compare it with an all-attention version, and explain what changes for prefix caching.
- Your team serves a large MoE reasoning model with long prompts and long outputs, and p95 inter-token latency spikes whenever big prompts arrive. Someone proposes disaggregating prefill and decode. When does that pay off, what does it cost, and how would you size it?
- You are evaluating speculative decoding for production: an EAGLE-3 drafter versus the model’s own multi-token-prediction heads. Which metrics decide it, how does the answer change with batch size and with reasoning workloads, and how do you prove outputs are unchanged?
- A document-QA product re-sends the same 60k-token contract across many sessions spread over hours, so GPU prefix-cache hits are rare. Would you offload KV cache to CPU memory or SSD and reload it instead of recomputing? Show the arithmetic.
- gpt-oss-120b (117B total, 5.1B active parameters) ships its weights in MXFP4 and runs within 80 GB. Check that claim with arithmetic, then compare MXFP4 with NVFP4 and explain what you would test before serving a model in either format.
- Your product serves a 70B model in FP8 on Hopper GPUs. Leadership asks whether moving to Blackwell with NVFP4 weights will halve the serving cost. Explain what NVFP4 is and how you would answer.
- Explain how EAGLE-3 differs from classic draft-model speculative decoding and from reusing a model’s own multi-token-prediction module, as DeepSeek-V3 does. When would you switch speculation off in production?
- You are moving about 3,000 concurrent coding agents from a managed API to a self-hosted open model served with vLLM on Kubernetes. Why does a standard Kubernetes Service balance this traffic badly, and what would your routing, scheduling and model-upgrade design look like?
- Qwen3-Omni separates a ‘Thinker’ that produces text from a ‘Talker’ that streams speech codec tokens. Why decouple them, how does a multi-codebook codec affect first-packet latency, and how would you evaluate a streaming speech output stage like this?
- You must serve a DeepSeek-style mixture-of-experts model (hundreds of billions of parameters, 256 routed experts, MLA attention) for an agentic coding product. Explain why the large public deployments since 2025 use disaggregated prefill and decode with wide expert parallelism and data-parallel attention rather than tensor parallelism, and what new failure modes this design introduces.
- What does a key–value cache store during autoregressive generation? Give the formula for its memory footprint, explain why decoding is usually memory-bandwidth-bound, and describe how grouped-query or multi-query attention changes this.
- Design the serving stack for a large multimodal assistant used by millions of people. Where are the bottlenecks?