Top-p sampling
Top-p sampling, also called nucleus sampling, is a stochastic decoding method for text generation. 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 introduced it in the 2019 preprint "The Curious Case of Neural Text Degeneration," published at 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 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 and greedy search with unrestricted sampling, temperature scaling, and top-k sampling [1].
The Problem with Deterministic Decoding
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
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].
- Sort tokens by probability. Arrange all tokens in descending order of their predicted probability.
- Accumulate probabilities. Starting from the most probable token, compute a running cumulative sum of probabilities.
- Identify the nucleus. Keep tokens through the first one that brings the sum to or above the threshold p.
- Renormalize. Rescale the probabilities of the tokens within the nucleus so that they sum to 1.
- Sample. Draw a token from this renormalized distribution.
Worked Example
Suppose a 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 $z_i$ and a positive temperature $T$, 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 GPT-5.2 | Accepts top_p when reasoning effort is none. Other reasoning effort settings reject a request that includes it [2]. |
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 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.
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].
Continue reading
- Decoding strategiesDecoding strategies are the algorithms that select output tokens from a language model's next-token probability distribution during text generation.Mentioned 11 times above
- International Conference on Learning RepresentationsThe International Conference on Learning Representations (ICLR) is an annual academic conference centered on representation learning and related areas of machine learning.Mentioned 3 times above
- Text Generation ModelsText generation models are language models trained to produce coherent natural-language text by predicting tokens one at a time, each conditioned on the preceding context.Linked in the introduction
- Yejin ChoiYejin Choi (born 1977) is a South Korean-born computer scientist and the Dieter Schwarz Foundation HAI Professor and Professor of Computer Science at Stanford UniversityLinked in the introduction
- Beam searchBeam search is a heuristic search algorithm for sequence generation that, at each decoding step, keeps only the top-K highest-scoring partial sequences (where K is the beam width) and discards the restMentioned 7 times above
- Temperature samplingTemperature sampling is the most common decoding control in large language models: a single hyperparameter, written T, that divides the model's output logits before the softmax function so that the formula…Mentioned 7 times above
More to read
- Top-p and top-k sampling
- Temperature (artificial intelligence)
- Greedy decoding
- Top-k sampling
- Language Model
- Anthropic
Topics:Large Language ModelsMachine LearningNatural Language Processing
References
- ^1 ^2 ^3 ^4 ^5 ^6 ^7 ^8 ^9 ^10 ^11 ^12 ^13 ^14 ^15 ^16 ^17 ^18 ^19 ^20 ^21 ^22 ^23 ^24 ^25 ^26Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes, and Yejin Choi. The Curious Case of Neural Text Degeneration. ICLR 2020, first posted April 2019.
- ^1 ^2 ^3OpenAI. Using GPT-5.2, section on GPT-5.2 parameter compatibility.
- ^1 ^2 ^3Anthropic. Migrating to API version 2026-10-21, section on sampling parameters.
- ^1 ^2 ^3Google Cloud. Gemini 2.5 Flash, model parameter defaults.
- ^Matthew Finlayson, John Hewitt, Alexander Koller, Swabha Swayamdipta, and Ashish Sabharwal. Closing the Curious Case of Neural Text Degeneration. ICLR 2024.
- ^1 ^2 ^3 ^4Minh 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. ICLR 2025.
- ^1 ^2John Hewitt, Christopher Manning, and Percy Liang. Truncation Sampling as Language Model Desmoothing. Findings of EMNLP 2022.
- ^1 ^2 ^3 ^4 ^5 ^6Hugging Face. Generation configuration. Transformers 4.55.4.
- ^Rylan Schaeffer, Joshua Kazdan, and Yegor Denisov-Blanch. Min-p, Max Exaggeration: A Critical Analysis of Min-p Sampling in Language Models. 2025.
- ^1 ^2 ^3Hugging Face. Generation utilities source code. Transformers 4.55.4.
- ^1 ^2 ^3Hugging Face. Utilities for Generation, `TopPLogitsWarper`. Transformers 4.55.4.
Improve this article
Add missing citations, update stale details, or write a clearer explanation. Anyone can edit: changes go live when you publish, and every edit is checked by an editor.
9 revisions · v9 · 2,518 words · full history
Fact-checks are independent of edits: a reviewer re-verifies the article against its sources and stamps the date. How we verify
Research and drafting on this wiki are AI-assisted, under named human editorial standards. How AI is used here
Reviewer note: The original min-p study and a reanalysis of its evaluations disagree about whether min-p improves on top-p and other samplers. Both findings are attributed in the comparison. The top-p definition and six-token worked example follow Holtzman and colleagues' threshold rule.
Cite this page: AI Wiki. "Top-p sampling." aiwiki.ai, updated 5 Dec 2026. CC BY 4.0. https://aiwiki.ai/wiki/top_p



