Sampling: Temperature, Top-k and Top-p
A language model outputs a probability distribution over the next token; generation must turn it into an actual token, again and again. Always taking the most likely token (greedy decoding) tends to produce bland, repetitive text, while sampling from the raw distribution occasionally picks absurd low-probability tokens. Temperature, top-k and top-p reshape or truncate the distribution before sampling to control this trade-off.
Temperature
Divide the logits by before the softmax:
leaves the distribution unchanged; sharpens it (as it approaches greedy argmax); flattens it (as it approaches uniform). The entropy of increases with .
import numpy as np
z = np.array([3.0, 2.0, 1.0, 0.0, -1.0])
def softmax(z): e = np.exp(z - z.max()); return e / e.sum()
for T in (0.2, 0.5, 1.0, 2.0, 10.0):
p = softmax(z / T)
H = -np.sum(p * np.log(p))
print(f"T = {T:4}: p = {np.round(p, 3)} entropy {H:.3f} (max ln 5 = {np.log(5):.3f})")T = 0.2: p = [0.993 0.007 0. 0. 0. ] entropy 0.041 (max ln 5 = 1.609)
T = 0.5: p = [0.865 0.117 0.016 0.002 0. ] entropy 0.458 (max ln 5 = 1.609)
T = 1.0: p = [0.636 0.234 0.086 0.032 0.012] entropy 1.000 (max ln 5 = 1.609)
T = 2.0: p = [0.429 0.26 0.158 0.096 0.058] entropy 1.394 (max ln 5 = 1.609)
T = 10.0: p = [0.242 0.219 0.198 0.179 0.162] entropy 1.600 (max ln 5 = 1.609)
Sampling with a seeded generator
To sample from , draw and return the first index whose cumulative probability exceeds (inverse-CDF sampling). A fixed seed makes generation reproducible.
Top-k and top-p (nucleus) sampling
Top-k: keep only the most likely tokens, renormalize, sample. Simple, but a fixed is too many when the model is confident and too few when it is unsure.
Top-p: keep the smallest set of most likely tokens whose total probability is at least (e.g. 0.9), renormalize, sample. The set adapts: one token when the model is sure, hundreds when it is not.
import numpy as np
def softmax(z): e = np.exp(z - z.max()); return e / e.sum()
def top_k(p, k):
q = np.zeros_like(p); idx = np.argsort(p)[::-1][:k]; q[idx] = p[idx]; return q / q.sum()
def top_p(p, thr):
order = np.argsort(p)[::-1]; c = np.cumsum(p[order])
keep = order[:np.searchsorted(c, thr) + 1]
q = np.zeros_like(p); q[keep] = p[keep]; return q / q.sum()
confident = softmax(np.array([6.0, 2.0, 1.5, 1.0, 0.5, 0.0]))
unsure = softmax(np.array([1.0, 0.9, 0.8, 0.8, 0.7, 0.6]))
for name, p in (("confident", confident), ("unsure", unsure)):
print(f"{name:9s} p = {np.round(p, 3)}")
print(f" top-3 = {np.round(top_k(p, 3), 3)}")
print(f" top-0.9= {np.round(top_p(p, 0.9), 3)} ({np.count_nonzero(top_p(p, 0.9))} tokens kept)")
rng = np.random.default_rng(0)
draws = rng.choice(6, size=10000, p=top_p(unsure, 0.9))
print("empirical frequencies of 10,000 nucleus samples:", np.round(np.bincount(draws, minlength=6) / 10000, 3))confident p = [0.959 0.018 0.011 0.006 0.004 0.002]
top-3 = [0.971 0.018 0.011 0. 0. 0. ]
top-0.9= [1. 0. 0. 0. 0. 0.] (1 tokens kept)
unsure p = [0.202 0.183 0.165 0.165 0.15 0.135]
top-3 = [0.367 0.332 0. 0.301 0. 0. ]
top-0.9= [0.202 0.183 0.165 0.165 0.15 0.135] (6 tokens kept)
empirical frequencies of 10,000 nucleus samples: [0.207 0.177 0.163 0.17 0.152 0.132]
Greedy and beam search
Greedy decoding picks each step. Beam search keeps the highest-probability partial sequences, maximizing (approximately) the probability of the whole output. It suits tasks with one correct answer (translation, speech recognition) but makes open-ended text dull and repetitive, because the most probable text is not typical text.
Other knobs
- Repetition / frequency penalties subtract from the logits of tokens already generated.
- Min-p keeps tokens whose probability is at least a fraction of the top token's.
- Logit bias and constrained decoding force or forbid tokens (e.g. valid JSON).
- Speculative decoding speeds up generation without changing the sampled distribution.
In software
- API parameters
temperature,top_k,top_pmap exactly onto the operations above; temperature 0 usually means greedy. - Hugging Face
generate(do_sample=True, temperature=0.7, top_p=0.9);num_beams=4for beam search. - The order matters: implementations typically apply temperature first, then the truncation filters.
Exercises
Exercise 1: Temperature extremes
For logits , what distributions do and give?
Answer
and .
Solution
As , dominates the others infinitely; as , all and the softmax of zeros is uniform.
Exercise 2: Nucleus size
Sorted probabilities are . Which tokens does top-p with keep?
Answer
The first three.
Solution
Cumulative sums : the third pushes the total past 0.8, so three tokens are kept, renormalized to .
Exercise 3: Inverse-CDF sampling (code)
Implement sampling with np.searchsorted on the cumulative probabilities and check its frequencies for .
Answer
The frequencies come out close to .
Solution
import numpy as np
rng = np.random.default_rng(1)
p = np.array([0.2, 0.5, 0.3]); c = np.cumsum(p)
samples = np.searchsorted(c, rng.uniform(size=100000), side="right")
print(np.round(np.bincount(samples) / 100000, 3))[0.2 0.499 0.301]
Test yourself
Lowering the temperature below 1…
- flattens the distribution
- sharpens the distribution toward the most likely token
- changes which token is most likely
- has no effect
What is the advantage of top-p over top-k?
- It is deterministic
- The number of kept tokens adapts to the model's confidence
- It never samples
- It uses no probabilities
Temperature scaling never changes…
- the probabilities
- the entropy
- the ranking (order) of the tokens
- the sampled token