Loading the problem
Turn a vector of next-token logits into the probability distribution that nucleus (top-p) sampling draws from.
Sampling from the full softmax lets rare, low-quality tokens through. Top-p
sampling keeps only the smallest set of the most likely tokens whose total
probability reaches p, and renormalises over that set. When the model is
confident, the set is small. When it is unsure, the set grows.
probs = softmax(logits / temperature).>= p. The
token that crosses p is kept.0 and divide by the sum of the kept ones.def top_p_filter(logits, p, temperature=1.0):
Input
logits = np.log(np.array([0.5, 0.3, 0.15, 0.05]))
top_p_filter(logits, p=0.75)
Output
array([0.625, 0.375, 0. , 0. ])
Reasoning
The softmax gives back [0.5, 0.3, 0.15, 0.05]. The top token alone has 0.5,
which is below 0.75. Adding the second gives 0.8, which reaches it, so two
tokens are kept. They are renormalised: 0.5 / 0.8 = 0.625 and
0.3 / 0.8 = 0.375.
logits has shape (V,), and 0 < p <= 1.1e-12, so that
a sum that should equal p exactly is not lost to rounding.Check runs the visible cases against a fresh kernel. Submit runs the hidden ones too.
⇧↵run cell