Nucleus sampling is a text generation method where, for each step, the model calculates the probability distribution over its vocabulary for the next token. It then sorts these probabilities in descending order and selects the smallest set of tokens whose cumulative probability mass first exceeds a predefined threshold p (e.g., 0.9). This dynamic set, called the nucleus, contains the most plausible continuations. The model then samples the next token exclusively from this nucleus, re-normalizing the probabilities of the selected tokens. This approach contrasts with top-k sampling, which uses a fixed number of candidates, and with greedy decoding, which always selects the single most probable token.
Glossary
Nucleus Sampling (Top-p)

What is Nucleus Sampling (Top-p)?
Nucleus sampling, commonly referred to as top-p sampling, is a probabilistic decoding algorithm used to generate text from language models by dynamically selecting a subset of the most probable next tokens.
The primary advantage of nucleus sampling is its adaptive vocabulary selection. Unlike a fixed-k approach, the size of the candidate pool expands or contracts based on the shape of the probability distribution at each generation step. When the model is highly confident (a sharp distribution), the nucleus is small, promoting coherence. When the model is uncertain (a flat distribution), the nucleus expands, encouraging diversity and creativity. This makes it highly effective for producing human-like, varied text while reducing the chance of generating low-probability nonsense tokens. It is a foundational technique in modern large language model interfaces and is closely related to methods for controlling output temperature.
Nucleus Sampling vs. Top-k Sampling
A technical comparison of two probabilistic text generation methods used to introduce controlled randomness and diversity into model outputs.
| Feature / Metric | Nucleus Sampling (Top-p) | Top-k Sampling |
|---|---|---|
Core Selection Principle | Dynamic token set based on cumulative probability mass | Fixed number (k) of top-probability tokens |
Primary Control Parameter | Probability threshold p (e.g., 0.9, 0.95) | Integer k (e.g., 40, 50) |
Vocabulary Coverage | Adapts to the model's confidence per input | Constant per input, ignores probability mass |
Handling of Sharp vs. Flat Distributions | Robust: Set size shrinks/expands naturally | Inflexible: Can include low-probability tokens in flat distributions |
Risk of Sampling from Tail | Minimal: Excludes low-probability tail by design | Possible if k is large and distribution is flat |
Computational Overhead | Slightly higher: Requires cumulative sum calculation | Lower: Simple sort and select top k |
Common Use Case | Open-ended generation (stories, dialogue) where coherence is paramount | Tasks requiring strict, predictable vocabulary limitation |
Hyperparameter Sensitivity | Lower: p values of 0.9-0.95 are generally robust across tasks | Higher: Optimal k is highly task and model-dependent |
Key Features of Nucleus Sampling
Nucleus sampling, or top-p sampling, is a probabilistic text generation method that dynamically selects from the smallest set of most probable next tokens whose cumulative probability exceeds a threshold p. This balances creativity and coherence more effectively than traditional top-k sampling.
Dynamic Vocabulary Selection
Unlike top-k sampling, which selects from a fixed number of tokens, nucleus sampling dynamically adjusts the size of the candidate set for each generation step. It calculates the cumulative probability distribution of the model's predicted tokens, sorted in descending order. The algorithm then selects the smallest possible set of tokens where the sum of their probabilities first exceeds the threshold p (e.g., 0.9). This set is called the nucleus. For a sharp distribution, the nucleus may be small; for a flat distribution, it can be large, making the method contextually adaptive.
Probability Mass Threshold (p)
The core hyperparameter p (top-p) controls the selectivity of the sampling process. It represents a probability mass threshold, typically between 0.7 and 0.95.
- High p (e.g., 0.95): A larger nucleus is selected, including more lower-probability tokens. This increases diversity and creativity in the output but can also raise the risk of incoherence or off-topic text.
- Low p (e.g., 0.7): A smaller, sharper nucleus is selected, restricting choices to only the highest-probability tokens. This produces more conservative, predictable, and grammatically coherent text but can become repetitive. The value is chosen based on the desired trade-off between coherence and novelty for the specific application.
Contrast with Top-k Sampling
Top-k sampling fixes the number of candidate tokens (k), which can be problematic:
- With a sharp distribution, a high k includes many very low-probability, nonsensical tokens.
- With a flat distribution, a low k may exclude plausible, high-probability candidates. Nucleus sampling solves this by being distribution-aware. It ignores the long "tail" of very low-probability tokens regardless of their rank, focusing computational probability mass on credible next steps. This generally leads to more human-like and contextually appropriate text generation, reducing the incidence of glaring errors that can occur when sampling from a fixed-k tail.
Rescaling and Sampling
Once the nucleus (set V) is defined, the probabilities of the tokens within it are renormalized to sum to 1. This is done by dividing each token's original probability by the cumulative probability of the nucleus: P'(x) = P(x) / sum(P(V)). Sampling (e.g., multinomial sampling) is then performed over this renormalized distribution. This ensures:
- The model never samples from tokens outside the nucleus.
- The relative likelihood of tokens within the nucleus is preserved.
- The final output is drawn from a focused, high-quality probability distribution tailored to the specific context of the preceding tokens.
Handling of Tail Probabilities
A key benefit of nucleus sampling is its automatic and principled truncation of the vocabulary's long tail. In many language model outputs, a vast number of tokens have vanishingly small probabilities. By design, nucleus sampling excludes this entire tail, as its cumulative mass is below the threshold (1 - p). This eliminates the chance of generating highly improbable, often garbled tokens that can break coherence, a common failure mode in pure random sampling or poorly calibrated top-k. The method effectively focuses the model's "creative energy" on the plausible region of the probability distribution.
Application in Creative & Summarization Tasks
Nucleus sampling is particularly favored for open-ended generation tasks where diversity and interesting output are valued alongside coherence.
- Creative Writing & Story Generation: A p-value of 0.9-0.95 helps produce varied narrative turns while maintaining plot consistency.
- Dialogue Systems: It enables more engaging and less repetitive conversational responses.
- Code Generation: A lower p (e.g., 0.8) is often used to prioritize syntactically correct and predictable code structures.
- Text Summarization: It helps generate paraphrased summaries that avoid verbatim copying from the source. It is commonly used in conjunction with temperature scaling, which sharpens or flattens the distribution before the nucleus is selected.
Frequently Asked Questions
Nucleus sampling (top-p) is a core decoding method for controlling the creativity and coherence of text generated by language models. These questions address its mechanics, trade-offs, and practical applications.
Nucleus sampling, also called top-p sampling, is a probabilistic text generation method that dynamically selects a variable-sized set of the most probable next tokens for sampling. It works by sorting all possible next tokens by their predicted probability, then calculating the cumulative probability distribution. The algorithm selects the smallest set of top tokens whose cumulative probability exceeds a predefined threshold p (e.g., 0.9). It then re-normalizes the probabilities of this selected set (the "nucleus") and samples the next token from this distribution. This creates a dynamic vocabulary that adapts to the predictability of each step, unlike top-k sampling which uses a fixed number of candidates.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
Nucleus sampling is one of several probabilistic methods used to control the output of autoregressive language models. These related techniques define how a model selects the next token from its predicted probability distribution.
Top-k Sampling
Top-k sampling restricts the model's vocabulary to the k most probable next tokens before sampling. Unlike nucleus sampling's dynamic threshold, k is a fixed hyperparameter.
- Mechanism: At each generation step, only the top
ktokens by probability are considered. Probabilities are renormalized over this set, and a token is sampled. - Trade-off: A small
k(e.g., 10) makes output more predictable but potentially repetitive. A largek(e.g., 50) increases diversity but can allow low-probability, nonsensical tokens into the candidate pool. - Key Difference vs. Top-p: Top-k uses a static count; top-p uses a dynamic probability mass.
Temperature Scaling
Temperature is a hyperparameter applied to the logits (pre-softmax scores) of a model to control the randomness of its output distribution before any sampling method (like top-p or top-k) is applied.
- Formula: Adjusted probability = softmax(logits / temperature).
- Effect: A temperature < 1.0 (e.g., 0.7) sharpens the distribution, making high-probability tokens more likely. This yields more focused, deterministic text.
- Effect: A temperature > 1.0 (e.g., 1.5) flattens the distribution, giving lower-probability tokens a better chance. This increases creativity and diversity but also the risk of incoherence.
- Standard practice: Temperature tuning is almost always used in conjunction with top-p or top-k sampling.
Greedy Decoding
Greedy decoding is the simplest decoding strategy where the model selects the single token with the highest probability at every generation step.
- Mechanism: No sampling is involved. The output is
argmax(P(token | context))at each step. - Result: Produces the locally optimal choice at each step, but often leads to repetitive, generic, and globally sub-optimal text sequences. It lacks exploration.
- Contrast with Sampling: Greedy decoding is deterministic and often fails to capture the natural variation and nuance that probabilistic sampling methods (like top-p) provide. It is rarely used for creative text generation.
Beam Search
Beam search is a deterministic, heuristic search algorithm that explores multiple potential sequence continuations in parallel to find a high-probability overall output.
- Mechanism: It maintains
b(beam width) candidate sequences at each step. For each candidate, it considers the topknext tokens, generatingb * kpossibilities. It then prunes back to thebsequences with the highest cumulative (log) probability. - Use Case: Predominantly used in tasks where correctness and coherence are paramount and a single 'best' output is desired, such as machine translation or abstractive summarization.
- Trade-off: Can produce more fluent and coherent long-form text than greedy decoding but is computationally heavier and can still suffer from blandness or repetition. It is less common for open-ended dialogue.
Contrastive Search
Contrastive search is a decoding method designed to reduce repetition by penalizing tokens that are too similar to the recent context, promoting diversity while maintaining coherence.
- Mechanism: At each step, it selects from a set of high-probability candidates (like top-k/p). The final score balances the model's probability with a degeneration penalty. This penalty is based on the cosine similarity between the candidate token's embedding and the embeddings of tokens in the recent context.
- Goal: Suppress tokens that would lead to repetitive loops (e.g., "the the the") or generic continuations, encouraging the model to produce more novel and information-dense text.
- Benefit: Can mitigate common failure modes of standard sampling without requiring model retraining.
Typical Sampling
Typical sampling is an alternative to nucleus sampling that selects tokens based on how closely their individual information content matches the expected information of the distribution.
- Core Concept: It chooses tokens whose negative log probability (surprisal) is close to the entropy of the distribution. Formally, it samples from the set where
| -log(p) - H(p) | < ε. - Intuition: It filters out tokens that are either too predictable (high probability, low information) or too surprising (low probability, high information). This aims to produce text that is both coherent and consistently informative.
- Result: Empirical studies suggest it can reduce the incidence of both bland, generic outputs and extreme, nonsensical outputs compared to nucleus sampling, offering a different trade-off in the diversity-coherence spectrum.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us