Sampling: Temperature, Top-k, Top-p
Key idea: divide logits by the temperature, optionally keep only the k largest (top-k) or the smallest set of tokens whose probability mass reaches p (nucleus / top-p), renormalize and sample.
import numpy as np
def softmax(z):
e = np.exp(z - z.max())
return e / e.sum()
def next_token_probs(logits, temperature=1.0, top_k=None, top_p=None):
z = np.asarray(logits, float) / max(temperature, 1e-8)
if top_k is not None:
kth = np.sort(z)[-top_k]
z = np.where(z < kth, -np.inf, z)
p = softmax(z)
if top_p is not None:
order = np.argsort(-p)
cum = np.cumsum(p[order])
cutoff = np.searchsorted(cum, top_p) + 1 # smallest prefix with mass >= top_p
keep = np.zeros_like(p, bool)
keep[order[:cutoff]] = True
p = np.where(keep, p, 0.0)
p /= p.sum()
return p
def sample(logits, rng, **kw):
p = next_token_probs(logits, **kw)
return rng.choice(len(p), p=p)
logits = [2.0, 1.0, 0.0, -1.0] # softmax ≈ [0.644, 0.237, 0.087, 0.032]
assert np.count_nonzero(next_token_probs(logits, top_k=2)) == 2
assert np.count_nonzero(next_token_probs(logits, top_p=0.5)) == 1 # 0.644 already >= 0.5
assert np.count_nonzero(next_token_probs(logits, top_p=0.9)) == 3 # 0.644 + 0.237 < 0.9
assert next_token_probs(logits, temperature=0.01)[0] > 0.999 # T -> 0 = greedy
hot = next_token_probs(logits, temperature=10.0)
assert hot.max() - hot.min() < 0.1 # high T -> near uniform
rng = np.random.default_rng(0)
draws = [sample(logits, rng, top_k=2) for _ in range(2000)]
assert set(draws) == {0, 1}
print("ok", np.round(next_token_probs(logits, top_p=0.9), 3))