Top-p (nucleus) sampling is a text generation algorithm that, at each step, selects the next token from the smallest set of most probable candidates whose cumulative probability mass exceeds a predefined threshold p (e.g., 0.9). Unlike fixed-size top-k sampling, it dynamically adjusts the candidate pool size based on the model's confidence distribution for that specific step. This method effectively trims the long tail of low-probability tokens, focusing generation on the model's most confident predictions.
Glossary
Top-p (Nucleus) Sampling

What is Top-p (Nucleus) Sampling?
Top-p (nucleus) sampling is a probabilistic decoding method for large language models that dynamically selects tokens from a variable-sized set of the most probable options.
The primary engineering benefit is a superior balance between coherence and diversity compared to greedy or pure random sampling. By excluding highly improbable tokens, it reduces nonsensical output, while the dynamic candidate pool allows for creative variation when the probability distribution is flat. It is commonly used in conjunction with the temperature parameter for fine-grained control. This makes it a standard technique for production applications like chatbots and creative writing assistants where predictable yet non-repetitive text is required.
Core Characteristics of Top-p Sampling
Top-p (nucleus) sampling is a probabilistic decoding method for large language models that dynamically selects tokens from a variable-sized set whose cumulative probability mass meets a threshold, balancing coherence and diversity.
Dynamic Vocabulary Selection
Unlike top-k sampling which uses a fixed number of tokens, top-p dynamically adjusts the candidate set size 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 set of tokens where the sum of their probabilities first exceeds the threshold p (e.g., 0.9). This means the candidate pool can be large for uncertain predictions and very small for highly confident ones.
Probability Mass Threshold (p)
The core parameter p (between 0 and 1) defines the nucleus or cumulative probability mass to sample from. Common values are between 0.7 and 0.95.
- High p (e.g., 0.95): Includes more tokens, leading to more diverse and potentially creative outputs, but with a higher risk of incoherence.
- Low p (e.g., 0.7): Restricts sampling to a smaller set of highly probable tokens, producing more predictable and coherent text, but with less variety. Setting p=1.0 is equivalent to sampling from the full vocabulary, while very low values approach greedy decoding.
Combination with Temperature
Top-p is almost always used in conjunction with the temperature parameter. The standard workflow is:
- Apply temperature scaling to the logits to control sharpness of the probability distribution.
- Apply softmax to get the final probabilities.
- Apply top-p filtering to select the nucleus of viable tokens.
- Renormalize the probabilities within this nucleus.
- Sample from this renormalized distribution. This combination allows fine-grained control: temperature adjusts the distribution's entropy, while top-p provides an intelligent, adaptive cutoff.
Contrast with Top-k Sampling
Top-k sampling selects from the k most likely tokens at every step, regardless of their probability mass.
Key Contrasts:
- Fixed vs. Dynamic Set Size: Top-k is static; top-p adapts to the prediction's certainty.
- Handling of Flat Distributions: In low-confidence scenarios, top-k might include many low-probability tokens, increasing randomness. Top-p excludes long tails of negligible probability.
- Handling of Sharp Distributions: When the model is very confident (one token has ~0.99 probability), top-p will select only that token, acting like greedy decoding. Top-k would still sample from
ktokens, adding unnecessary noise. Top-p is generally considered more robust across different tasks.
Primary Use Case: Creative Text Generation
Top-p is the default decoding strategy in most APIs (e.g., OpenAI's ChatGPT) for open-ended generation tasks because it effectively balances quality and diversity.
Ideal applications include:
- Creative writing and story generation.
- Conversational AI where varied, non-repetitive responses are desired.
- Brainstorming and idea generation. It reduces the likelihood of degenerate, repetitive loops (a common failure mode of pure random sampling) while avoiding the excessive determinism of greedy or beam search.
Limitations and Considerations
Not Ideal for Deterministic Tasks: For tasks requiring exact, reproducible outputs (e.g., code generation, data extraction), beam search or greedy decoding with a very low temperature and p-value is preferred.
Parameter Sensitivity: The quality of output can be sensitive to the chosen p value, requiring task-specific tuning.
Computational Overhead: Requires sorting probabilities and computing a cumulative sum each step, adding slight overhead compared to top-k, though this is negligible for most applications.
Does Not Guarantee Factuality: Like all decoding methods, it only controls the selection mechanism from the model's distribution; it does not address underlying model hallucinations or inaccuracies.
Top-p vs. Top-k vs. Greedy Decoding: A Comparison
A technical comparison of core algorithms for selecting the next token during autoregressive generation in large language models, focusing on their mechanisms and trade-offs between determinism, diversity, and coherence.
| Feature / Mechanism | Greedy Decoding | Top-k Sampling | Top-p (Nucleus) Sampling |
|---|---|---|---|
Core Selection Principle | Always chooses the single token with the highest predicted probability. | Samples from the k tokens with the highest probabilities. | Dynamically samples from the smallest set of tokens whose cumulative probability ≥ p. |
Determinism | |||
Output Diversity | |||
Primary Control Parameter | N/A (inherently deterministic) | k (integer, e.g., 50) | p (probability threshold, e.g., 0.9) |
Dynamic Vocabulary Size | |||
Common Artifacts / Risks | RepetitionGeneric phrases | Incoherence from low-probability tailsFixed k can be suboptimal for varying distributions | High coherenceBalanced creativity |
Typical Use Case | Machine translation, code generation where deterministic output is critical. | General text generation before the advent of top-p. | Modern chat and creative writing applications; often used with a temperature parameter. |
Integration with Temperature |
Top-p Sampling in Major LLM Platforms and APIs
Top-p (nucleus) sampling is a core decoding parameter for controlling text generation diversity. This guide details its implementation across leading platforms.
Frequently Asked Questions
Top-p (nucleus) sampling is a core decoding parameter for controlling the creativity and coherence of large language model outputs. These questions address its technical mechanics, practical use, and relationship to other sampling methods.
Top-p (nucleus) sampling is a probabilistic decoding strategy for large language models (LLMs) that dynamically selects from the smallest set of most probable next tokens whose cumulative probability mass exceeds a predefined threshold p (e.g., 0.9), then randomly samples from that set.
Unlike top-k sampling, which selects a fixed number (k) of top tokens regardless of their probability distribution, top-p adapts to the model's confidence on a per-token basis. When the model is highly certain (a steep probability distribution), the nucleus is small, promoting coherence. When the model is uncertain (a flatter distribution), the nucleus expands, allowing for more diverse and creative outputs. This dynamic adjustment makes it a preferred method for balancing focused and varied text generation.
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 one of several key parameters and strategies used to control the output of a large language model. These related concepts define the mechanics of how a model selects the next token.
Temperature
Temperature is a hyperparameter that controls the randomness of a model's outputs by scaling the logits (raw prediction scores) before applying the softmax function.
- Low temperature (e.g., 0.1): Makes the probability distribution sharper. The model becomes more deterministic, consistently choosing the most likely tokens. This is ideal for tasks requiring factual accuracy and consistency, like code generation.
- High temperature (e.g., 1.0): Flattens the probability distribution. The model becomes more creative and diverse in its outputs, useful for brainstorming or creative writing.
- Interaction with Top-p: Temperature is applied before top-p sampling. A high temperature can create a flatter distribution, making top-p's selection of the nucleus more diverse.
Top-k Sampling
Top-k sampling is a decoding strategy that restricts the model's next-token selection to the k most probable tokens from its vocabulary.
- Mechanism: At each generation step, only the top
ktokens by probability are considered. The probability mass is redistributed among thesektokens (via softmax), and one is sampled. - Comparison to Top-p: Top-k uses a fixed number (
k), while top-p uses a dynamic cumulative probability (p). Top-k can be problematic because the appropriatekcan vary wildly depending on the steepness of the probability distribution at each step. Top-p adapts to this variability naturally. - Use Case: Often used in earlier models (e.g., GPT-2). It's simpler but less adaptive than top-p.
Greedy Decoding
Greedy decoding is the simplest decoding strategy where the model always selects the single most probable token at every generation step.
- Mechanism: No sampling is involved. The algorithm is deterministic:
next_token = argmax(P(token | context)). - Limitations: It often leads to repetitive, generic, and sub-optimal text sequences because it doesn't consider that a slightly less probable token now might lead to a much better overall sequence later (a problem known as search error).
- Contrast: Top-p and other sampling methods introduce controlled randomness to escape these local optima, producing more natural and higher-quality text. Greedy decoding is used when absolute determinism is required.
Beam Search
Beam search is a deterministic decoding algorithm that explores multiple potential sequences in parallel to find a high-probability overall output.
- Mechanism: It maintains
b(beam width) most promising sequences at each step. It expands each, keeps the topbsequences by cumulative probability, and repeats. This approximates a broader search for the optimal sequence. - Use Case: Highly effective for tasks where coherence and likelihood are paramount, such as machine translation or text summarization, where there is often a single "best" answer.
- Contrast with Sampling: Beam search is deterministic and aims to maximize sequence probability. Sampling methods (top-p, top-k) are stochastic and aim for diversity and naturalness, which is often better for open-ended generation like dialogue or story writing.
Logits
Logits are the raw, unnormalized output scores generated by a language model's final layer before being converted into a probability distribution.
- Role in Decoding: The model produces a logit for every token in its vocabulary. These values represent the model's relative preference for each token given the context.
- Transformation to Probabilities: The softmax function is applied to the logits to convert them into a proper probability distribution (all values sum to 1).
- Parameter Interaction: Decoding parameters like temperature and top-p operate directly on these logits or the resulting probabilities. Temperature scales the logits before softmax. Top-p is applied to the sorted probabilities after softmax.
Repetition Penalty
Repetition penalty (or frequency/presence penalty) is a technique used to discourage a model from generating repetitive text by artificially reducing the probability of tokens that have already appeared in the recent context or output.
- Mechanism: The logits of tokens that are already in the output sequence are manually decreased by a penalty factor. This makes the model less likely to sample them again immediately.
- Synergy with Top-p: While top-p controls diversity via probability mass, repetition penalty controls diversity via token history. They are often used together. Top-p ensures a dynamic candidate set, while repetition penalty actively discourages re-selection from that set.
- Application: Critical for long-form generation to avoid loops or excessive reuse of phrases. It's a common parameter in inference APIs alongside
temperatureandtop_p.

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