# Top-p sampling

> Source: https://aiwiki.ai/wiki/top_p
> Updated: 2026-12-05
> Categories: Large Language Models, Machine Learning, Natural Language Processing
> License: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/) - attribute to "AI Wiki (aiwiki.ai)"
> Cite as: AI Wiki. "Top-p sampling." aiwiki.ai, 5 Dec 2026. https://aiwiki.ai/wiki/top_p
> From AI Wiki (https://aiwiki.ai), the free encyclopedia of artificial intelligence. Reuse freely with attribution.

Top-p sampling, also called **nucleus sampling**, is a stochastic [decoding](https://aiwiki.ai/wiki/decoding_strategies) method for [text generation](https://aiwiki.ai/wiki/text_generation_models). At each step it ranks possible next tokens by probability, keeps the shortest prefix whose probabilities sum to at least *p*, and samples from that prefix. Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes, and [Yejin Choi](https://aiwiki.ai/wiki/yejin_choi) introduced it in the 2019 preprint "The Curious Case of Neural Text Degeneration," published at [ICLR](https://aiwiki.ai/wiki/iclr) 2020 [1].

The number of tokens available for a draw can change with every word of the prompt or generated passage. In [large language model](https://aiwiki.ai/wiki/large_language_model) APIs, whether a user can set `top_p` depends on the model, its mode, and the API version [1][2][3][4].

## Background and Motivation

Holtzman and colleagues studied open-ended continuations, where many responses to a prompt may be plausible. They compared [beam search](https://aiwiki.ai/wiki/beam_search) and greedy search with unrestricted sampling, [temperature](https://aiwiki.ai/wiki/temperature_sampling) scaling, and [top-k sampling](https://aiwiki.ai/wiki/top_k_sampling) [1].

### The Problem with Deterministic Decoding

[Greedy decoding](https://aiwiki.ai/wiki/greedy_decoding) selects a most probable token at every step. Beam search retains several high-scoring partial sequences. On the authors' GPT-2 continuations, greedy and beam outputs often repeated phrases. In human-written passages, the model's probabilities for successive words varied more widely. Choosing only high-scoring continuations changed that pattern [1].

### The Problem with Top-k Sampling

Top-k sampling restricts each draw to the *k* highest-ranked tokens. Consider two hypothetical prompts. If nearly all probability follows "The capital of France is" in a single token, keeping five tokens admits four unlikely alternatives. After "My favorite food is," the same limit excludes every possibility below fifth place even if it is almost as probable as the fifth. Holtzman et al. used this difference between concentrated and diffuse distributions to motivate an adaptive cutoff [1].

## How Top-p Sampling Works

<figure>
<a href="/images/top-p-f30a9fb8bdbf.png"><img src="/images/top-p-f30a9fb8bdbf.png" alt="Cumulative probability plot first crosses 80 percent at token three." width="1120" height="585" /></a>
<figcaption>At a threshold of 80%, two tokens supply only 70% of the mass. The third brings the total to 86%, completing the nucleus. Original illustration by AI Wiki. <a href="https://arxiv.org/abs/1904.09751">Method source</a>.</figcaption>
</figure>



At each generation step, the model produces a probability distribution for the next token. For a threshold greater than zero and at most one, the sampler performs the following steps [1].

1. **Sort tokens by probability.** Arrange all tokens in descending order of their predicted probability.
2. **Accumulate probabilities.** Starting from the most probable token, compute a running cumulative sum of probabilities.
3. **Identify the nucleus.** Keep tokens through the first one that brings the sum to or above the threshold *p*.
4. **Renormalize.** Rescale the probabilities of the tokens within the nucleus so that they sum to 1.
5. **Sample.** Draw a token from this renormalized distribution.

### Worked Example

Suppose a [language model](https://aiwiki.ai/wiki/language_model) assigns the following next-token probabilities after "The weather today is." The numbers illustrate the rule in the original paper [1].

| Token | Probability | Cumulative Probability |
|---|---|---|
| sunny | 0.35 | 0.35 |
| warm | 0.20 | 0.55 |
| nice | 0.15 | 0.70 |
| beautiful | 0.10 | 0.80 |
| cloudy | 0.07 | 0.87 |
| cold | 0.05 | 0.92 |
| perfect | 0.03 | 0.95 |
| terrible | 0.02 | 0.97 |
| Remaining tokens combined | 0.03 | 1.00 |

With *p* = 0.90, the first five tokens account for 0.87. Adding the sixth, "cold," raises the total to 0.92. The nucleus therefore contains **six tokens**, from "sunny" through "cold." Dividing each probability by 0.92 gives "sunny" a sampling probability of approximately 38.04% and "cold" approximately 5.43%. At *p* = 0.87 exactly, the sampler stops at "cloudy" and keeps five tokens [1].

Now consider a more concentrated distribution after "The capital of France is." The last row again combines multiple lower-ranked tokens [1].

| Token | Probability | Cumulative Probability |
|---|---|---|
| Paris | 0.96 | 0.96 |
| the | 0.01 | 0.97 |
| a | 0.005 | 0.975 |
| Remaining tokens combined | 0.025 | 1.00 |

With *p* = 0.90, the nucleus contains just "Paris." Its sampling probability becomes 1 at this step. The next step uses a new distribution [1].

## Mathematical Formulation

Given a context, order its possible continuations so their next-token probabilities satisfy $q_1 \ge q_2 \ge \cdots \ge q_n$. Write $C_j = \sum_{i=1}^{j} q_i$. For $0 < p \le 1$, let $m$ be the first index with $C_m \ge p$. The nucleus consists of the first $m$ tokens. Each retained token $i$ has sampling probability $q_i/C_m$, and each excluded token has probability zero [1].

The ordering matters if a tie straddles the cutoff. For probabilities 0.50, 0.25 and 0.25 at *p* = 0.75, the first token and either one of the two tied tokens meet the rule. A particular ordering chooses which tied token occupies second place. At *p* = 1, all positive probability mass is retained. At thresholds up to and including the largest token probability, one token suffices. The mathematical definition above assumes positive *p*. An interface that accepts zero defines how it handles that endpoint [1][4][8].

## Comparison with Other Decoding Strategies

### Top-p vs. Top-k Sampling

| Aspect | Top-p (nucleus) | Top-k |
|---|---|---|
| Cutoff | Cumulative probability threshold | Token rank |
| Size of candidate set | Can change at each step | Fixed at *k* when at least *k* tokens are available and ties are ordered |
| Mass kept | At least *p* | Sum of the first *k* probabilities |

At *p* = 0.90 a token with probability 0.95 forms the entire nucleus. If 200 tokens are equally likely, the same *p* keeps 180 under the ordered-prefix convention. Top-k with *k* = 50 keeps 50 of the 200, covering only 25% of the mass [1].

The two filters can also be applied in sequence. For example, Transformers 4.55.4 applies the top-k filter before top-p. Top-p then uses probabilities normalized over the surviving candidates. A filter applied to those candidates can give a different answer from one calculated on the original distribution [8][10][11].

### Top-p vs. Temperature

Given [logits](https://aiwiki.ai/wiki/logits) $z_i$ and a positive temperature $T$, [softmax](https://aiwiki.ai/wiki/softmax) assigns token $i$ probability $\exp(z_i/T) / \sum_j \exp(z_j/T)$. Temperature scaling changes the odds between tokens. Top-p preserves the relative odds between any pair that survives its cutoff [1].

| Setting | Effect on the next draw |
|---|---|
| $0 < T < 1$ | Sharpens differences in probability |
| $T = 1$ | Preserves the original probabilities |
| $T > 1$ | Flattens differences in probability |
| Higher *p* at fixed temperature | Keeps the same prefix or extends it |
| Lower *p* at fixed temperature | Keeps the same prefix or shortens it |

### Interaction Between Temperature and Top-p

When temperature is applied first, it affects how many tokens top-p retains. Raising the temperature moves mass away from the leading tokens in a nonuniform distribution, so a given threshold can require a longer prefix. If the distribution is uniform to begin with, scaling by a positive temperature leaves it uniform [1][10].

### Greedy Decoding and Beam Search

Greedy decoding commits to one token at each step. Beam search can retain alternative prefixes and rank them again after the next step. Nucleus sampling draws one continuation in proportion to the probabilities left after truncation. When the leading token alone reaches the threshold, greedy decoding and a nucleus draw can make the same choice [1].

## Typical Values and API Defaults

### Provider Defaults

| Model, API or library | Documented behavior |
|---|---|
| [OpenAI](https://aiwiki.ai/wiki/openai) GPT-5.2 | Accepts `top_p` when reasoning effort is `none`. Other reasoning effort settings reject a request that includes it [2]. |
| [Anthropic](https://aiwiki.ai/wiki/anthropic) Messages API version `2026-10-21` | Sending `top_p` in a Messages or Message Batch request returns HTTP 400, including when the supplied value is the former default [3]. |
| Google Cloud Gemini 2.5 Flash (`gemini-2.5-flash`) | Its model specification lists `topP` from 0.0 to 1.0, with a default of 0.95 [4]. |
| [Hugging Face](https://aiwiki.ai/wiki/hugging_face) Transformers 4.55.4 | A model's generation configuration can specify `top_p`. The library fallback is 1.0. Sampling is enabled with `do_sample=True` [8]. |

### Recommended Values by Use Case

Holtzman et al. reported *p* = 0.95 for a WebText continuation experiment. That experiment measured properties such as repetition and similarity to human writing. It did not test how often generated code compiled or a factual answer was correct. A threshold specifies how much next-token probability to retain. It supplies no syntax or factuality test [1].

## Why Nucleus Sampling Was Invented

The authors observed two different failure modes in GPT-2. Beam search could repeat a phrase whose probability rose with repetition. Unrestricted sampling could select an improbable token that made the resulting passage hard to follow. The authors studied how much mass the model assigned to the most likely completions at different points in a passage. That mass varied with context, motivating a variable number of candidates [1].

## The Original Paper in Detail

The authors generated 5,000 passages from GPT-2 Large, using first paragraphs from held-out WebText documents as prompts. A passage ended at an end-of-document token or 200 generated tokens. Table 1 of the paper illustrates how different measurements rank the same decoding methods [1].

| Method | Perplexity | Repetition (%) |
|---|---:|---:|
| Human text | 12.38 | 0.28 |
| Greedy decoding | 1.50 | 73.66 |
| Beam search (width 16) | 1.48 | 28.94 |
| Unrestricted sampling | 22.73 | 0.22 |
| Top-k (*k* = 640) | 13.82 | 0.28 |
| Nucleus sampling (*p* = 0.95) | 13.13 | 0.36 |

The paper counted a passage as repetitive when a phrase of at least two tokens repeated at least three times at the end. The authors also combined human typicality ratings with a statistical evaluation called HUSE. For that comparison, they mixed 10% of the original distribution back into the truncated top-k and nucleus distributions. This version of nucleus sampling scored 0.97 on HUSE, compared with 0.94 for top-k at *k* = 640 [1].

## Closing the Curious Case: Follow-Up Research

In 2022, John Hewitt, Christopher Manning, and Percy Liang proposed viewing the probabilities learned by a language model as a mixture of a true distribution and a smoothing distribution. They called removal of the extra probability mass *desmoothing*. They also examined cases where top-p pruned plausible continuations and proposed eta sampling, which uses an entropy-dependent cutoff [7].

In "Closing the Curious Case of Neural Text Degeneration" (ICLR 2024), Matthew Finlayson, John Hewitt, Alexander Koller, Swabha Swayamdipta, and Ashish Sabharwal studied a different explanation. They examined the *softmax bottleneck*, a restriction on which distributions a model's output layer can represent. Under their assumptions, a probability threshold can exclude tokens with zero true probability while also discarding some valid continuations. The paper investigated a sampling rule that uses the output layer to identify more of those valid candidates [5].

## Min-p Sampling: A Newer Alternative

Nguyen and colleagues compared nucleus sampling with **min-p sampling** in "Turning Up the Heat," presented at ICLR 2025 [6].

### How Min-p Works

For a fraction *m*, min-p retains each candidate with probability at least *m* times the most probable token's probability. For example, if the leading token has probability 0.40 and *m* = 0.10, every token with probability at least 0.04 qualifies. Top-p requires a running total over the ranked candidates. Min-p only needs each candidate's probability and the maximum [6][8].

### Does min-p improve on top-p?

Nguyen et al. reported that human evaluators favored min-p for quality and creativity in their experiments [6]. Schaeffer, Kazdan, and Denisov-Blanch reanalyzed the human evaluations and reported no advantage over the baseline samplers. Their benchmark comparisons also found no improvement when the samplers received comparable tuning [9].

### Adoption

Transformers 4.55.4 documents both `top_p` and `min_p` as generation settings and defines the latter as a fraction of the highest token probability [8].

## Relationship to Other Decoding Strategies

| Strategy | Quantity used to select candidates |
|---|---|
| Greedy decoding | Largest token probability [1] |
| Beam search | Scores of partial sequences extended over multiple steps [1] |
| Top-k sampling | Fixed token-rank cutoff [1] |
| Top-p sampling | Cumulative probability of a ranked prefix [1] |
| Min-p sampling | Probability relative to the highest-probability token [6] |
| Eta sampling | Token probability compared with a threshold that depends on the distribution's entropy [7] |

A broader comparison appears in [Top-p and top-k sampling](https://aiwiki.ai/wiki/top_p_sampling).

## Implementation Details

This pseudocode samples once, assuming at least one eligible token and finite logits for the eligible tokens. Token ID breaks ties so the selection in this example is reproducible for a given probability distribution and random draw [1][11].

```
function top_p_sample(logits, p, temperature=1.0):
    require 0 < p <= 1 and temperature > 0
    probs = softmax(logits / temperature)
    if p == 1:
        return categorical_sample(probs)

    ordered = token_ids_sorted_by_decreasing_probability_then_id(probs)
    total = 0
    retained = []
    for token in ordered:
        retained.append(token)
        total += probs[token]
        if total >= p:
            break

    return weighted_sample(retained, weights=probs[retained] / total)
```

A full comparison sort takes $O(n \log n)$ time for $n$ tokens. Implementations can also enforce a minimum number of surviving candidates. For example, Transformers' `TopPLogitsWarper` exposes `min_tokens_to_keep`, with a default of one. A larger minimum can retain more tokens than the mathematical cutoff requires [11].

## Practical Guidance

Consider the other filters when interpreting a `top_p` value. In a Transformers 4.55.4 sampling run with top-k enabled, setting `top_p=1.0` disables top-p truncation. Top-k can still exclude tokens. Likewise, decreasing *p* has no effect on a particular draw's distribution until the cutoff crosses a cumulative probability in that context [1][8][10].

## Current State (2025 to 2026)

Two versions of the same sampling request can behave differently at an API boundary. For example, GPT-5.2 checks the reasoning setting before accepting `top_p`. Anthropic's `2026-10-21` Messages API checks whether the field is present at all. The model identifier, API version, and other decoding settings are therefore relevant when reporting the use of nucleus sampling [2][3].

## References

[1] Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes, and Yejin Choi. [The Curious Case of Neural Text Degeneration](https://arxiv.org/abs/1904.09751). ICLR 2020, first posted April 2019.

[2] OpenAI. [Using GPT-5.2](https://developers.openai.com/api/docs/guides/latest-model?model=gpt-5.2), section on GPT-5.2 parameter compatibility.

[3] Anthropic. [Migrating to API version 2026-10-21](https://platform.claude.com/docs/en/api/migration-2026-10-21), section on sampling parameters.

[4] Google Cloud. [Gemini 2.5 Flash](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/gemini/2-5-flash), model parameter defaults.

[5] Matthew Finlayson, John Hewitt, Alexander Koller, Swabha Swayamdipta, and Ashish Sabharwal. [Closing the Curious Case of Neural Text Degeneration](https://proceedings.iclr.cc/paper_files/paper/2024/file/34899013589ef41aea4d7b2f0ef310c1-Paper-Conference.pdf). ICLR 2024.

[6] Minh Nguyen, Andrew Baker, Clement Neo, Allen Roush, Andreas Kirsch, and Ravid Shwartz-Ziv. [Turning Up the Heat: Min-p Sampling for Creative and Coherent LLM Outputs](https://proceedings.iclr.cc/paper_files/paper/2025/hash/afa5f124e36bed5cc2125067005d43f5-Abstract-Conference.html). ICLR 2025.

[7] John Hewitt, Christopher Manning, and Percy Liang. [Truncation Sampling as Language Model Desmoothing](https://aclanthology.org/2022.findings-emnlp.249/). Findings of EMNLP 2022.

[8] Hugging Face. [Generation configuration](https://huggingface.co/docs/transformers/v4.55.4/main_classes/text_generation). Transformers 4.55.4.

[9] Rylan Schaeffer, Joshua Kazdan, and Yegor Denisov-Blanch. [Min-p, Max Exaggeration: A Critical Analysis of Min-p Sampling in Language Models](https://arxiv.org/abs/2506.13681). 2025.

[10] Hugging Face. [Generation utilities source code](https://github.com/huggingface/transformers/blob/v4.55.4/src/transformers/generation/utils.py#L1188-L1197). Transformers 4.55.4.

[11] Hugging Face. [Utilities for Generation](https://huggingface.co/docs/transformers/v4.55.4/internal/generation_utils#transformers.TopPLogitsWarper), `TopPLogitsWarper`. Transformers 4.55.4.

