Construct a top-k candidate set

Watch the spaces around tokens and probability values. · 165 words

Top-k decoding first restricts a language model's next-token choices to the k highest-scoring tokens. Here, k is a fixed number such as 2, 3, or 5. Candidates can be words, word pieces, or punctuation. Ranking means sorting the candidates by score from largest to smallest and keeping only the first k entries. Top-k differs from greedy decoding: greedy keeps one token, while top-k keeps a small set that can later be sampled.

Suppose a weather app starts the sentence "Tomorrow in Paris," and the next-token probabilities are sunny 0.45, rainy 0.25, cloudy 0.20, and windy 0.10. For k=2, rank the probabilities and keep sunny and rainy. To sample only from this set, divide each retained probability by their total, 0.45 + 0.25 = 0.70. The adjusted probabilities are sunny 0.45/0.70 = 0.642857 and rainy 0.25/0.70 = 0.357143. A random draw therefore chooses sunny about 64.3 percent of the time and rainy about 35.7 percent. Top-k adds variety without allowing cloudy or windy at this step.

Check your recall

With k=2, which weather tokens remain, and what are their adjusted probabilities?

Check your answer

The candidate set contains sunny and rainy. After renormalization, sunny has probability 0.642857 and rainy has probability 0.357143.

Sources and credits

Original KeyTouch lesson. Background reading · Hugging Face · LLM Course.