Module lessons (3/4)
Sampling Control: Temperature, Top-P, Top-K & Min-P
From Unnormalized Logits to Probabilities
At each autoregressive step, the final linear projection of an LLM produces a vector of raw, unnormalized scores called logits (z), with one real number for every token in the vocabulary (V ≈ 32,000 … 200,000).
To convert logits into a valid probability distribution where all values lie in [0, 1] and sum to 1, the model applies the softmax function:
P(w_i) = exp(z_i / T) / sum(exp(z_j / T))Where T is the temperature hyperparameter:
| Temperature | Behavior | Recommended Use Cases |
|---|---|---|
| T = 0.0 | Greedy decoding (argmax only) | Structured JSON, code parsing, math |
| T = 0.2 | Highly focused, minimal drift | Classification, SQL queries, factual QA |
| T = 0.7 | Balanced variety and cohesion | Summarization, copywriting, chat |
| T ≥ 1.2 | High entropy, hallucination | Brainstorming, poetry, diverse samples |
Interactive Sampling Distribution Lab
Manipulate temperature, Top-P, and Top-K sliders in real-time, observing probability mass collapse and tail token pruning:
Top-P (Nucleus) and Top-K Truncation
While temperature flattens or sharpens the distribution, it does not prevent the model from sampling low-probability tail tokens. Two truncation filters eliminate the tail:
- Top-K: Keeps strictly the top K tokens with the highest probabilities (e.g. K=50) and zeros out the rest.
- Top-P (Nucleus): Dynamically sorts tokens in descending order of probability and keeps only the smallest set whose cumulative sum reaches P (e.g. P=0.90). If the top token has 95% probability, only 1 token is considered; if the distribution is flat, dozens are kept.
import numpy as np
def apply_temperature(logits: np.ndarray, temperature: float = 1.0) -> np.ndarray:
"""Scales logits by temperature and applies numerically stable softmax."""
if temperature <= 0.0:
probs = np.zeros_like(logits)
probs[np.argmax(logits)] = 1.0
return probs
scaled = logits / temperature
exp_shifted = np.exp(scaled - np.max(scaled))
return exp_shifted / np.sum(exp_shifted)Check Your Understanding
What is the primary advantage of Top-P (nucleus) sampling compared to fixed Top-K sampling?
Practice: Temperature Softmax & Top-P Nucleus Filtering
Warmup — Temperature-scaled softmax
Write softmax_with_temp(logits, temp=1.0) using numpy. For temp <= 0.0, return a one-hot array (1.0 at argmax, 0.0 elsewhere). Use a stable softmax shift: exp(z - max(z)). Return a numpy array.
Show hint
Subtract np.max(scaled) before applying np.exp to prevent floating-point overflow.
Solution available after 3 attempts
Practice — Nucleus (Top-P) probability mask
Write filter_top_p(probs, p=0.90) that takes normalized probabilities, sorts them descending, finds the cutoff where cumulative sum exceeds p, and zeros out remaining tokens. Renormalize the result so it sums to 1.0.
Show hint
Sort descending, compute np.cumsum, identify tokens whose cumsum <= p (plus one boundary token), and zero out others.
Solution available after 3 attempts
Challenge — Min-P dynamic thresholding
Write min_p_filter(probs, min_p=0.05) that implements Min-P dynamic truncation. Calculate threshold = min_p * max(probs), zero out probabilities below threshold, and renormalize so the output sums to 1.0. Return the filtered array.
Show hint
Calculate threshold = min_p * np.max(p), set p[p < threshold] = 0.0, and renormalize.
Solution available after 3 attempts