20 — Inference

Sampling#

Temperature · Top-K · Top-PMathematical 1 min read
◆ The PatternControlling creativity by shaping the probability distribution

Instead of argmax, sample from the distribution — but shape it first. Temperature sharpens or flattens. Top-K limits to K most likely tokens. Top-P (nucleus) limits to the smallest set that sums to P probability.

Temperature: P'(token) = softmax(logit / T)
T<1 → sharper (more confident). T>1 → flatter (more random). T→0 = greedy.
Top-K: zero out all but top K logits, renormalize
K=50 is common. Prevents sampling very unlikely tokens (garbage).
Top-P (nucleus): keep tokens until cumulative P ≥ p, zero rest
Adaptive: for confident predictions, keeps few tokens. For uncertain, keeps many. p=0.9–0.95 typical.

In practice, combine them: temperature + top-P is the standard. Repetition penalty divides logits of recently-generated tokens by a factor (1.1–1.3) to reduce loops. Min-P is a newer approach that scales the threshold with the top token's probability.

Temperature 0.0–0.3 for code/math (deterministic). Temperature 0.7–1.0 for creative writing. Top-P 0.9 is a solid default for most tasks.
Interactive — probability distribution shaping

Python — sampling with temperature + top-p#

Pattern bridge: Temperature, top-k, top-p control the randomness of generation. Temperature is softmax temperature scaling. In statistics, sampling from distributions is the foundation.
Worked example

Eight candidate tokens. At temperature 0.7 the distribution has 1.69 bits of entropy and top-p = 0.9 keeps 3 tokens; at 1.0, 2.07 bits and 4 tokens; at 1.3, 2.33 bits and 5. Temperature changes how flat the distribution is, and nucleus sampling adapts how many tokens survive to that shape.

Where it misleads
  • High temperature adds diversity and errors together; for factual or code tasks, low temperature is usually better.
  • Fixed top-k ignores the shape of the distribution; top-p and min-p adapt, but all are heuristics tuned by eye.
  • Sampling settings interact: temperature applied before or after truncation gives different results.
In code
logits = np.array([3.0, 2.5, 2.0, 1.0, 0.5, 0.0, -1.0, -2.0])

def probs(T):
    z = np.exp((logits - logits.max()) / T); return z / z.sum()

def nucleus_size(p, top_p=0.9):
    return int(np.searchsorted(np.cumsum(np.sort(p)[::-1]), top_p) + 1)

entropy = lambda p: -(p * np.log2(p)).sum()
table = {T: (round(entropy(probs(T)), 2), nucleus_size(probs(T))) for T in (0.7, 1.0, 1.3)}
Python, in your browser — edit the code and run it again

Assumes import numpy as np. Configurations named after real models use their published shapes; other numbers are made up or simulated, as the comments say.

The same idea with a library
def sample(logits, temperature=0.8, top_p=0.9, top_k=50):
    logits = logits / temperature
    # Top-K filtering
    if top_k > 0:
        indices_to_remove = logits < logits.topk(top_k).values[..., -1:]
        logits[indices_to_remove] = float('-inf')
    # Top-P (nucleus) filtering
    sorted_logits, sorted_idx = logits.sort(descending=True)
    cumsum = sorted_logits.softmax(dim=-1).cumsum(dim=-1)
    remove = cumsum - sorted_logits.softmax(dim=-1) >= top_p
    sorted_logits[remove] = float('-inf')
    logits.scatter_(-1, sorted_idx, sorted_logits)
    probs = logits.softmax(dim=-1)
    return torch.multinomial(probs, 1)
Sources
  • A. Holtzman, J. Buys, L. Du, M. Forbes & Y. Choi, “The Curious Case of Neural Text Degeneration”, ICLR, 2020
  • A. Fan, M. Lewis & Y. Dauphin, “Hierarchical Neural Story Generation”, ACL, 2018 — top-k sampling
  • M. N. Nguyen et al., “Turning Up the Heat: Min-p Sampling for Creative and Coherent LLM Outputs”, arXiv:2407.01082, 2024

Last reviewed October 2026 · How this site checks its content · Report a mistake

Check yourself

1. What does temperature 0 (greedy decoding) do?

Show answer

B. Greedy decoding is (nearly) deterministic and can fall into repetition loops on long outputs.

2. What does top-p = 0.9 sample from?

Show answer

B. The set adapts: one token when the model is sure, many when it is not (Holtzman et al. 2020).

3. Raising the temperature makes the output…

Show answer

A. A higher temperature flattens the distribution, giving unlikely tokens more chance — good for brainstorming, bad for facts.

Linked from 3
← Previous
Decoding Strategies
Open in the full reader, with the topic sidebar