---
title: "LLM inference: decoding, batching, quantisation and speculative decoding"
url: https://gurkanozkan.ai/learn/topics/inference/
markdown: https://gurkanozkan.ai/learn/topics/inference.md
kind: topic
tracks:
  - Applied LLM
  - ML engineering
  - Research
  - AI leadership
json: https://gurkanozkan.ai/api/learn/topics/inference.json
---

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

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

### 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).

**Solution**

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


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

**Solution**

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.

**Solution**

**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

- **Oct 2026: 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](https://platform.claude.com/docs/en/api/migration-2026-10-21)
- **Jul 2026: 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](https://vllm.ai/blog/2026-07-28-speculators-parallel-drafting)
- **May 2025: 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](https://llm-d.ai/blog/llm-d-announce)
- **Mar 2025: 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](https://developer.nvidia.com/blog/introducing-nvidia-dynamo-a-low-latency-distributed-inference-framework-for-scaling-reasoning-ai-models/)
- **Mar 2025: 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](https://arxiv.org/abs/2503.01840)

## 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?

## Reading

- [How to generate text: using different decoding methods for language generation with Transformers](https://huggingface.co/blog/how-to-generate) (Blog, 25 min, Intro): Hands-on walkthrough of greedy, beam, temperature, top-k and top-p sampling.
- [The Curious Case of Neural Text Degeneration](https://arxiv.org/abs/1904.09751) (Paper, 40 min, Core): Why likelihood-maximising decoding degenerates and the case for nucleus (top-p) sampling.
- [Orca: A Distributed Serving System for Transformer-Based Generative Models](https://www.usenix.org/conference/osdi22/presentation/yu) (Paper, 50 min, Core): The original iteration-level scheduling paper behind continuous batching.
- [Fast Inference from Transformers via Speculative Decoding](https://arxiv.org/abs/2211.17192) (Paper, 40 min, Core): Derives the acceptance rule and the expected speed-up formula used in interviews.
- [AWQ: Activation-aware Weight Quantization for LLM Compression and Acceleration](https://arxiv.org/abs/2306.00978) (Paper, 40 min, Core): Explains why a few salient channels dominate weight-only quantisation error.
- [Defeating Nondeterminism in LLM Inference](https://thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference/) (Blog, 35 min, Core): Shows that batch-size-dependent kernels, not just concurrency, make temperature-0 outputs vary.
- [Inside vLLM: Anatomy of a High-Throughput LLM Inference System](https://vllm.ai/blog/2025-09-05-anatomy-of-vllm) (Blog, 40 min, Core): One 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 Serving](https://vllm.ai/blog/2026-09-29-disaggregated-serving-guide) (Blog, 20 min, Core): Measured 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…](https://gurkanozkan.ai/learn/questions/applied-llm-fnd-07.md)
- [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…](https://gurkanozkan.ai/learn/questions/applied-llm-fnd-08.md)
- [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…](https://gurkanozkan.ai/learn/questions/applied-llm-fnd-09.md)
- [Why does static batching waste GPU capacity for LLMs, how does continuous batching fix it, and what new problems appear?](https://gurkanozkan.ai/learn/questions/applied-llm-srv-02.md)
- [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?](https://gurkanozkan.ai/learn/questions/applied-llm-srv-04.md)
- [How does speculative decoding speed up generation without changing the output distribution, and when does it not help?](https://gurkanozkan.ai/learn/questions/applied-llm-srv-05.md)
- [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…](https://gurkanozkan.ai/learn/questions/applied-llm-srv-10.md)
- [How would you get a 3B-parameter LLM running interactively on a phone-class Arm CPU, and where are the bottlenecks?](https://gurkanozkan.ai/learn/questions/applied-llm-dom-07.md)
- [You must halve serving cost for a large model without retraining it from scratch. Discuss quantisation (INT8/FP8/4-bit), speculative decoding and batching…](https://gurkanozkan.ai/learn/questions/research-cutting-inference-cost-039.md)
- [What levers do you have for cutting LLM latency and cost, and what does each trade away?](https://gurkanozkan.ai/learn/questions/lead-td-08.md)
- [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.](https://gurkanozkan.ai/learn/questions/mle-self-attention-cost-and-the-kv-cache-15.md)
- [What limits LLM decode throughput, and how do continuous batching, paged KV cache, quantisation and speculative decoding help?](https://gurkanozkan.ai/learn/questions/mle-llm-serving-efficiency-63.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-a-debug-01.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-a-kvcache-01.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-a-inference-01.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-a-inference-02.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-a-kvcache-02.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-a-eff-02.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-b-serving-02.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-b-serving-03.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-b-mlops-02.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-b-modalities-03.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-b-serving-01.md)
- [What does a key–value cache store during autoregressive generation? Give the formula for its memory footprint, explain why decoding is usually…](https://gurkanozkan.ai/learn/questions/research-kv-cache-035.md)
- [Design the serving stack for a large multimodal assistant used by millions of people. Where are the bottlenecks?](https://gurkanozkan.ai/learn/questions/research-serving-a-large-multimodal-assistant-081.md)
---

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