AI Logic

Decoding

Nucleus (Top-p) Sampling

Updated:

Example of nucleus sampling with p = 0.8. At the top is the flat distribution after "Today is": adding probabilities in descending order reaches a total of 0.83 at the fifth word, "cold," so 5 words are kept and renormalized into the probabilities on the right. At the bottom is the peaked distribution after "Thank you very": the first word, "much," alone reaches 0.90, so only "much" is kept

What is nucleus sampling?

Nucleus sampling (top-p sampling) is a decoding method that adds up the next-word probabilities produced by a language model in descending order, keeps only the words up to the point where the total reaches pp, and randomly picks one of them in proportion to its probability. Its defining feature is that the number of words kept automatically grows or shrinks with the shape of the distribution. It was proposed by Holtzman et al. (2020) and is widely used for open-ended text generation such as stories and dialogue.

The previously common top-k sampling keeps the top kk words by probability. However, the right number of candidates varies greatly from situation to situation.

  • When many words could follow, as after "Today is," it is better to keep more.
  • When the answer is nearly determined, as after "Thank you very," it is better to narrow down to one or two.

Nucleus sampling handles both by cutting on total probability rather than on a count. The paper calls the set of top words that holds most of the probability mass the "nucleus."

Procedure

At each step, one word is chosen as follows (Section 3.1 of Holtzman et al.).

  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. Sort the words in descending order of probability and add up their probabilities from the top.
  3. Stop as soon as the total first reaches pp or more, and call the set of words up to that point V(p)V^{(p)}.
  4. Set the probabilities of words outside V(p)V^{(p)} to 0 and divide by the total probability p′p' inside V(p)V^{(p)} so that the probabilities sum to 1 again.
  5. Randomly pick one word according to the renormalized probabilities.

V(p)V^{(p)} in step 3 is the smallest set whose total probability is pp or more.

∑x∈V(p)P(x∣x1:i−1)≥p\sum_{x \in V^{(p)}} P(x \mid x_{1:i-1}) \ge p

With p′=∑x∈V(p)P(x∣x1:i−1)p' = \sum_{x \in V^{(p)}} P(x \mid x_{1:i-1}), the renormalization in step 4 is as follows.

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

With p=1p = 1, nothing is cut, giving "pure sampling"; as pp approaches 0, only the most probable word remains, so the method approaches greedy decoding.

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 p=0.8p = 0.8 (the probabilities are illustrative values, the same examples as in the top-k sampling article).

Flat distribution (after "Today is"): Adding up in descending order of probability gives the following.

RankWordProbabilityRunning totalResult
1sunny0.300.30Keep
2rainy0.200.50Keep
3Sunday0.150.65Keep
4hot0.100.75Keep
5cold0.080.83Keep (the total reaches 0.8 here)
6–10Monday, nice, the, cat, of0.06–0.01−Discard

Five words remain, and dividing by their total of 0.83 gives sunny 0.36, rainy 0.24, Sunday 0.18, hot 0.12, and cold 0.10. "hot" and "cold," which top-k with k=3k = 3 discarded, are now candidates.

Peaked distribution (after "Thank you very"): The top word "much" alone has 0.90, exceeding 0.8. The only candidate is therefore "much," and "cat," with a probability of 0.01, can never be chosen. With top-k at k=3k = 3, even "cat" remained.

With the same p=0.8p = 0.8, the number of candidates changes between 5 words and 1 word. This is what "the number of candidates adapts to the shape of the distribution" means.

Why it works

Holtzman et al. explain the failure of open-ended text generation in terms of two causes.

  • Maximizing probability makes text dull: Searching for high-probability sentences with methods such as beam search leads to repeated phrases and generic text. Human-written text is not a sequence of high-probability words only; it occasionally includes low-probability words that carry a lot of information.
  • Pure sampling breaks down on tail words: Even if each word's probability is very small, the vocabulary contains tens of thousands of words, so their total probability is far from negligible. When a word is drawn from this "unreliable tail," the text becomes incoherent.

Nucleus sampling prevents the latter by cutting the tail, and the former by choosing randomly within the nucleus. Top-k sampling follows the same idea, but because nucleus sampling "cuts by total probability," the cut-off moves with the model's confidence. When the model is uncertain (a flat distribution), it takes a wide range of candidates; when it is confident (a peaked distribution), a narrow one. The paper notes that the size of the nucleus varies from 1 word to around 1,000 words depending on the context.

As an analogy, top-k is "always choosing from the top 3 dishes," while nucleus is "choosing from the popular dishes that make up 80% of all orders." At a restaurant where orders concentrate on one signature dish, the choice narrows to that one dish; at one where every dish is about equally popular, the options widen.

Experimental results

Holtzman et al. used GPT-2 Large (762 million parameters) to generate 5,000 continuations of WebText document prefixes (up to 200 tokens) and compared them with human-written text (excerpt from Table 1).

MethodPerplexitySelf-BLEU4Zipf coefficientRepetition (%)HUSE
Human text12.380.310.930.28−
Greedy1.500.501.0073.66−
Beam search (b=16b = 16)1.480.440.9428.94−
Pure sampling22.730.280.930.220.67
Sampling with temperature 0.910.250.350.960.660.79
Top-k (k=40k = 40)6.880.390.960.780.19
Top-k (k=640k = 640)13.820.320.960.280.94
Nucleus (p=0.95p = 0.95)13.130.320.950.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 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.
  • Zipf coefficient: The skew in word usage. Closer to human text means more natural vocabulary usage.
  • 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.

Nucleus sampling (p=0.95p = 0.95) had perplexity and Self-BLEU close to human text, and the highest HUSE of the methods compared, at 0.97. The paper notes that pure sampling and top-k with a large kk can also match human perplexity, but at those settings the text tends to lose coherence. It also shows that Self-BLEU closely matches human text over the commonly used range p∈[0.9,1)p \in [0.9, 1) (Figure 8).

Caveats

If pp is too small, the problems of greedy decoding return. Holtzman et al. report that every sampling method approaches greedy decoding and repeats more when its parameter is made small enough to cut too much. For open-ended text generation, it is common to start with pp around 0.9–0.95.

  • Mind the order when combining with temperature: Temperature changes the shape of the probabilities, so with the same pp, the number of words kept depends on the temperature. Hugging Face's generate applies the temperature first, then cuts with top-k and then top-p.
  • Mind the top-k default: Hugging Face's generate applies top_k=50 by default when do_sample=True. To use nucleus sampling alone, specify top_k=0.
  • The number of candidates changes every time: In situations with a flat distribution, the nucleus can contain several hundred words or more. Even so, tail words beyond the point where the total reaches pp are never chosen.
  • Not suited to tasks with nearly one correct answer: For tasks such as translation and summarization, where the most likely sentence is wanted, beam search is a better fit.

Comparison with other decoding methods

Nucleus sampling and top-k sampling are both methods that "keep only the top of the distribution, renormalize, and then choose"; they differ only in where to cut (Section 3.2 of Holtzman et al.).

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 samplingTop kk by probabilityFixed (kk)Varies each timeStories, dialogue
Nucleus sampling (this article)Top 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:

  • Natural open-ended text: Start with nucleus sampling (p=0.9p = 0.9–0.950.95). Because the number of candidates changes with the situation, a single value covers a wide range of situations.
  • A firm cap on the number of candidates: top-k sampling, or top-k combined with top-p.
  • Avoiding words that are too probable as well: locally typical sampling. Nucleus sampling always keeps the most probable words, whereas typical sampling may also exclude words that are "too predictable."

PyTorch example

Show code
python
import torch


def nucleus_sample(logits, p, temperature=1.0):
    """logits: [batch, vocab size]. Pick one word from the top words until the total probability reaches p"""
    probs = torch.softmax(logits / temperature, dim=-1)
    sorted_probs, sorted_idx = torch.sort(probs, dim=-1, descending=True)
    cum = sorted_probs.cumsum(dim=-1)
    # discard a word if the words above it already total p or more (the top word is always kept)
    remove = (cum - sorted_probs) >= p
    sorted_probs = sorted_probs.masked_fill(remove, 0.0)
    sorted_probs = sorted_probs / sorted_probs.sum(dim=-1, keepdim=True)  # renormalize by the total p'
    choice = torch.multinomial(sorted_probs, num_samples=1)
    return sorted_idx.gather(-1, choice).squeeze(-1)  # map back to vocabulary indices


# Same probabilities as the figure at the top of the article
words = ["sunny", "rainy", "Sunday", "hot", "cold", "Monday", "nice", "the", "cat", "of"]
flat = torch.tensor([[0.30, 0.20, 0.15, 0.10, 0.08, 0.06, 0.05, 0.03, 0.02, 0.01]])
peak = torch.tensor([[0.90, 0.06, 0.01, 0.01, 0.01, 0.01]])  # much, kindly, cat, sunny, of, rainy

torch.manual_seed(0)
for name, dist in [("flat", flat), ("peaked", peak)]:
    picks = torch.stack([nucleus_sample(dist.log(), p=0.8) for _ in range(5000)])
    print(name, "distinct words chosen:", picks.unique().numel())
# flat distinct words chosen: 5 (sunny to cold)
# peaked distinct words chosen: 1 (much)


# Usage with a real model (autoregressively extend one word at a time)
@torch.no_grad()
def generate(model, input_ids, max_new_tokens=50, p=0.95, temperature=1.0, eos_id=None):
    """model(input_ids) is assumed to return logits of shape [batch, length, vocab size]"""
    model.eval()  # disable dropout
    for _ in range(max_new_tokens):
        next_id = nucleus_sample(model(input_ids)[:, -1, :], p, 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 (top_k=0 disables top-k)
# model.generate(input_ids, do_sample=True, top_p=0.95, top_k=0)

FAQ

Q. What value should p take?
A.

For open-ended text generation, it is common to start around 0.9–0.95. The comparison by Holtzman et al. (2020) used p=0.95p = 0.95 and showed that over the range p∈[0.9,1)p \in [0.9, 1), the diversity of generated text (Self-BLEU) is close to that of human text. Smaller values are safer but more repetitive; values closer to 1 are more diverse but more likely to break down.

Q. Should I use top-p or top-k?
A.

If you choose only one, top-p (nucleus) is easier to handle. Because the number of candidates changes with the situation, it does not keep inappropriate words when the answer is nearly determined. Many libraries allow both at the same time, first setting an upper limit with top-k and then narrowing with top-p.

Q. Does nucleus sampling eliminate repetition?
A.

It reduces repetition but does not eliminate it. In the experiments of Holtzman et al., repetition appeared in 0.36% of generations with p=0.95p = 0.95 (0.28% for human text). Lowering pp increases repetition. When repetition must be strongly avoided, also consider repetition penalties or contrastive search.

References

  1. A. Holtzman, J. Buys, L. Du, M. Forbes, and Y. Choi, "The Curious Case of Neural Text Degeneration," ICLR, 2020.