Truncate by mass, not by count
Top-p keeps the smallest set of tokens whose probabilities add up to at least , and throws the rest away.
- : the whole vocabulary.
- : the nucleus: the tokens that survive.
- : the mass to keep, typically 0.9 or 0.95.
In practice you sort by probability descending and walk down the list adding probabilities until the running total crosses .
Then renormalise
The surviving probabilities no longer sum to one, so they are rescaled.
Without that division the sampler would be drawing from a distribution summing to about 0.9, and the missing mass has to go somewhere.
Why a mass threshold beats a fixed count
The size of the nucleus changes with how certain the model is, and that is the entire point.
After "the capital of France is" the model may put 0.99 on one token, so the nucleus at contains exactly one token and sampling is effectively greedy.
After "she opened the door and saw" the mass is spread over hundreds of plausible continuations, so the nucleus is large and the sampler has real freedom.
Top-k cannot do this: admits 49 bad tokens in the first case and cuts off good ones in the second.
One token, in order
- Get the logits and apply temperature.
- Softmax them into probabilities.
- Sort descending and accumulate until the total reaches .
- Zero everything outside that set and rescale what is left to sum to one.
- Draw one token from the rescaled distribution.
What the values do
At nothing is truncated and you are sampling from the full distribution, tail included.
At only the single most likely token survives, which is greedy decoding again.
The interesting range is narrow: below about 0.8 the text tends to loop, above about 0.98 the tail starts leaking in nonsense.
It composes with temperature rather than replacing it: temperature reshapes the distribution and top-p then cuts it.
The order matters, because cutting first would truncate a distribution that is about to change shape.