Notes

Top-p (Nucleus) Sampling

Fix the shortlist at fifty candidates and you have made the same bet at every step of generation — that fifty is the right number whether the model is certain or guessing. Top-p sampling drops the fixed count and sets a bar on probability instead.

The nucleus
Sort the vocabulary by probability and walk down the list, accumulating mass until the total crosses p — 0.9 or 0.95 in practice. That smallest set of tokens is the nucleus; renormalise it and sample from it, discarding everything else. The size of the nucleus is not fixed, and that is the whole idea:

  • where the model is confident — closing a quotation, finishing a known name — the top one or two tokens already carry 0.9, so the nucleus is tiny and sampling is nearly deterministic;
  • where many continuations are genuinely plausible, the nucleus widens to hundreds of tokens and the output gets real variety.

Why it became a default
Holtzman and colleagues introduced it against a specific failure they named neural text degeneration: beam search and greedy decoding produce text that loops and repeats, while unrestricted sampling wanders into incoherence, because a flat tail of tens of thousands of tokens holds a lot of mass between them. Nucleus sampling matched human text far more closely on the statistics they measured, and it is now a default in Hugging Face's generate alongside temperature.

What it does not fix
p is still a knob, and a poor setting still shows: too low and output turns repetitive, too high and the tail creeps back. It also does nothing about whether the content is true — the nucleus is shaped by the model's probabilities, which reward fluency, not accuracy.

Top-p sampling, or nucleus sampling, selects the next token from the smallest set of highest-probability tokens whose cumulative probability exceeds p, then renormalises and samples within that set. Unlike a fixed-size cut, the candidate pool shrinks where the model is confident and widens where many continuations are plausible, which suppresses the unreliable tail without flattening variety. It is a standard default for open-ended generation, typically with p near 0.9.

Think of a chef tasting as they cook. If one seasoning is obviously right, they reach straight for it. If several would work, they let themselves choose. The number of options they consider depends on how clear the situation is.

Top-p sampling gives software the same flexibility when it writes. Instead of always shortlisting a fixed number of possible next words, it keeps adding candidates — best first — until they add up to enough of the total likelihood, say ninety per cent. When the next word is almost certain, the shortlist is one or two words. When lots of words would fit, it grows. That is why text produced this way reads neither robotic nor rambling.