AI Logic

Decoding

Top-k Sampling

Updated:

Example of top-k sampling with k = 3. At the top is the flat distribution after "Today is": from the model probabilities on the left, only the top 3 (sunny, rainy, Sunday) are kept and divided by their total of 0.65 to give the probabilities on the right (0.46, 0.31, 0.23). At the bottom is the peaked distribution after "Thank you very": besides the nearly certain "much," even "cat" with a probability of 0.01 remains a candidate

What is top-k sampling?

Top-k sampling is a decoding method that keeps only the top kk words of the next-word probabilities produced by a language model and randomly picks one of them in proportion to its probability. By removing low-probability words from the candidates, it prevents clearly wrong words from slipping in while keeping the text diverse. It is widely used for generating text without a single correct answer, such as stories and dialogue.

Given the preceding words x1:i−1x_{1:i-1}, a language model outputs the probability P(x∣x1:i−1)P(x \mid x_{1:i-1}) of the next word xx for every word in the vocabulary. Methods for choosing the next word from these probabilities fall into two broad families.

  • Methods that maximize probability: greedy decoding and beam search. They search for high-probability sentences, but in open-ended text they are known to repeat the same phrases and produce bland text.
  • Methods that choose randomly according to the probabilities (sampling): A different text comes out each time. However, sampling directly from the whole vocabulary occasionally picks very low-probability words, which breaks the text.

Top-k sampling addresses the weakness of the latter. Fan et al. (2018) used it for story generation and reported that it was more effective than beam search. It later became widely known through its use in the generation samples of GPT-2.

Procedure

At each step, one word is chosen as follows.

  1. Use the model to compute the next-word probability P(x∣x1:i−1)P(x \mid x_{1:i-1}) for every word in the vocabulary.
  2. Select the kk words with the highest probabilities and call this set V(k)V^{(k)}.
  3. Set the probabilities of words outside V(k)V^{(k)} to 0 and divide by the total probability p′p' inside V(k)V^{(k)} so that the probabilities sum to 1 again (formula below).
  4. Randomly pick one word according to the renormalized probabilities.
  5. Append the chosen word to the sequence and repeat steps 1–4 until an end-of-sequence token appears or a set length is reached.

The set and renormalization in steps 2–3 are written as follows in Section 3.2 of Holtzman et al. (2020). V(k)V^{(k)} is the set of kk elements with the largest total probability (that is, the top kk).

p′=∑x∈V(k)P(x∣x1:i−1)p' = \sum_{x \in V^{(k)}} P(x \mid x_{1:i-1}) P′(x∣x1:i−1)={P(x∣x1:i−1)/p′(x∈V(k))0(otherwise)P'(x \mid x_{1:i-1}) = \begin{cases} P(x \mid x_{1:i-1}) / p' & (x \in V^{(k)}) \\ 0 & (\text{otherwise}) \end{cases}

With k=1k = 1, only the most probable word remains, so the method is the same as greedy decoding. With kk equal to the vocabulary size, nothing is cut, giving "pure sampling."

In practice, it is often combined with a temperature tt that smooths or sharpens the probabilities. Temperature divides the logits uu by tt before the softmax; with t<1t < 1, high-probability words become even more likely to be chosen (Equation 4 in Holtzman et al.). Fan et al. also adjust the temperature at generation time.

Example: the word after "Today is"

The figure at the top of the article shows examples of choosing the next word in two situations with k=3k = 3 (the probabilities are illustrative values, and the same examples are used in other articles in this category).

Flat distribution (after "Today is"): There are many candidates, and the top 3, "sunny," "rainy," and "Sunday," have a total probability of 0.30+0.20+0.15=0.650.30 + 0.20 + 0.15 = 0.65. Renormalizing by 0.65 gives the following.

WordOriginal probabilityRenormalized probability
sunny0.300.46
rainy0.200.31
Sunday0.150.23
7 words such as hot, cold, Monday0.35 in total0 (never chosen)

Even words that would follow naturally, such as "hot" (0.10) and "cold" (0.08), are discarded.

Peaked distribution (after "Thank you very"): "much" is almost certain (0.90), yet because k=3k = 3, "kindly" (0.06) and even "cat," with a probability of 0.01, remain as candidates.

Thus, with the same kk, both "cutting too much" and "keeping too much" occur depending on the shape of the distribution. This is the biggest weakness of top-k sampling, and it motivated nucleus sampling.

Why it works

Sampled text breaks down because of the collection of very low-probability words (the tail of the distribution). Each word's probability is small, but since the vocabulary contains tens of thousands of words, the total mass of the tail is far from negligible. Holtzman et al. call this the "unreliable tail" and identify it as the reason pure sampling produces incoherent text.

Fan et al. likewise explain that when a very low-probability word is chosen, a model that never saw such errors during training cannot recover, and generation breaks down. Restricting to the top kk means tail words are never chosen in the first place. At the same time, because the choice within the top is random, the method also avoids the repetitive and bland text that results from always choosing the safest word, as beam search does.

As an analogy, it is like "choosing on a whim from the three most popular dishes" at a restaurant. There is more variety than always ordering the number one dish (greedy decoding), and fewer misses than picking from the whole menu with your eyes closed (pure sampling).

Experimental results

Fan et al. (2018) generated stories on a dataset of 300,000 stories (WritingPrompts) by choosing from the top k=10k = 10. They reported that beam search tends to produce common phrases from the training data and repetition, yielding short and generic sentences, whereas this method was considerably more effective (no numerical comparison was given).

Holtzman et al. (2020) generated 5,000 continuations of WebText documents with GPT-2 Large and compared them with human-written text (excerpt from Table 1).

MethodPerplexitySelf-BLEU4Repetition (%)HUSE
Human text12.380.310.28−
Greedy1.500.5073.66−
Beam search (b=16b = 16)1.480.4428.94−
Pure sampling22.730.280.220.67
Top-k (k=40k = 40)6.880.390.780.19
Top-k (k=640k = 640)13.820.320.280.94
Top-k (k=40k = 40, temperature 0.7)3.480.448.860.08
Nucleus (p=0.95p = 0.95)13.130.320.360.97

The columns are read as follows.

  • Perplexity: The value measured on the generated text by the generating model itself. Closer to human text (12.38) is more natural. A value that is too low indicates that only high-probability words are being chosen.
  • Self-BLEU4: How similar the generated texts are to one another. Lower means more diverse.
  • Repetition: The proportion of generations whose end repeats the same phrase three or more times.
  • HUSE: An overall score of quality and diversity that combines human judgments with probability statistics. Higher is better.

Top-k sampling greatly reduces repetition compared with greedy decoding and beam search. However, at k=40k = 40, the perplexity is about half that of human text and Self-BLEU is high, so it is still on the "too safe" side. Raising kk to 640 brings it closer to human text, with a HUSE of 0.94, second only to nucleus sampling (0.97).

Caveats

The right kk changes from situation to situation. When there are many plausible candidates (a flat distribution), a small kk discards even natural words and yields bland text; when the answer is nearly determined (a peaked distribution), a large kk keeps inappropriate words and renormalization raises their probabilities. Holtzman et al. point out that a single kk cannot handle both cases.

  • Do not lower the temperature too much: In the experiments of Holtzman et al., combining k=40k = 40 with a temperature of 0.7 increased repetition from 0.78% to 8.86% and lowered perplexity to 3.48. Lowering the temperature stabilizes quality but sacrifices diversity.
  • Check library defaults: In Hugging Face's generate, setting do_sample=True applies the default value of 50 even if top_k is not specified. To disable top-k, specify top_k=0.
  • Not suited to tasks with nearly one correct answer: For tasks such as translation and summarization, where the most likely sentence for the input is wanted, beam search is a better fit.

Comparison with other decoding methods

Top-k sampling and nucleus sampling are both methods that "keep only the top of the distribution, renormalize, and then choose"; they differ only in where to cut.

MethodHow candidates are determinedNumber of candidatesOutputSuitable tasks
Beam searchSearch while keeping the top BB partial sequencesFixed (BB)Always the sameTranslation, summarization, speech recognition
Top-k sampling (this article)Top kk by probabilityFixed (kk)Varies each timeStories, dialogue
Nucleus samplingTop words until the total probability reaches ppVaries with the distributionVaries each timeStories, dialogue
Locally typical samplingWords whose information content is close to the average (entropy)Varies with the distributionVaries each timeStories, summarization
Contrastive searchWithin the top kk, chosen by both probability and not being too similar to the preceding contextFixed (kk)Always the sameGeneration that should avoid repetition

Guidelines for choosing:

  • Diverse text with little effort: top-k sampling. It is simple to implement, requiring only the computation of the top kk.
  • A number of candidates that adapts to the situation: nucleus sampling. Candidates shrink when the distribution is peaked and grow when it is flat.
  • The same output every time, while avoiding repetition: contrastive search.

PyTorch example

Show code
python
import torch


def top_k_sample(logits, k, temperature=1.0):
    """logits: [batch, vocab size]. Pick one word from the top k and return its index"""
    logits = logits / temperature                      # temperature (1.0 does nothing)
    top_values, top_indices = torch.topk(logits, k, dim=-1)  # logits and indices of the top k
    probs = torch.softmax(top_values, dim=-1)          # softmax over the k = same as renormalizing by the total p'
    choice = torch.multinomial(probs, num_samples=1)   # pick one in proportion to probability
    return top_indices.gather(-1, choice).squeeze(-1)  # map back to vocabulary indices


# Same probabilities as the figure at the top of the article (after "Today is")
words = ["sunny", "rainy", "Sunday", "hot", "cold", "Monday", "nice", "the", "cat", "of"]
p = torch.tensor([[0.30, 0.20, 0.15, 0.10, 0.08, 0.06, 0.05, 0.03, 0.02, 0.01]])
logits = p.log()  # passing log-probabilities as logits recovers the same probabilities after softmax

top_values, top_indices = torch.topk(logits, 3, dim=-1)
print([words[i] for i in top_indices[0]], torch.softmax(top_values, -1))
# ['sunny', 'rainy', 'Sunday'] tensor([[0.4615, 0.3077, 0.2308]])

torch.manual_seed(0)
counts = torch.zeros(len(words))
for _ in range(10000):
    counts[top_k_sample(logits, k=3)] += 1
print(counts / 10000)  # sunny, rainy, Sunday about 0.46, 0.31, 0.23; others 0


# Usage with a real model (autoregressively extend one word at a time)
@torch.no_grad()
def generate(model, input_ids, max_new_tokens=50, k=50, temperature=1.0, eos_id=None):
    """model(input_ids) is assumed to return logits of shape [batch, length, vocab size]"""
    model.eval()  # disable dropout (keep randomness only inside top_k_sample)
    for _ in range(max_new_tokens):
        next_logits = model(input_ids)[:, -1, :]       # next-word logits at the last position
        next_id = top_k_sample(next_logits, k, temperature)
        input_ids = torch.cat([input_ids, next_id[:, None]], dim=-1)
        if eos_id is not None and (next_id == eos_id).all():
            break
    return input_ids

# With Hugging Face Transformers
# model.generate(input_ids, do_sample=True, top_k=50, temperature=1.0, top_p=1.0)

FAQ

Q. What value should k take?
A.

There is no fixed value; validate it for the task and model. Fan et al. (2018) used k=10k = 10 for story generation, and the default in Hugging Face's generate is 50. In the GPT-2 experiments of Holtzman et al. (2020), k=640k = 640 came closer to the statistics of human text than k=40k = 40, but a larger kk makes it easier for low-probability words to slip in.

Q. Is the "top k" in top-k sampling the same as in beam search?
A.

No. Beam search keeps the top BB partial sequences and continues searching, then finally picks the single most probable sentence, so the output is always the same. Top-k sampling randomly picks one word from the top kk and moves on, so the output changes each time.

Q. Can top-k and top-p (nucleus) be used together?
A.

Yes. Many libraries first narrow to the top kk, and then further narrow to the words within that set until the total probability reaches pp. Setting kk fairly large and tuning with top-p reduces the problem of inappropriate words remaining in peaked distributions.

References

  1. A. Fan, M. Lewis, and Y. Dauphin, "Hierarchical Neural Story Generation," Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics (ACL), 2018.
  2. A. Holtzman, J. Buys, L. Du, M. Forbes, and Y. Choi, "The Curious Case of Neural Text Degeneration," ICLR, 2020.