TExcelTAD
Home › Math for Deep Learning & LLMs › Sampling: Temperature, Top-k and Top-p

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 T>0T > 0 before the softmax:

pi(T)=ezi/T∑jezj/Tp_i(T) = \frac{e^{z_i/T}}{\sum_j e^{z_j/T}}

T=1T = 1 leaves the distribution unchanged; T<1T < 1 sharpens it (as T→0T \to 0 it approaches greedy argmax); T>1T > 1 flattens it (as T→∞T \to \infty it approaches uniform). The entropy of p(T)p(T) increases with TT.

python · try it yourself
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 p\mathbf{p}, draw u∼Uniform⁡(0,1)u \sim \operatorname{Uniform}(0, 1) and return the first index whose cumulative probability exceeds uu (inverse-CDF sampling). A fixed seed makes generation reproducible.

Top-k and top-p (nucleus) sampling

Top-k: keep only the kk most likely tokens, renormalize, sample. Simple, but a fixed kk 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 pp (e.g. 0.9), renormalize, sample. The set adapts: one token when the model is sure, hundreds when it is not.

python · try it yourself
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 arg⁡max⁡ipi\arg\max_i p_i each step. Beam search keeps the bb 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_p map 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=4 for beam search.
  • The order matters: implementations typically apply temperature first, then the truncation filters.

Exercises

Exercise 1: Temperature extremes

For logits (2,1,0)(2, 1, 0), what distributions do T→0T \to 0 and T→∞T \to \infty give?

Answer

(1,0,0)(1, 0, 0) and (13,13,13)(\frac{1}{3}, \frac{1}{3}, \frac{1}{3}).

Solution

As T→0T \to 0, z1/Tz_1/T dominates the others infinitely; as T→∞T \to \infty, all zi/T→0z_i/T \to 0 and the softmax of zeros is uniform.

Exercise 2: Nucleus size

Sorted probabilities are 0.5,0.2,0.15,0.1,0.050.5, 0.2, 0.15, 0.1, 0.05. Which tokens does top-p with p=0.8p = 0.8 keep?

Answer

The first three.

Solution

Cumulative sums 0.5,0.7,0.850.5, 0.7, 0.85: the third pushes the total past 0.8, so three tokens are kept, renormalized to (0.588,0.235,0.176)(0.588, 0.235, 0.176).

Exercise 3: Inverse-CDF sampling (code)

Implement sampling with np.searchsorted on the cumulative probabilities and check its frequencies for p=(0.2,0.5,0.3)\mathbf{p} = (0.2, 0.5, 0.3).

Answer

The frequencies come out close to (0.2,0.5,0.3)(0.2, 0.5, 0.3).

Solution
python · try it yourself
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…

  1. flattens the distribution
  2. sharpens the distribution toward the most likely token
  3. changes which token is most likely
  4. has no effect

What is the advantage of top-p over top-k?

  1. It is deterministic
  2. The number of kept tokens adapts to the model's confidence
  3. It never samples
  4. It uses no probabilities

Temperature scaling never changes…

  1. the probabilities
  2. the entropy
  3. the ranking (order) of the tokens
  4. the sampled token