FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Sampling and Decoding

How logits temperature top-p and deterministic choices shape generated sequences.

Freshness: current•15 min read•Foundation Models and Multimodal AI

Key Learning Outcomes

  • ✓Explain probability reshaping
  • ✓Choose decoding settings
  • ✓Recognize reproducibility limits
Isometric Diagram LabAI & LLM Systems · 6 steps · 12 min

Autoregressive Sampling & Modern LLM Decoding

Tune Temperature, Top-K, and Top-P nucleus probability thresholds live on next-token distributions.

Open Isometric Walkthrough
Full Technical Reference Document

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.

Raw model logits
Penalties and grammar mask
Temperature softmax scaling
Top-k, top-p, min-p filter
Multinomial or speculative verify
Conceptual teaching model synthesized from:Generation with LLMsFast Inference from Transformers via Speculative DecodingOn Calibration of Modern Neural Networks

Learning outcomes

  • Explain temperature scaling as post-hoc logit calibration (Guo et al.) and why T>0T \gt 0 preserves rank ordering while reshaping tail entropy.
  • Contrast top-kk, nucleus top-pp, and min-pp 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 z∈R∣V∣z \in \mathbb{R}^{|V|}. Temperature scaling (analyzed by Guo et al. for neural network confidence calibration) divides logits by T>0T \gt 0 before softmax normalization:

pi(T)=exp⁡(zi/T)∑j=1∣V∣exp⁡(zj/T)p_i(T) = \frac{\exp(z_i / T)}{\sum_{j=1}^{|V|} \exp(z_j / T)}

Because division by positive TT is strictly monotonic, temperature never changes the argmax token. As T→0T \to 0, mass collapses onto the highest logit; as T>1T \gt 1, distributions flatten toward higher entropy. Because modern networks tend toward overconfidence (ECE miscalibration), adjusting TT tunes calibration alongside generation diversity.

Temperature & Logit Sampler

H = 1.59 bits(Balanced / Creative)
Temperature (T)0.70
0.1 (Argmax)2.0 (Uniform)
Nucleus Top-P (p)1.00
0.1 (Truncated)1.0 (Full)
Top-K (k)8
1 (Greedy)8 (All)
Softmax Probability Distribution P(x_i)Sample Space (Sorted)
return
59.5%
z=5.4
def
25.2%
z=4.8
const
9.3%
z=4.1
class
3.9%
z=3.5
import
1.4%
z=2.8
async
0.4%
z=1.9
yield
0.1%
z=1.2
pass
0.1%
z=0.5
Click sample to draw from distribution

Untruncated softmax leaves nonzero probability on tens of thousands of irrelevant tail words. Production samplers prune low-probability tails before drawing:

  • Top-kk sampling keeps the kk highest-probability tokens. Its flaw is rigidity: k=50k = 50 retains 49 junk tokens on near-deterministic continuations, while k=5k = 5 clips valid choices when many continuations compete equally.
  • Nucleus (top-pp) sampling keeps the smallest sorted subset V(p)V^{(p)} satisfying ∑x∈V(p)p(x)≥p\sum_{x \in V^{(p)}} p(x) \ge p, adapting support size automatically to uncertainty.
  • Min-pp sampling enforces a relative threshold tied to the top probability: retain token ii iff pi≥pbase⋅max⁡jpjp_i \ge p_{\text{base}} \cdot \max_j p_j. Unlike top-pp, min-pp 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 θ>1\theta \gt 1, frequency penalty subtracts αf⋅c(t)\alpha_f \cdot c(t) proportionally to token count c(t)c(t), and presence penalty subtracts αp\alpha_p once c(t)>0c(t) \gt 0.

At the sequence level, beam search tracks the top BB 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 q(x)q(x) proposes γ\gamma tokens, and the target model p(x)p(x) verifies all γ+1\gamma + 1 positions in parallel. Each draft token xx passes with probability:

α(x)=min⁡ ⁣(1,  p(x)q(x))\alpha(x) = \min\!\left(1,\; \frac{p(x)}{q(x)}\right)

Upon rejection (probability 1−α(x)1 - \alpha(x)), subsequent draft tokens are discarded and one replacement token is drawn from normalized residual mass norm(max⁡(0,p(x)−q(x)))\text{norm}(\max(0, p(x) - q(x))), preserving exact target probabilities p(x)p(x).

Worked quantitative example

Suppose five candidate tokens carry raw logits z=[5.0,4.2,2.0,0.5,−1.0]z = [5.0, 4.2, 2.0, 0.5, -1.0].

At T=0.5T = 0.5, scaled logits [10.0,8.4,4.0,1.0,−2.0][10.0, 8.4, 4.0, 1.0, -2.0] yield softmax probabilities p≈[0.8302,0.1676,0.0021,0.0001,0.0000]p \approx [0.8302, 0.1676, 0.0021, 0.0001, 0.0000]. Both top-p=0.90p = 0.90 and min-p=0.10p = 0.10 (floor 0.10×0.8302=0.08300.10 \times 0.8302 = 0.0830) select {tok_0, tok_1} cleanly.

At T=1.5T = 1.5, logits flatten to probabilities p≈[0.531,0.313,0.072,0.026,0.011]p \approx [0.531, 0.313, 0.072, 0.026, 0.011] (plus tail terms). Under top-p=0.95p = 0.95, tokens 3 and 4 (2.6% and 1.1% noise) survive into the nucleus; under min-p=0.10p = 0.10 (floor 0.10×0.531=0.05310.10 \times 0.531 = 0.0531), only {tok_0, tok_1, tok_2} survive. Meanwhile, under speculative verification, when draft gives q(tok1)=0.60q(\text{tok}_1) = 0.60 and target gives p(tok1)=0.45p(\text{tok}_1) = 0.45, acceptance probability is min⁡(1,0.45/0.60)=0.75\min(1, 0.45/0.60) = 0.75—preventing overconfident draft errors while preserving p(x)p(x) exactly.

Decoding and sampling strategy comparison

StrategyAdaptive SupportLatency ImpactExact Target p(x)p(x)Best Production Workload
Greedy (T = 0)1 token (argmax)Minimal computeDeterministic mode onlyDeterministic classification & extraction
Top-kkFixed kk tokensNegligible sortTruncated approximationSimple bounded baselines
Nucleus Top-ppVaries by cumulative massSmall sort/cumsumTruncated approximationGeneral dialogue & summarization
Min-ppScales with pmax⁡p_{\max}Minimal threshold scanTruncated approximationCreative coding/writing at T≥0.8T \ge 0.8
Beam Search (B>1B \gt 1)BB parallel beamsB×B\times KV cache memorySequence-level MAP biasMachine translation & structured ASR
Speculative DecodingPreserves any target filter1.8x–3.0x lower ITL (low batch)Exact mathematical matchLow-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-pp or top-pp pruning so tail noise never breaks syntax or citations.

Deploy speculative decoding carefully across batch regimes: verifying γ\gamma 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 = 0 guarantees 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-p=0.99p = 0.99. 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 γ\gamma 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 γ=4\gamma = 4 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-pp/top-kk/top-pp filtering, and speculative rejection sampling verification.

python
import math
import random
​
def 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.0
for idx in ranked:
if probs[idx] < min_p * p_max:
continue
kept.append(idx)
cum_p += probs[idx]
if cum_p >= top_p:
break
kept = 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], dist
​
def 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)
Reflect before revealing the guide

Why does speculative decoding preserve the target model's exact output distribution while greedy vs high-temperature top-p trade repeatability against tail risk?

Prerequisites & Related Concepts (2)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next