LLM Decoding: Temperature, Top-K & Top-P (Nucleus) Sampling Visualized
How an LLM turns 128,000 raw logits into the next token: Temperature scaling (z/T), rigid Top-K vs. adaptive Top-P (Nucleus) filtering, exact re-normalization, and why decoding order matters.
LLM Decoding controls how the next token is selected from raw vocabulary logits using Temperature (sharpness), Top-K (fixed candidate cap), and Top-P / Nucleus (cumulative probability cutoff).
Pure greedy decoding sounds robotic and repetitive, while unfiltered random sampling emits gibberish; tuning T, Top-K, and Top-P balances factual precision with creativity.
The exact same 70B LLM can look like a razor-sharp coding genius at T = 0.1 or a hallucinating poet at T = 1.5 — decoding parameters control everything after the final linear layer!
Tuning temperature and top_p (and knowing the exact order in which vLLM/Hugging Face apply logit warpers) is critical for reproducible RAG, code generation, and Best-of-N sampling.
Understanding why greedy decoding (T = 0) is NOT always globally optimal — and why Top-P adapts gracefully across low-entropy and high-entropy tokens — prevents common production quality bugs.
Classic Generative AI coding interview: 'Implement Temperature Softmax Sampling and Top-P (Nucleus) Filtering from scratch in NumPy without overflow!'
On a super-confident prompt like 'The capital of France is ___' where 'Paris' has 95% probability, which sampler better protects against sampling absurd tail words?
- Compute temperature-scaled softmax probabilities p_i = exp(z_i / T) / Σ exp(z_j / T) with numerical log-sum-exp stability
- Explain the exact mathematical behavior at T → 0 (greedy argmax), T = 1 (calibrated model distribution), and T → ∞ (uniform random)
- Contrast fixed Top-K truncation with adaptive Top-P (Nucleus) sampling on peaked factual prompts vs. flat creative prompts
- Implement Top-P filtering cleanly: sort descending, compute cumulative sum, keep the smallest prefix reaching ≥ p, mask the tail to −∞, and re-normalize
Think of the LLM's next-token logits as a mountain range of 128,000 peaks. Temperature is a gravity dial: lowering stretches the tallest mountain into a skyscraper while crushing all other hills flat (deterministic greedy); raising flattens the mountains into rolling hills so underdog words get picked. Top-P (Nucleus) then draws a smart floodline that keeps only the top 90% of probability mass — cutting off the weird long tail of 100,000 hallucination tokens!
1. Temperature Scaling: Controlling Entropy Without Changing Ranking
Notice that dividing by NEVER changes which token is #1 — it only changes how much probability mass is concentrated on the top peak vs. spread across runners-up!
Numerically Stable Temperature Softmax
- (Greedy Decoding): All probability collapses onto . Best for factual extraction, SQL/JSON, and unit-testable code.
- : Exact unmodified distribution learned during pre-training/post-training.
- : Increases Shannon entropy , encouraging diverse brainstorming — but above without Top-P/Min-P, the 100,000-token tail accumulates dangerous mass and causes gibberish!
p_i = exp((z_i − z_max)/T) / Σ exp((z_j − z_max)/T)
Subtracting the max logit before dividing by small T prevents exp(+500) = Infinity overflow!
2. Rigid Top-K vs. Adaptive Top-P (Nucleus) Filtering
Drag the Top-P slider in the mini-lab below to see how tokens are sorted, accumulated, truncated right after crossing , and re-normalized to sum to 100%!
The Exact 4-Step Top-P (Nucleus) Algorithm
- Sort probabilities descending: .
- Cumulative sum: .
- Keep the smallest prefix where cumulative mass reaches — crucially, always include the boundary token that crosses (and always keep at least 1 token, even if !).
- Zero out the tail & re-normalize: divide each kept probability by .
Top-P (Nucleus) Cutoff & Re-Normalization Lab
3. Exact Production Decoding Pipeline Order
Does applying Temperature before Top-P produce the same result as Top-P before Temperature? No — order matters!
Standard Inference Engine Order (vLLM / Hugging Face)
- Repetition / Presence Penalty on raw logits
- Temperature Scaling
- Top-K / Top-P / Min-P Filtering (set discarded logits to )
- Softmax & Multinomial Sample (or
argmaxif )
Rule of Thumb for APIs: Tune either temperature OR top_p — not both aggressively at once! For deterministic JSON/code use T = 0.0; for general chat use T = 0.7, top_p = 0.9.
Worked Example: Top-P = 0.80 Filtering & Re-Normalization
Sorted token probabilities are [0.50, 0.25, 0.15, 0.06, 0.04] with top_p = 0.80.
[0.50, 0.75, 0.90, 0.96, 1.00].
In standard Top-P = 0.90 sampling, if the top token alone has probability 0.94, how many tokens remain in the nucleus?
What happens in a naive Top-P implementation if you keep only tokens where cumsum <= top_p instead of including the first token that crosses top_p?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Because floating-point addition on GPUs is not strictly associative across dynamic continuous-batching sizes (and Sparse MoE router capacity), tiny 1e-5 rounding differences can occasionally flip a near-tie top logit!
60 FPS Temperature Morphing & Top-P Nucleus Filter Studio
Watch temperature T sweep smoothly from 0.25 (sharp greedy) to 2.00 (flat creative) while Top-P dynamically shrinks and expands the active nucleus.
z / T), while Top-P (Nucleus) dynamically prunes the noisy vocabulary tail by keeping the smallest prefix whose cumulative probability reaches before re-normalizing.Code & Structured Extraction (T = 0.0–0.2)
Sharpens probability mass onto high-confidence syntax tokens, minimizing bracket and schema errors.
Best-of-N / Self-Consistency Reasoning (T = 0.6–0.8)
Generates N diverse reasoning chains and picks the majority-vote or unit-test-verified winner.
import torch
import torch.nn.functional as F
# Combined Temperature + Top-K + Top-P (Nucleus) Token Sampler
def sample_next_token(logits: torch.Tensor, temp: float = 0.8, top_k: int = 40, top_p: float = 0.9) -> int:
scaled = logits / max(temp, 1e-5)
if top_k > 0:
thresh = torch.topk(scaled, min(top_k, scaled.size(-1))).values[-1]
scaled = scaled.masked_fill(scaled < thresh, float("-inf"))
sorted_logits, sorted_idx = torch.sort(scaled, descending=True)
cum_probs = F.softmax(sorted_logits, dim=-1).cumsum(dim=-1)
remove = cum_probs > top_p
remove[1:] = remove[:-1].clone() # keep the first token that crosses top_p
remove[0] = False
sorted_logits[remove] = float("-inf")
probs = F.softmax(sorted_logits, dim=-1)
choice = torch.multinomial(probs, num_samples=1)
return sorted_idx[choice].item()
torch.manual_seed(7)
logits = torch.randn(100)
print("Sampled token ID:", sample_next_token(logits, temp=0.7, top_k=20, top_p=0.9))
max(z) before exp(z / T) when T is small (e.g. T = 0.05).shifted = (z - np.max(z)) / T first! Without max-shift, exp(10 / 0.05) = exp(200) overflows float16/float32 to NaN!p_1 > top_p.keep = (cumsum - sorted_probs) < top_p — guarantees the top token is always kept!