Top-k Sampling
A trained sequence model does not output text; it outputs a probability for every token in its vocabulary, at every step. Something has to pick one. Top-k sampling picks randomly, but only from the k tokens the model rated highest.
How the cut works
At each decoding step, sort the vocabulary by probability, keep the top k entries, discard the rest, renormalise what remains into a distribution and draw from it. With k = 1 this collapses into greedy decoding. With k = 50 — the common default in Hugging Face's generate — the model has fifty plausible continuations to choose between and the implausible remainder is gone. The truncation is what matters: without it, the long tail of near-zero tokens collectively holds enough probability mass that pure sampling eventually draws one and the sentence derails.
What it buys and costs
Randomness is the point. Greedy and beam search suit translation and summarisation, where there is roughly one right answer, but they make open-ended generation repetitive and bland — the same safe phrases, loops that never end. Sampling from a truncated head gives varied output that still stays on the rails. It is normally combined with temperature, which reshapes the distribution before the cut.
Why k is awkward
k is fixed, but the model's confidence is not. When the next token is nearly certain — the second half of a name, a closing bracket — fifty candidates reach far into nonsense. When the model is genuinely uncertain, fifty may cut off good options. Top-p sampling exists because a fixed count cannot adapt to that, setting a threshold on cumulative probability instead.
Top-k sampling is a decoding strategy that, at each step, keeps only the k highest-probability tokens, renormalises their probabilities and samples the next token from that truncated set. Restricting the draw to the head of the distribution removes the long tail of low-probability tokens whose combined mass makes unrestricted sampling incoherent, so generated text stays varied without drifting into nonsense. Because k is fixed, the cut ignores how confident the model actually is at that step.
Picture a songwriter looking for the next line. They do not pick the single most obvious word every time — that way you get a dull song. But they do not pick at random from the whole dictionary either. They shortlist a few words that could work, then choose from the shortlist.
Top-k sampling is software doing exactly that. When a language system writes, it scores every possible next word. Top-k keeps the best handful — say the top fifty — throws the rest away, and then picks from that shortlist with a bit of chance involved. The result reads naturally rather than mechanically, and the odd, wildly unlikely word that would wreck the sentence never gets a look in.