Top-p (nucleus) sampling is a decoding strategy that dynamically selects the smallest set of tokens whose cumulative probability mass exceeds a threshold p, sampling only from this nucleus of high-confidence options. Unlike top-k sampling, which uses a fixed vocabulary size, top-p adapts the candidate pool based on the shape of the probability distribution, ensuring coherent generation in both high- and low-confidence contexts.
Glossary
Top-p (Nucleus) Sampling

What is Top-p (Nucleus) Sampling?
Top-p sampling, also known as nucleus sampling, is a decoding strategy that dynamically selects the smallest set of tokens whose cumulative probability mass exceeds a threshold p, sampling only from this nucleus of high-confidence options.
The mechanism sorts predicted tokens by descending probability, then sums them until the cumulative mass reaches p. Only this dynamically sized subset is considered for random sampling, while the tail of low-probability tokens is discarded. This prevents the model from selecting improbable words that would derail fluency, making it a standard technique for hallucination mitigation and high-quality natural language generation.
Key Characteristics of Top-p Sampling
Top-p sampling, also known as nucleus sampling, is a decoding strategy that dynamically selects the smallest set of tokens whose cumulative probability mass exceeds a threshold p, sampling only from this nucleus of high-confidence options. This approach adapts the candidate pool size based on the model's confidence distribution, providing a robust balance between text quality and diversity.
Dynamic Vocabulary Truncation
Unlike top-k sampling which uses a fixed number of candidates, top-p dynamically adjusts the candidate set size based on the probability distribution shape. When the model is highly confident, the nucleus is small; when uncertain, it expands. This prevents including low-probability tokens in flat distributions while preserving diversity in peaked ones. The algorithm sorts tokens by probability, then cumulatively sums them until the threshold p is reached, discarding all remaining tokens.
The Cumulative Probability Mechanism
The core algorithm operates in three steps:
- Sort: Arrange all tokens in descending order by their predicted probability
- Accumulate: Compute the cumulative sum of probabilities starting from the highest
- Truncate: Retain only tokens whose cumulative sum ≤ p
For example, with p=0.9, if the top token has 0.5 probability and the next has 0.3, the cumulative sum reaches 0.8. The third token at 0.15 pushes it to 0.95, exceeding the threshold, so only the first two tokens form the nucleus.
Adaptive Behavior Across Distributions
Top-p sampling exhibits fundamentally different behavior depending on the entropy of the prediction:
- High-confidence context: When one token dominates (e.g., 0.95 probability), the nucleus contains only that single token, effectively behaving as greedy decoding
- Medium-confidence context: A moderate spread of probabilities yields a nucleus of 5-20 tokens, enabling controlled creativity
- Low-confidence context: A flat distribution may require dozens of tokens to reach the p threshold, allowing broader exploration
This adaptivity makes top-p superior to fixed-k approaches for open-ended generation tasks.
Interaction with Temperature
Top-p sampling is typically combined with temperature scaling for fine-grained control. Temperature is applied first to reshape the logits distribution, then top-p truncation is applied to the resulting probabilities. A typical production configuration uses:
- Temperature = 0.7 to 0.9 for creative writing
- Top-p = 0.9 to 0.95 for balanced output
- Temperature = 0.2 to 0.5 with top-p = 0.9 for factual, grounded generation
The interplay allows practitioners to independently control distribution sharpness and candidate pool size.
Comparison with Top-k Sampling
Top-p addresses a fundamental limitation of top-k: fixed candidate counts ignore distribution shape. Consider two scenarios:
- Peaked distribution: Top-k=40 may include tokens with near-zero probability, introducing noise
- Flat distribution: Top-k=40 may exclude viable candidates that collectively represent significant probability mass
Top-p solves both cases by using the probability mass itself as the cutoff criterion. However, many production systems combine both methods, applying top-k truncation first to limit the maximum pool size, then top-p to further refine based on confidence.
Origin and Adoption
Top-p sampling was introduced by Ari Holtzman et al. in 2019 in the paper 'The Curious Case of Neural Text Degeneration' as a solution to the repetitive, degenerate text produced by maximization-based decoding methods like beam search. It demonstrated that sampling from the dynamic nucleus produces text that is both more diverse and more coherent than likelihood-maximizing approaches. The technique has since become a standard default in major frameworks including Hugging Face Transformers, OpenAI's API, and Anthropic's Claude.
Top-p vs. Other Decoding Strategies
A technical comparison of Top-p (Nucleus) Sampling against Temperature Sampling, Beam Search, and Top-k Sampling across key generation control dimensions.
| Feature | Top-p (Nucleus) | Temperature | Beam Search | Top-k |
|---|---|---|---|---|
Selection Mechanism | Dynamic cumulative probability threshold | Logit scaling before softmax | Fixed-width hypothesis beam | Fixed-size candidate pool |
Vocabulary Adaptability | Adapts to confidence distribution | Uniform scaling, no adaptation | No adaptation | Static k, no adaptation |
Output Diversity | High, context-sensitive | Controllable via parameter | Low, tends toward repetition | Moderate, fixed ceiling |
Degeneracy Risk | Low | High at extreme values | Moderate | High with small k |
Computational Overhead | Sorting + cumulative sum | Negligible | O(beam_width * vocab_size) | Sorting only |
Deterministic Output | ||||
Handles Flat Distributions | ||||
Typical p/k Value | 0.9–0.95 | 0.7–1.0 | 4–10 beams | 40–50 |
Frequently Asked Questions
Clear, technical answers to the most common questions about nucleus sampling, its mechanics, and its role in controlling text generation quality.
Top-p sampling, also known as nucleus sampling, is a decoding strategy for language models that dynamically selects the smallest set of tokens whose cumulative probability mass exceeds a threshold p. Instead of sampling from a fixed number of top tokens (top-k), nucleus sampling adapts the candidate pool size based on the model's confidence distribution at each step. The algorithm sorts predicted tokens by descending probability, then iteratively adds them to the 'nucleus' until the sum of their probabilities reaches p. Sampling then occurs only from this dynamically sized nucleus, effectively truncating the unreliable tail of the distribution while preserving diversity when the model is uncertain.
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
Top-p sampling is part of a broader family of decoding strategies that control the randomness and quality of text generation. Understanding these related concepts is essential for fine-tuning model output.
Temperature Sampling
A hyperparameter that controls the randomness of predictions by scaling the logits before the softmax function. Unlike top-p, which truncates the distribution, temperature reshapes it.
- T → 0: The distribution sharpens, making the model nearly deterministic (greedy).
- T = 1: The original learned distribution is used.
- T → ∞: The distribution flattens, approaching a uniform random selection.
Temperature is often used in conjunction with top-p to first reshape the probability landscape and then sample from the nucleus.
Top-k Sampling
A predecessor to top-p that restricts sampling to the k most likely next tokens at each step, regardless of the shape of the probability distribution.
- Fixed Cutoff: If k=50, exactly 50 tokens are considered, whether they represent 99% or 10% of the probability mass.
- Rigidity Problem: A flat distribution may need many tokens to cover the nucleus, while a peaked distribution may need very few. Top-k cannot adapt to this dynamic range.
Top-p was designed to solve this rigidity by using a dynamic probability threshold instead of a fixed token count.
Beam Search Decoding
A deterministic heuristic that maintains a fixed number (beam width) of the most probable partial sequences at each step to find a near-optimal output.
- Objective: Maximize the overall sequence probability, not just the next token.
- Use Case: Best for tasks with a clear, single correct answer like machine translation or speech recognition.
- Drawback: In open-ended generation, beam search often produces bland, repetitive, and generic text because it strictly follows high-probability paths.
Top-p sampling is preferred for creative tasks where diversity is valued over strict probability maximization.
Greedy Decoding
The simplest decoding strategy: at each step, the model selects the single token with the highest probability.
- Mechanism: Equivalent to temperature sampling with T → 0 or top-k with k=1.
- Result: Purely deterministic output. The same input always produces the same output.
- Failure Mode: Greedy decoding often gets trapped in repetitive loops because it cannot backtrack from a locally optimal but globally poor choice.
Top-p introduces controlled randomness to escape these loops, enabling more natural and varied text generation.
Contrastive Decoding
A newer technique that exploits the difference between a large expert model and a smaller amateur model to improve generation quality.
- Mechanism: Rewards tokens that the expert model finds much more likely than the amateur model, filtering out common but uninteresting choices.
- Benefit: Produces more coherent and non-generic text without sacrificing fluency.
Like top-p, contrastive decoding is a method for navigating the probability distribution to avoid degenerate outputs, but it uses a relative signal between two models rather than an absolute probability threshold.
Repetition Penalty
A post-hoc adjustment applied during generation to penalize tokens that have already appeared in the recent context, preventing degenerative loops.
- Mechanism: Scales down the logits of previously generated tokens by a factor (typically 1.0-1.2) before sampling.
- Synergy with Top-p: Top-p truncates the tail of the distribution, but repetition penalty actively reshapes it to discourage redundancy.
These two techniques are frequently combined in production inference pipelines to achieve both diversity (via top-p) and non-repetitiveness (via penalty).

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