Articles

What is top-p sampling? How nucleus sampling affects LLM responses

24 November 2026Braintrust Team17 min
TL;DR: Top-p sampling

Top-p sampling, also called nucleus sampling, limits each next-token choice to the most probable tokens whose combined probability reaches a threshold, p. The number of eligible tokens changes at each step, so lowering top-p generally reduces response diversity without guaranteeing factual accuracy.

This guide explains how the cutoff works, how top-p interacts with temperature and top-k, and which provider restrictions affect its use. It also covers how to test candidate thresholds on representative inputs and distinguish repeatable improvements from normal sampling variation.

Braintrust evaluates candidate thresholds against a shared dataset and retains repeated trials to compare against a production baseline. Product and engineering reviewers can use the same results to assess whether a sampling change meets the application's release requirements.


Top-p sampling in LLM decoding

A language model generates text one token at a time. At each step, the model scores every token in its vocabulary, converts the scores into a probability distribution, and uses a decoding method to select the next token. Greedy decoding takes the most probable token. Sampling draws in proportion to each token's probability, so lower-probability candidates remain possible.

Top-p is a truncation step that runs before sampling. The sampler sorts candidate tokens by probability and keeps the smallest group whose cumulative probability reaches or exceeds p. A top_p of 0.1, the example used in OpenAI's API reference, retains enough top-ranked tokens to cover at least 10% of the probability mass, and if the leading token alone carries 10% or more, the nucleus holds just that one token.

Ari Holtzman and colleagues introduced nucleus sampling in their 2019 paper, The Curious Case of Neural Text Degeneration. Their experiments showed that decoding methods favoring the most likely sequence could produce repetitive text in open-ended generation. Nucleus sampling preserved variation by sampling from a changing set of likely continuations and excluding the low-probability tail.

Top-p affects generation only when sampling is active. Greedy decoding always selects the highest-probability token, which remains eligible at every top-p threshold, so changing top-p doesn't affect the next-token choice.

How nucleus sampling works

Nucleus sampling ranks candidates, applies the cumulative probability cutoff, and rescales the surviving probabilities at every generation step. The meeting example below shows why the retained probability can exceed the configured threshold.

Cumulative probability and the nucleus cutoff

The nucleus is the smallest set of top-ranked tokens whose combined probability reaches p or higher. Tokens outside the nucleus become ineligible for the current sampling step.

Suppose a model completing "The meeting was moved to" assigns the following illustrative probabilities to six candidate tokens, with top_p set to 0.75. The example treats each displayed word as one token and uses a simplified distribution totaling 100%.

Candidate tokenProbabilityCumulative probabilityIn the nucleus at top_p=0.75
Friday40%40%Yes
Monday25%65%Yes
tomorrow15%80%Yes
next10%90%No
the6%96%No
noon4%100%No

After "Monday," the running total is 65%, which falls short of 75%. Adding "tomorrow" brings the total to 80%, so the nucleus contains three tokens. The remaining candidates are excluded for this step.

Why the candidate pool changes size at each step

The threshold sets how much probability the nucleus must cover, and the distribution determines how many tokens it needs. Two steps in the same response can therefore produce candidate pools of different sizes under the same setting.

Confident steps: After "The capital of France is," a model might assign 92% probability to "Paris." At top_p=0.9, Paris covers the threshold alone, leaving a nucleus of one token.

Uncertain steps: After "My favorite fruit is," probability might spread across many fruit names, with no single candidate above 16%. In the illustrative diagram, reaching 90% requires ten tokens, with a combined probability of 93%.

Two next-token distributions at top_p = 0.9: a confident step where Paris at 92% forms a one-token nucleus, and an uncertain step across fruit names where ten tokens are needed to reach 93% cumulative probability

The changing candidate count separates top-p from top-k, which retains a fixed number of top-ranked tokens. Top-p narrows the pool when probability concentrates on a few continuations and expands it when it spreads across many candidates.

Renormalization before sampling

When the nucleus contains less than the full probability mass, the retained probabilities must be rescaled to sum to 1. Each token keeps its weight relative to the other surviving candidates. In the meeting example, dividing the retained probabilities by 0.80 produces the sampling distribution.

Token in the nucleusOriginal probabilityRenormalized probability
Friday40%50%
Monday25%31.25%
tomorrow15%18.75%

Top-p values and LLM response diversity

Adjusting top-p determines which continuations remain eligible at each step. Selecting a different token shifts the context for later predictions, so a small difference early in generation can alter the wording, structure, or length of the complete response.

Low top-p values

A lower threshold retains fewer candidates from the same distribution and often produces more consistent wording across repeated runs. When the highest-probability token alone reaches the threshold, the nucleus contains one candidate and the next-token choice matches greedy decoding.

Extraction and classification often require consistent values or labels, so repeatability matters. A lower top-p is worth testing when inconsistent outputs cause downstream failures, but the evaluation must still check correctness and format validity. Sampling controls cannot guarantee a correct label or schema-compliant output.

Very low thresholds can also make long responses repetitive. Holtzman and colleagues observed repetition in likelihood-focused decoding, and a top-p setting that repeatedly reduces the nucleus to one token can approach similar behavior. The effect depends on the model, prompt, and probability distribution at each step.

High top-p values

A higher threshold admits additional, lower-probability candidates that a smaller nucleus would exclude. Brainstorming, creative writing, and synthetic data generation may benefit from the added variety, as long as the outputs still meet relevance and quality requirements.

At top_p=1, nucleus filtering removes no candidates. Temperature, top-k, and any other active constraints still affect the distribution available for sampling. A higher top-p therefore permits broader sampling, but the additional candidates are not necessarily diverse or useful.

Token probability vs. factual accuracy

A token's probability reflects how likely a continuation is under the model and the supplied context. A model can assign high probability to an incorrect answer, particularly when the context lacks the evidence needed to respond accurately.

Top-p filters by probability, so a confidently wrong continuation can survive a low threshold and recur consistently. Lowering top-p may improve or worsen accuracy on a particular task, and only measurement settles which. Hallucination evaluations, which assess unsupported claims directly alongside checks on retrieval quality and grounding, test accuracy in ways sampling settings cannot.

Top-p vs. temperature vs. top-k

Temperature, top-p, and top-k affect sampling through different mechanisms. Temperature redistributes probability across candidates, top-p retains a cumulative share of probability, and top-k retains a fixed number of candidates.

ControlWhat it changesHow the candidate pool behavesEffect of a lower value
TemperatureRelative probabilities across eligible tokensDoes not itself remove tokensConcentrates probability on the highest-scoring candidates
Top-pCumulative probability retained for samplingCandidate count varies with the distributionRetains a smaller or equal set from the same distribution
Top-kNumber of top-ranked tokens retainedKeeps a fixed count, subject to available candidatesRetains fewer candidates

Temperature

Temperature scales the model's raw scores before they become probabilities. Positive values below 1 concentrate probability on the highest-scoring tokens, and values above 1 flatten the distribution. When temperature is applied before top-p, changing temperature also changes how many tokens are needed to reach the nucleus threshold.

For example, concentrating probability on the leading candidates may let a smaller set cover 90% of the distribution. Spreading probability across additional candidates may require a larger nucleus at the same top_p=0.9 setting. The order of operations depends on the inference implementation, so interpret combined settings in the context of the library or API running the model.

Top-k sampling

Top-k retains the k most probable tokens, regardless of how probability is distributed among them. At a confident step, top_k=50 may retain many unlikely continuations alongside the leading candidate. At an uncertain step, the same count may exclude plausible continuations ranked below 50th place.

Combining top-p with other sampling parameters

When multiple filters are active, only candidates that survive every filter remain eligible. If top-k runs before top-p, top_k=50 first restricts the pool to 50 candidates. Top-p then applies its threshold to the probability distribution over the remaining tokens, potentially reducing the pool further.

Change one sampling control per comparison to isolate its effect. OpenAI recommends adjusting either top-p or temperature, and Anthropic's model parameter guidance on Amazon Bedrock gives the same recommendation. Some models and endpoints restrict which parameters may be supplied, so check which combinations an endpoint accepts before applying the general sampling theory.

Top-p support and defaults by LLM provider

Top-p support depends on the exact model, endpoint, API version, and sometimes the reasoning setting. As of November 2026, one model may accept a parameter that another rejects or ignores, so verify the request configuration before comparison.

ProviderTop-p supportConfiguration notes
OpenAI GPT-6.2Not supported. OpenAI's migration guidance says to omit top_p and temperature, and GPT-6.2 Astra and GPT-6.2 Sol reject a reasoning effort of none.Evaluate prompt instructions and supported reasoning-effort settings instead.
OpenAI GPT-6 and GPT-6.1Custom top_p requires reasoning effort none. GPT-6 Astra and GPT-6.1 Sol do not support none.GPT-6.1 Terra, GPT-6 Sol, and GPT-6 Luna support none.
Anthropic Claude APIAPI version 2026-10-21 rejects top_p at any value, including its default. Earlier API versions have model-specific restrictions.The Claude API and Amazon Bedrock have separate request contracts; verify the requirements for the endpoint in use.
Google GeminiNot supported on recent models. Custom top_p, temperature, and top_k values are ignored on Gemini 3.6 Flash and later, including Gemini 4 Argon.The values are ignored silently rather than rejected, so confirm the model before relying on one. For earlier models, check Google's token sampling parameter guidance.

Omitting top_p uses the model or endpoint's default, which may differ from explicitly sending 1. On an API version that rejects the parameter, sending a default value still sends the field and still returns an error, so remove the key from the request and from any saved prompt configuration. Braintrust documents this case for Claude sampling parameter errors, including how to clear a stored Top p value so framework or gateway defaults do not reintroduce it.

Choosing a top-p value for a specific task

A useful top-p value must improve the behavior the application requires under its actual model and prompt. A controlled evaluation establishes whether a candidate threshold offers a repeatable benefit over the current configuration.

  1. Confirm the model accepts and uses top-p. Check the exact model, endpoint, API version, and reasoning setting. If a parameter is rejected or ignored, you can't evaluate it as a sampling change. When top-p is unavailable, test a supported control in a separate comparison.
  2. Define the failure and acceptance criteria. Extraction may fail on incorrect fields, classification on wrong labels, and variant generation on repetitive or irrelevant responses. Select matching checks, such as exact match, schema validation, or an LLM-as-a-judge rubric, and specify which failures prevent release.
  3. Build a representative dataset. Include production inputs, known failures, and cases with several plausible continuations. Preserve the same dataset version across candidates so changes in test coverage do not confound the results.
  4. Change only top-p. Hold the model version, prompt, temperature, top-k, output limit, and scorers fixed. Compare the current setting with a small set of supported thresholds, and record both explicit values and effective defaults.
  5. Run repeated trials. Evaluate each input several times per configuration to measure output variation. Keep the judge model and rubric fixed as well, since nondeterministic scoring can contribute noise alongside the task's sampled output.
  6. Compare individual cases and task segments. An aggregate improvement can conceal new failures on important inputs. A case-level comparison reveals which inputs improved, regressed, or alternated between passing and failing across trials.
  7. Retest after model or API changes. An upgrade may change the probability distribution, the default settings, or whether top-p is supported. Re-establish the baseline before carrying a threshold into the new configuration.

Keep the current setting when repeated trials do not establish a meaningful improvement. Small differences need additional evidence, particularly when they affect release-critical cases. Three to five trials can be an initial check, but the number needed for a production decision depends on the observed variation and the consequences of failure.

Evaluating top-p settings in Braintrust

Braintrust preserves the evidence needed to approve a sampling change: the tested configuration, results for each input, and differences from the production baseline. Once the target model's top-p support is confirmed, the comparison can move from exploratory prompt checks to repeatable release requirements.

Step 1. Check candidate settings in a playground

Create a base prompt task with the current production configuration in a Braintrust playground, then add comparison tasks that change only top-p. Attach the same dataset and scorers to inspect response differences before selecting candidates for a full evaluation.

Braintrust playground with three prompt tasks sharing one prompt, a dataset selector open, and per-task ExactMatch scores beneath each output

Product and domain reviewers can test supported prompt parameters in the browser without editing the evaluation code. A playground suits quick exploration, and saving a selected run as an experiment preserves the results for later review. The production evaluation should use the same request settings and application behavior that will serve users.

Step 2. Save one experiment per threshold

Run each candidate against the same dataset version and save the tested top-p value alongside the model and generation parameters in experiment metadata. Reviewers can then identify the configuration behind each result and compare thresholds without relying on experiment names alone.

Braintrust experiments list with a score chart and an x-axis selector offering metadata fields including model, prompt, and temperature

Braintrust matches test cases by input by default. When inputs include changing values such as temporary references or timestamps, use a stable comparison key so each candidate is evaluated against the corresponding baseline case. Comparison rows showing a dash instead of a score are the signal that inputs are not matching.

Step 3. Measure consistency with repeated trials

Set trial_count in Python or trialCount in TypeScript to run each input multiple times. Braintrust aggregates matching inputs and retains the individual trial results, making inconsistent responses visible alongside average scores. Per-case trial counts concentrate additional runs on inputs that need closer measurement.

Begin with a small trial count and increase it when the candidate's apparent advantage is difficult to distinguish from normal variation. Each additional trial repeats the task and its scorers, so the trial budget should reflect the cost of the model calls and the confidence required for the release decision. Repeated trials should execute fresh task calls; response caching must not substitute the same generated answer for independent samples. When requests route through the Braintrust Gateway, set x-bt-use-cache to never, since the default auto mode caches requests that set temperature=0 or a seed.

Step 4. Review regressions before approving the change

Select the production configuration as the baseline and inspect score deltas and output differences for the matching inputs. Group trials by input to find cases that alternate between passing and failing, and review critical task segments separately from the overall average.

Braintrust experiment grouped by input, with each group header showing aggregate scores and duration above its individual trial rows

A candidate should meet the acceptance criteria defined before testing, including the required consistency on critical cases. Shared experiment records let product and engineering reviewers assess the same failures and agree on whether the observed benefit justifies changing production behavior.

Step 5. Enforce the approved requirements in CI

The Braintrust GitHub Action runs evaluations on pull requests and posts the resulting scores and metrics as a PR comment, which requires the pull-requests: write permission.

Posting results does not by itself block a merge. By default, bt eval returns a non-zero exit code only when an eval throws an exception, so a score that drops below the agreed requirement still exits successfully. To gate on quality, define a custom reporter whose reportRun function returns false when the score requirements are missed, then make the evaluation job a required repository check so the failing status blocks the merge.

The GitHub Actions evaluation pipeline covers baseline selection, repeated trials, and reporter-based score thresholds. Applying the agreed requirements to later configuration changes preserves the evidence behind the selected top-p value.

Braintrust's free Starter plan includes 10,000 scores and 1 GB of processed data per month, with 14-day retention. Repeated trials multiply the scores recorded per input, so size the trial budget against that monthly allowance.

Evaluate top-p settings with Braintrust for free.

FAQs about top-p sampling

What is top-p in LLMs?

Top-p sets the cumulative probability cutoff for candidates eligible to become the next token. For example, top_p=0.9 retains enough of the highest-probability candidates to cover at least 90% of the distribution, and the number retained can change with every generation step.

Is top-p the same as nucleus sampling?

Top-p is the threshold used by nucleus sampling, the method introduced by Holtzman and colleagues. API documentation often uses the terms interchangeably, and in practice the top-p value is the setting that decides how much probability the nucleus of eligible tokens must cover.

What is a good top-p value?

Start with the model's supported default and change it only when evaluations show a useful improvement on representative inputs. In Braintrust, that means running each candidate threshold against the same test cases and quality criteria and keeping the one that meets the application's requirements.

Should you adjust temperature and top-p together?

Adjust one parameter per experiment so the cause of any score change remains identifiable. After measuring their separate effects, test a combined configuration only when the model accepts both parameters and the interaction is relevant to the application's requirements.

What is the difference between top-p and top-k?

Top-p selects candidates by cumulative probability, and top-k selects them by rank count. As a result, top-p may retain one candidate at a confident step and many at an uncertain step; top-k uses the same configured count whenever enough eligible candidates are available.

Does a top-p of 1 remove all sampling restrictions?

A value of 1 removes the nucleus cutoff on models that accept the setting. Other controls, including top-k, temperature, and constrained decoding, can still affect generation, so top_p=1 alone doesn't describe the full sampling configuration.

Why do some models reject the top_p parameter?

Some models and API contracts use fixed sampling settings or restrict custom values to specific modes. Check the exact model and endpoint before sending top-p, since an unsupported field may trigger an error or be accepted without affecting generation.

Does lowering top-p reduce hallucinations?

Lowering top-p cannot guarantee factual answers because an incorrect continuation can still have high probability. To find out whether a candidate setting improves correctness on your test set, score responses against expected answers with Braintrust's Factuality scorer.

Share

Trace everything