Skip to main content
Module 1 · Lesson 3 of 43/48 in the course~15 min
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:

Text
P(w_i) = exp(z_i / T) / sum(exp(z_j / T))

Where T is the temperature hyperparameter:

TemperatureBehaviorRecommended Use Cases
T = 0.0Greedy decoding (argmax only)Structured JSON, code parsing, math
T = 0.2Highly focused, minimal driftClassification, SQL queries, factual QA
T = 0.7Balanced variety and cohesionSummarization, copywriting, chat
T ≥ 1.2High entropy, hallucinationBrainstorming, 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:

  1. Top-K: Keeps strictly the top K tokens with the highest probabilities (e.g. K=50) and zeros out the rest.
  2. 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.
Python
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

Quiz#ai-engineering.m1.l3.q1

What is the primary advantage of Top-P (nucleus) sampling compared to fixed Top-K sampling?

Answer options

Practice: Temperature Softmax & Top-P Nucleus Filtering

Practice Stage

Warmup — Temperature-scaled softmax

Exercise#ai-engineering.m1.l3.e1
Attempts: 0Loading…

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.

Loading editor…
Show hint

Subtract np.max(scaled) before applying np.exp to prevent floating-point overflow.

Solution available after 3 attempts

Practice Stage

Practice — Nucleus (Top-P) probability mask

Exercise#ai-engineering.m1.l3.e2
Attempts: 0Loading…

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.

Loading editor…
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

Practice Stage

Challenge — Min-P dynamic thresholding

Exercise#ai-engineering.m1.l3.e3
Attempts: 0Loading…

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.

Loading editor…
Show hint

Calculate threshold = min_p * np.max(p), set p[p < threshold] = 0.0, and renormalize.

Solution available after 3 attempts