liveBook · Manning

Top-p filtering

As explained in Generative AI in Action

Nucleus sampling is a text-generation technique that samples from the smallest dynamically selected set of tokens whose cumulative probability exceeds a specified threshold.

Top-p filtering, also called nucleus sampling, controls generation randomness by selecting the smallest group of likely next tokens whose cumulative probability reaches a configured threshold. The group changes for each prediction, so the technique adapts to the model’s probability distribution. section 2.8.5 section 3.2.5

Use the threshold to shape the balance between consistency and variety:

  • Set top_p to a lower value to consider fewer tokens, producing more consistent and less creative text. section 3.2.5
  • Set top_p to a higher value to allow more token choices, increasing creative variation while also increasing errors and randomness. section 3.2.5
  • Change either temperature or top_p for a generation configuration rather than adjusting both. section 3.2.5

Filtering the probability tail

With top_p set to 0.9, generation samples from tokens comprising 90% of the probability distribution and excludes the remaining 10%, which may contain highly random choices and nonsensical hallucinations. A typical starting range is 0.7 to 0.95, adjusted for the use case. section 3.2.5

Figure 2.11 Example showing how top-p works
figure

Visualizes how the selected nucleus changes as top-p filtering determines which tokens remain eligible. section 2.8.5

How Generative AI in Action covers it

How deep it goes
Explains cumulative-probability selection, changing group size, trade-offs, and configuration guidance without mathematical derivation.
Examples
Uses a top_p value of 0.9 and contrasts lower and higher thresholds through token-choice and output-quality effects.
What you can do after
Apply it via a language-model API and tune top_p for more predictable or more varied generated text.
How it connects
Connects nucleus sampling with temperature, language model APIs, probability distributions, and hallucinations.

Also explained in

Compare how 12 books explain top-p filtering →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Generative AI in Action. The section links point to the parts of the book it draws on.