Inferensys

Glossary

Nucleus Sampling (Top-p)

Nucleus sampling, or top-p sampling, is a text generation decoding method that dynamically selects the smallest set of the most probable next tokens whose cumulative probability mass exceeds a threshold p, then samples from this set.
Engineer reviewing vector database search results on laptop, embeddings visualization on screen, home office coding session.
DECODING METHOD

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.

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.

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.

DECODING METHOD COMPARISON

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 / MetricNucleus 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

DECODING METHOD

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.

01

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.

02

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.
03

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.
04

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.
05

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.

06

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.
NUCLEUS SAMPLING (TOP-P)

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.

Prasad Kumkar

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.