LearnTopic guide

LLM inference: decoding, batching, quantisation and speculative decoding

Inference is everything between a trained checkpoint and a token on the user’s screen: how the next token is chosen (greedy, sampling, beam), how requests are batched on a GPU, how weights and caches are compressed, and how tricks such as speculative decoding cut latency without changing outputs. The physics is simple and examinable: prefill is compute-bound, decode is memory-bandwidth-bound, and most optimisations either raise arithmetic intensity (batching) or cut bytes moved (quantisation, GQA). Interviewers probe whether you can pick decoding settings for a product, explain why temperature 0 is not deterministic, estimate throughput from hardware numbers, and say what each optimisation costs in quality or latency.

Applied LLM · ML engineering · Research · AI leadership8 key concepts25 questions

Start: Key concepts 6 lessons · about 16 min
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

Static vs continuous batchingA flow diagram with four groups. Requests arrive and either enter a static batch that waits for the whole batch, leaving short requests idle and new requests queued, or enter a continuous decode loop where finished sequences leave and new ones join at every step. A final box lists the 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.Requests arriveStatic batchwaits for the wholebatchDecode stepOrca, every stepShortrequestsidlenewrequestsqueueFinishedsequencesleaveRemainingproblemsKVpressure,preemption,prefillstallsNewsequencesjoinimmediately12345InputStaticContinuousLimits
  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.

Static batching waits for the whole batch to finish, while continuous (iteration-level) batching schedules at every decode step so finished sequences leave and new ones join immediately.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Steps
StepTitleWhat happens
1Requests arriveRequests arrive and either enter a static batch or the continuous decode loop.
2Static batchingStatic batching waits for a whole batch to finish, so short requests idle behind long ones and new requests queue.
3Continuous batchingContinuous (iteration-level) batching, introduced by Orca, schedules at every decode step.
4Leave and joinFinished sequences leave and new ones join immediately at every decode step.
5Remaining problemsKV-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

Boxes
BoxGroupDetail
Requests arriveInput
Static batchStaticwaits for the whole batch
Short requests idleStaticnew requests queue
Decode stepContinuousOrca, every step
Finished sequences leaveContinuous
New sequences joinContinuousimmediately
Remaining problemsLimitsKV 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.

Next: Worked examples Lesson 3 of 6 · about 3 min

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 = HBM bandwidth × 1000 ÷ Weight bytes

Ridge point = Dense bf16 compute ÷ HBM bandwidth

Batch limit = Ridge point × Weight bytes ÷ 16

Worked cases
CaseHBM bandwidth (TB/s)Dense bf16 compute (TFLOP/s)Weight bytes (GB)Single-stream decode ceilingRidge pointBatch limit
bf16, batch 13.3598916209 tokens/s295 FLOPs/byte295 sequences
INT4 weights3.359894.5744 tokens/s295 FLOPs/byte83 sequences
Each token reads every weight, so the single-stream ceiling is bandwidth ÷ weight bytes (≈209 tokens/s in bf16, ≈740 in INT4); weight matmuls stay memory-bound up to a batch of about 295.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.

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.

Next: What changed Lesson 4 of 6 · about 3 min

What changed recently

  1. 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.

    Source

  2. 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.

    Source

  3. 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.

    Source

  4. 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.

    Source

  5. 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.

    Source

Next: Pitfalls and interview angles Lesson 5 of 6 · about 2 min

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?
Next: Quiz Lesson 6 of 6 · about 3 min

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.

  1. Question 1 of 3 · Applied LLM · Technical · Easy

    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?

  2. Question 2 of 3 · Applied LLM · Coding · Medium

    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.

  3. Question 3 of 3 · Applied LLM · Technical · Medium

    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.

Reading

Practise this topic

  1. 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?Applied LLM · Technical · Easy
  2. 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.Applied LLM · Coding · Medium
  3. 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.Applied LLM · Technical · Medium
  4. Why does static batching waste GPU capacity for LLMs, how does continuous batching fix it, and what new problems appear?Applied LLM · Technical · Medium
  5. 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?Applied LLM · Technical · Medium
  6. How does speculative decoding speed up generation without changing the output distribution, and when does it not help?Applied LLM · Technical · Hard
  7. 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?Applied LLM · Technical · Hard
  8. How would you get a 3B-parameter LLM running interactively on a phone-class Arm CPU, and where are the bottlenecks?Applied LLM · Technical · Hard
  9. 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.Research · System design · Medium
  10. What levers do you have for cutting LLM latency and cost, and what does each trade away?AI leadership · Technical · Hard
  11. 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.ML engineering · Technical · Hard
  12. What limits LLM decode throughput, and how do continuous batching, paged KV cache, quantisation and speculative decoding help?ML engineering · Technical · Hard
  13. 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?Applied LLM · Technical · Hard
  14. 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.Applied LLM · Technical · Hard
  15. 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?Applied LLM · System design · Hard
  16. 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?Applied LLM · Technical · Hard
  17. 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.Applied LLM · Technical · Hard
  18. 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.Research · Technical · Medium
  19. 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.Applied LLM · Technical · Medium
  20. 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?Applied LLM · Technical · Medium
  21. 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?ML engineering · System design · Hard
  22. 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?ML engineering · Technical · Medium
  23. 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.ML engineering · System design · Hard
  24. 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.Research · Technical · Hard
  25. Design the serving stack for a large multimodal assistant used by millions of people. Where are the bottlenecks?Research · System design · Hard

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.