Top-k sampling is a decoding method that keeps only the top 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 , a language model outputs the probability of the next word 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.

