Mental model
At every generation step, a language model emits raw unnormalized logits over the vocabulary; decoding transforms those logits via penalties, temperature calibration, and tail truncation into a bounded distribution from which one token is chosen, trading determinism, diversity, tail hallucination risk, and multi-token verification throughput.
Learning outcomes
- Explain temperature scaling as post-hoc logit calibration (Guo et al.) and why preserves rank ordering while reshaping tail entropy.
- Contrast top-, nucleus top-, and min- truncation under peaked versus ambiguous next-token distributions.
- Apply frequency, presence, and repetition penalties cleanly without corrupting structured syntax or required entities.
- Derive speculative decoding acceptance and rejection-sampling math showing why draft-and-verify accelerates generation with zero distribution drift.
Theory
When a transformer completes a forward step, its LM head outputs logits . Temperature scaling (analyzed by Guo et al. for neural network confidence calibration) divides logits by before softmax normalization:
Because division by positive is strictly monotonic, temperature never changes the argmax token. As , mass collapses onto the highest logit; as , distributions flatten toward higher entropy. Because modern networks tend toward overconfidence (ECE miscalibration), adjusting tunes calibration alongside generation diversity.
Temperature & Logit Sampler
Untruncated softmax leaves nonzero probability on tens of thousands of irrelevant tail words. Production samplers prune low-probability tails before drawing:
- Top- sampling keeps the highest-probability tokens. Its flaw is rigidity: retains 49 junk tokens on near-deterministic continuations, while clips valid choices when many continuations compete equally.
- Nucleus (top-) sampling keeps the smallest sorted subset satisfying , adapting support size automatically to uncertainty.
- Min- sampling enforces a relative threshold tied to the top probability: retain token iff . Unlike top-, min- cuts off noisy flat tails at high temperature while retaining genuine competing branches.
To curb repetitive loops, repetition penalty divides positive logits (and multiplies negative logits) of prior tokens by , frequency penalty subtracts proportionally to token count , and presence penalty subtracts once .
At the sequence level, beam search tracks the top hypotheses by length-normalized log-probability—strong for translation or ASR, yet prone to bland repetition in dialogue. Speculative decoding (Leviathan et al., 2022) accelerates autoregressive sampling without shifting the distribution: a fast draft model proposes tokens, and the target model verifies all positions in parallel. Each draft token passes with probability:
Upon rejection (probability ), subsequent draft tokens are discarded and one replacement token is drawn from normalized residual mass , preserving exact target probabilities .
Worked quantitative example
Suppose five candidate tokens carry raw logits .
At , scaled logits yield softmax probabilities . Both top- and min- (floor ) select {tok_0, tok_1} cleanly.
At , logits flatten to probabilities (plus tail terms). Under top-, tokens 3 and 4 (2.6% and 1.1% noise) survive into the nucleus; under min- (floor ), only {tok_0, tok_1, tok_2} survive. Meanwhile, under speculative verification, when draft gives and target gives , acceptance probability is —preventing overconfident draft errors while preserving exactly.
Decoding and sampling strategy comparison
| Strategy | Adaptive Support | Latency Impact | Exact Target | Best Production Workload |
|---|---|---|---|---|
Greedy (T = 0) | 1 token (argmax) | Minimal compute | Deterministic mode only | Deterministic classification & extraction |
| Top- | Fixed tokens | Negligible sort | Truncated approximation | Simple bounded baselines |
| Nucleus Top- | Varies by cumulative mass | Small sort/cumsum | Truncated approximation | General dialogue & summarization |
| Min- | Scales with | Minimal threshold scan | Truncated approximation | Creative coding/writing at |
| Beam Search () | parallel beams | KV cache memory | Sequence-level MAP bias | Machine translation & structured ASR |
| Speculative Decoding | Preserves any target filter | 1.8x–3.0x lower ITL (low batch) | Exact mathematical match | Low-batch interactive latency reduction |
Trade-offs
Low temperature (0.0–0.2) combined with grammar masking maximizes JSON validity and repeatability for tool extraction, yet cannot fix missing context and risks greedy repetition. Higher temperatures (0.6–1.0) boost lexical variety, requiring tight min- or top- pruning so tail noise never breaks syntax or citations.
Deploy speculative decoding carefully across batch regimes: verifying draft tokens accelerates low-batch decode because extra target checks utilize idle Tensor Cores during HBM weight reads. Once concurrent batch size saturates GPU compute, extra verification tokens slow batch throughput. Nor does T = 0 guarantee bit-exact reproducibility across batch sizes due to non-associative floating-point reductions.
Failure modes and misconceptions
- Assuming
temperature = 0guarantees factual accuracy or determinism. Argmax simply emits the highest-scoring token; near-tied FP16/BF16 kernel reductions still shift across batches and hardware. - Applying aggressive repetition penalties to code or JSON. Penalizing recurring quotes, braces, or numeric identifiers triggers malformed syntax and schema failures.
- Combining high temperature (
T > 1.2) with loose top-. Flattening logits across thousands of noisy tail tokens causes incoherent drift before factual errors even surface. - Leaving speculative decoding enabled at peak compute saturation. Gate draft length off dynamically once active batch size exceeds the GPU compute ridge point.
Decision scenario
An engineering IDE assistant serves interactive chat (batch = 1–4 off-peak) alongside automated JSON schema extraction (batch = 96 peak). Teams see malformed JSON when repetition_penalty = 1.15 penalizes repeated keys, plus sluggish 48 ms/token streaming off-peak.
Split decoding contracts by workload: run JSON extraction with temperature = 0.0, repetition_penalty = 1.0, and CFG grammar masking; run interactive coding with temperature = 0.6, min_p = 0.08, and top_p = 0.95, gating speculative decoding strictly to replicas running at batch concurrency at most 16.
Implementation example
This Python sampler applies frequency/presence penalties, numerically stable temperature-scaled softmax, min-/top-/top- filtering, and speculative rejection sampling verification.
pythonimport mathimport randomdef sample_next_token(logits: list[float], counts: dict[int, int], *,temperature: float = 0.7, top_k: int = 40, top_p: float = 0.95, min_p: float = 0.05, freq_pen: float = 0.05) -> tuple[int, list[float]]:adj = [z - freq_pen * counts.get(i, 0) for i, z in enumerate(logits)]if temperature <= 1e-6:best = max(range(len(adj)), key=lambda i: adj[i])return best, [1.0 if i == best else 0.0 for i in range(len(adj))]scaled = [z / temperature for z in adj]max_z = max(scaled)exps = [math.exp(z - max_z) for z in scaled]probs = [e / sum(exps) for e in exps]p_max = max(probs)ranked = sorted(range(len(probs)), key=lambda i: probs[i], reverse=True)[:max(1, top_k)]kept, cum_p = [], 0.0for idx in ranked:if probs[idx] < min_p * p_max:continuekept.append(idx)cum_p += probs[idx]if cum_p >= top_p:breakkept = kept or [ranked[0]]renorm = sum(probs[i] for i in kept)dist = [probs[i] / renorm if i in kept else 0.0 for i in range(len(probs))]return random.choices(kept, weights=[dist[i] for i in kept], k=1)[0], distdef speculative_accept(p_target: float, q_draft: float, u_rand: float) -> bool:return u_rand <= min(1.0, p_target / max(q_draft, 1e-12))tok, dist = sample_next_token([5.0, 4.2, 2.0, 0.5, -1.0], {1: 2}, temperature=0.8, min_p=0.1)assert 0 <= tok < 5 and abs(sum(dist) - 1.0) < 1e-9 and speculative_accept(0.45, 0.60, 0.50)
Why does speculative decoding preserve the target model's exact output distribution while greedy vs high-temperature top-p trade repeatability against tail risk?