Chapter 13 of 40 · ~22 min read & lab+80 XP
Chapter 13 · Generative AI

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.

What Is It?

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

Why Is It Required?

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.

Everyday Analogy: Choosing a dinner spot by either always picking your #1 favorite (greedy), picking among your top 5 (Top-K), or picking among the spots that cover 90% of your cravings (Top-P).
Why ML Engineers & Data Scientists Actually Need This

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!

ML / AI Engineer

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.

Data Scientist

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.

Interview & Debug Edge

Classic Generative AI coding interview: 'Implement Temperature Softmax Sampling and Top-P (Nucleus) Filtering from scratch in NumPy without overflow!'

Step 0 · Test Your Gut Before Any Math!

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?

What You Will Master in This Chapter
  • 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
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 4
z_i / TSay aloud:“temperature-scaled logit”
Plain-English Meaning
Dividing raw logits by T > 0 before softmax controls sharpness vs. entropy
Everyday Example
T=0.2 sharpens; T=1.5 flattens
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Think of the LLM's next-token logits as a mountain range of 128,000 peaks. Temperature TT is a gravity dial: lowering T→0T \to 0 stretches the tallest mountain into a skyscraper while crushing all other hills flat (deterministic greedy); raising T>1T > 1 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

Everyday Story First (Zero Math Yet!)

Notice that dividing by T>0T > 0 NEVER changes which token is #1 — it only changes how much probability mass is concentrated on the top peak vs. spread across runners-up!

Temperature Scaling: p_i = softmax(z_i / T)T = 0.2 (Greedy / Sharp)92%cat6%dog1.5%fox0.5%owlT = 1.0 (Calibrated)52%cat26%dog14%fox8%owlT = 2.0 (Creative / Flat)33%cat27%dog22%fox18%owl
Temperature T rescales logits z_i / T before softmax: T → 0 sharpens into greedy argmax, T = 1 keeps calibrated probabilities, and T > 1 flattens toward uniform randomness.

Numerically Stable Temperature Softmax

pi(T)=exp⁡ ⁣((zi−zmax⁡)/T)∑j=1∣V∣exp⁡ ⁣((zj−zmax⁡)/T)p_i(T) = \frac{\exp\!\big((z_i - z_{\max}) / T\big)}{\sum_{j=1}^{|V|} \exp\!\big((z_j - z_{\max}) / T\big)}

  • T→0+T \to 0^+ (Greedy Decoding): All probability collapses onto arg⁡max⁡izi\arg\max_i z_i. Best for factual extraction, SQL/JSON, and unit-testable code.
  • T=1.0T = 1.0: Exact unmodified distribution learned during pre-training/post-training.
  • T>1.0T > 1.0: Increases Shannon entropy H(p)H(p), encouraging diverse brainstorming — but above T≈1.3T \approx 1.3 without Top-P/Min-P, the 100,000-token tail accumulates dangerous mass and causes gibberish!
Formula Anatomy · Click Any Colored Piece to Decode It
Anatomy of Temperature-Scaled Softmax

p_i = exp((z_i − z_max)/T) / Σ exp((z_j − z_max)/T)

Max-Shift Stability Trick

Subtracting the max logit before dividing by small T prevents exp(+500) = Infinity overflow!

In our example: Largest exponent is always exp(0) = 1.0
Put it together with real numbers: Logits [4.0, 2.0] have gap 2.0: at T=1.0 → [88.1%, 11.9%]; at T=0.5 → gap doubles to 4.0 → [98.2%, 1.8%]; at T=2.0 → gap halves to 1.0 → [73.1%, 26.9%]!

2. Rigid Top-K vs. Adaptive Top-P (Nucleus) Filtering

Everyday Story First (Zero Math Yet!)

Drag the Top-P slider in the mini-lab below to see how tokens are sorted, accumulated, truncated right after crossing pp, and re-normalized to sum to 100%!

Rigid Top-K vs. Adaptive Top-P (Nucleus) CutoffConfident Prompt: "The capital of France is ___"ParisLyontheabananaTop-P (0.9) keeps ONLY 1 token! Top-K=5 lets junk in!Creative Prompt: "Once upon a time, a ___"dragonknightwizardpiraterobotTop-P (0.9) automatically expands to 5 rich choices!
Top-K keeps a rigid fixed count of K tokens regardless of uncertainty, while Top-P (Nucleus) dynamically shrinks on confident prompts and expands on open-ended creative prompts!

The Exact 4-Step Top-P (Nucleus) Algorithm

  1. Sort probabilities descending: p(1)≥p(2)≥⋯≥p(∣V∣)p_{(1)} \ge p_{(2)} \ge \dots \ge p_{(|V|)}.
  2. Cumulative sum: ck=∑j=1kp(j)c_k = \sum_{j=1}^k p_{(j)}.
  3. Keep the smallest prefix where cumulative mass reaches pp — crucially, always include the boundary token that crosses pp (and always keep at least 1 token, even if p(1)>pp_{(1)} > p!).
  4. Zero out the tail & re-normalize: divide each kept probability by ∑keptpj\sum_{\text{kept}} p_j.
Animated Mini-Lab • 3.1

Top-P (Nucleus) Cutoff & Re-Normalization Lab

Parisorig: 52% · cum: 52%renorm: 59.8%
Lyonorig: 21% · cum: 73%renorm: 24.1%
Marseilleorig: 14% · cum: 87%renorm: 16.1%
Niceorig: 8% · cum: 95%MASKED (−∞)
bananaorig: 5% · cum: 100%MASKED (−∞)

3. Exact Production Decoding Pipeline Order

Everyday Story First (Zero Math Yet!)

Does applying Temperature before Top-P produce the same result as Top-P before Temperature? No — order matters!

Exact Logit-to-Token Decoding Pipeline (Order Matters!)1. Raw Logitsz ∈ R^|V|2. Rep Penaltypenalize seen3. Temp Scalez / T4. Top-K/P/Min-Pmask tail → −∞5. Softmaxsample next tokMasked logits set to −∞ become exact 0.0 probability after softmax; remaining tokens re-normalize to sum = 1.0!
Exact production decoding order: raw logits z → Repetition Penalty → Temperature scaling (z/T) → Top-K / Top-P / Min-P masking (−∞) → Softmax → Multinomial Sample.

Standard Inference Engine Order (vLLM / Hugging Face)

  1. Repetition / Presence Penalty on raw logits zz
  2. Temperature Scaling z←z/Tz \leftarrow z / T
  3. Top-K / Top-P / Min-P Filtering (set discarded logits to −∞-\infty)
  4. Softmax & Multinomial Sample (or argmax if T=0T = 0)

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.

Walk Through With Me · Interactive Worked Example

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.

11. Compute cumulative sumsStep 1 / 3

[0.50, 0.75, 0.90, 0.96, 1.00].

Teacher's Note: At token 2 we are at 0.75 (< 0.80), so we MUST include token 3 (0.90 ≥ 0.80)!
Pause & Check · Quick Intuition Pulse

In standard Top-P = 0.90 sampling, if the top token alone has probability 0.94, how many tokens remain in the nucleus?

Try It YourselfStandard

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?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

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!

Interactive Visual Lab
Lab Challenge: Watch the 60 FPS Temperature Morphing Studio sweep T from 0.25 to 2.00 and adjust the Top-P slider to see the active nucleus shrink and grow.
Interactive Animation • 3.1 Deep Lab

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.

T = 0.25 · Top-P = 0.85
Active Nucleus Size: 1 / 5 tokens
99.6%ParisKEEP0.4%Lyon−∞0.0%Nice−∞0.0%Rome−∞0.0%Mars−∞
0%
Temp T = 0.25
Intuition Takeaway: Temperature scales logit sharpness (z / T), while Top-P (Nucleus) dynamically prunes the noisy vocabulary tail by keeping the smallest prefix whose cumulative probability reaches pp before re-normalizing.
Where This Powers Real ML, Deep Learning & Generative AI

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.

Production NumPy & PyTorch Code Patterns
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))
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Forgetting to subtract max(z) before exp(z / T) when T is small (e.g. T = 0.05).
Best Practice: Always compute shifted = (z - np.max(z)) / T first! Without max-shift, exp(10 / 0.05) = exp(200) overflows float16/float32 to NaN!
Trap #2: Dropping the first token in Top-P when p_1 > top_p.
Best Practice: Use the shifted-cumsum mask: keep = (cumsum - sorted_probs) < top_p — guarantees the top token is always kept!
Chapter Mastery Check (+80 XP)
Score: 0 / 2
1Why does Top-P (Nucleus) sampling generally outperform fixed Top-K sampling in open-ended LLM generation?
2Which formula avoids floating-point overflow when computing Temperature Softmax for small T = 0.05?

Apply What You Learned — Solve Matching Coding Problems