K Sampling
Definition
Top-k sampling is a decoding strategy used in language models to generate text. In this approach, the model selects the next token in a sequence from the top k tokens with the highest probabilities. This method helps in controlling the randomness and diversity of the generated text by focusing only on the most likely tokens.
Mechanism
In top-k sampling, the process begins by evaluating the logits (raw prediction scores) for all possible tokens. The top k tokens with the highest logits are identified, and all other tokens are excluded from consideration by setting their logits to negative infinity (-inf). This exclusion ensures that when the softmax function is applied, the probability distribution assigns a probability of 0 to all non-top-k tokens. Consequently, the probabilities of the top-k tokens are normalized to sum up to 1.
This method is particularly useful in generating coherent and contextually relevant text, as it limits the selection to the most probable tokens while still allowing for some variability in the output.
Illustration
The concept of top-k sampling is visually represented in Figure 5.15. In this example, with k set to 3, the focus is on the three tokens with the highest logits. The figure demonstrates how the non-top-k tokens are masked out with negative infinity before applying the softmax function, resulting in a probability distribution where only the top-k tokens have non-zero probabilities.
Figure 5.15 Using top-k sampling with k = 3, we focus on the three tokens associated with the highest logits and mask out all other tokens with negative infinity (–inf) before applying the softmax function. This results in a probability distribution with a probability value 0 assigned to all non-top-k tokens. (The numbers in this figure are truncated to two digits after the decimal point to reduce visual clutter. The values in the “Softmax” row should add up to 1.0.)
Applications
Top-k sampling is often used in conjunction with other techniques such as probabilistic sampling and temperature scaling to enhance text generation results. By restricting the selection to the top-k most likely tokens, the model can produce more coherent and contextually appropriate text, while still allowing for creative and diverse outputs. This approach is particularly beneficial in applications where maintaining a balance between randomness and determinism is crucial.