Keep the best k, discard the rest
Everything outside that set is removed, and what is left is renormalised so it sums to one again.
- : how many tokens survive, typically between 20 and 100.
The renormalisation matters: without it the surviving probabilities sum to less than one, and the missing mass has nowhere to go.
What it is protecting against
A vocabulary of 100,000 tokens has a very long tail, and the tail's total mass is not negligible.
If 90,000 tokens each hold a probability of , their combined mass is 0.09.
So nearly one time in eleven, pure sampling picks from the part of the distribution the model considers absurd.
One such token is usually unrecoverable: the model conditions on it and the rest of the sentence follows it into nonsense.
Truncation exists to make that impossible rather than merely unlikely.
Why a fixed k is the wrong shape
The problem is that does not know how certain the model is.
In the first case the model is sure, and keeps 49 tokens it gave almost no mass to. Some of them will be sampled.
In the second the model is genuinely uncertain across hundreds of reasonable options, and cuts off continuations it rated nearly as highly as the ones it kept.
One number cannot be right for both, which is the entire argument for top-p.
One token, in order
- Get the logits and apply temperature.
- Take the largest.
- Set every other logit to negative infinity.
- Softmax what remains.
- Draw one token.
Where it still earns its place
is greedy decoding, written as a special case rather than a separate algorithm.
A modest is also used as a floor underneath top-p, so that a very peaked distribution cannot collapse the nucleus to a single token when some variety was wanted.
The two compose: apply top-k first as a hard cap, then top-p within it.