# What Is Top-P (Nucleus) Sampling?

> How top-p, or nucleus sampling, lets a model choose from a shortlist that grows and shrinks with its confidence, explained for your AI interview.

**In short:** Top-p, also called nucleus sampling, lets a model pick its next token only from the smallest group of likely candidates whose chances add up to p, such as 0.9. The group grows when the model is unsure and shrinks when it is sure.

AI and LLM interview question Q012, LLM fundamentals. Beginner, very common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/what-is-top-p-nucleus-sampling

## Say it in 30 seconds

Top-p, or nucleus sampling, is a setting that controls which words a model may pick. The model ranks its candidates from most to least likely, keeps the top ones until their chances add up to p, and picks only from those. If p is 0.9, the shortlist is the smallest group that covers 90 percent of the chances. Because the group grows and shrinks, it is more flexible than a fixed count. It narrows the choice, but it can't check whether the answer is true.

## Say it in 2 minutes

A language model writes one token at a time, and before each one it gives every possible token a chance of being picked. Top-p is a rule about which tokens may win. The model sorts the candidates from most to least likely, adds their chances up, and stops once the total reaches p. The tokens it kept form the nucleus. It scales their chances to add up to one again, then picks one at random.

Here is a case from a bank. A support bot is finishing a sentence about a late payment fee. Suppose the top choice is the number 35 with a 46 percent chance, and the rest is spread over 25, 45, 50, 250 and 0. With top-p at 0.9, the nucleus is 35, 25, 45 and 50, so 250 and 0 are cut. Top-k, by contrast, keeps a fixed number of candidates whatever the chances look like. The hard part is that 50 is still allowed, so a wrong fee can still come out.

So top-p does not check facts. It only trims the rare tail. The fix sits in code: look the fee up from the policy table, and let the model word the sentence around it. Top-p is a tuning knob, never the only safeguard.

On settings, OpenAI's guidance is to change top-p or temperature, not both. A lower temperature makes output more focused. I would test the bot on real past chats and check every fee it quotes before I touched either setting.

## What is top-p (nucleus) sampling, in plain words?

A language model writes text in small pieces called tokens. Before each one, it gives every possible token a chance of being picked. Sampling means picking one at random, with those chances as weights. Top-p is a rule for which tokens may be picked at all.

Think of a triage nurse listing likely causes for a chest pain. She writes the most likely causes first and stops once her list covers most of the cases she has seen. She does not spend time on the rare ones. Top-p works the same way with words.

For the model, the list is the nucleus, and p is how much of the total chance it must cover. A support bot writing a late fee might have 35 as its top choice, with a long tail of unlikely numbers. Top-p keeps the likely numbers and drops the tail: the long list of unlikely ones.

- **Token:** A small piece of text, such as a word or part of one, that the model reads and writes.
- **Chance:** How likely the model thinks each token is to come next. Also called probability.
- **Nucleus:** The shortlist of tokens that top-p keeps.
- **Temperature:** A setting that sharpens or flattens all the chances before a token is picked.

## How does top-p decide how many tokens to keep?

Top-p works in four steps. The chances are ranked, the top ones are added up, the total is cut at p, and the kept chances are scaled before one is picked. The number of tokens kept is not fixed in advance. It comes from the chances themselves.

1. **Rank the candidates:** Sort every possible next token from most to least likely.
2. **Add up the chances:** Walk down the list, adding each chance to a running total.
3. **Stop at p:** Stop once the total reaches p. The tokens kept so far form the nucleus.
4. **Scale and pick:** Scale the kept chances to add up to one, then pick one token from them.

*Diagram, How top-p picks the shortlist: The bank bot's candidates are ranked, and top-p keeps the top four, which add up to 93 percent. The 250 and the 0 are cut and can never be picked. One of the four is then chosen at random, by its chance.*
1. The model's ranked list goes in, most likely first.
2. Tokens past the cut-off are left out, so they can't be picked.
3. One token is picked at random from the kept ones, by their chances.

- **Model is sure: One strong choice.** One token has a 92 percent chance. At p 0.9 the nucleus is that single token, so nothing else can win.
- **Model is unsure: Many close choices.** Five tokens at 30, 25, 20, 12 and 8 percent. At p 0.9 the nucleus needs all five to reach the total.

Here is the same rule in plain Python, with the bank's made-up chances. It prints the nucleus at two settings. Nothing in it is random, so you get the same output on every run.

```python
# A bank's support bot is finishing a sentence about a late fee. The chances are made up.
OPTIONS = [("35", 0.46), ("25", 0.27), ("45", 0.12), ("50", 0.08), ("250", 0.04), ("0", 0.03)]

def top_p_pool(options, p):
    # Keep the most likely tokens until their chances add up to p.
    pool, total = [], 0.0
    for token, chance in sorted(options, key=lambda o: o[1], reverse=True):
        pool.append((token, chance))
        total += chance
        if total >= p:
            break
    # Scale the kept chances so they add up to 1 again.
    kept = sum(chance for _, chance in pool)
    return [(token, round(chance / kept, 2)) for token, chance in pool]

for p in (0.5, 0.9):
    print("top_p", p, top_p_pool(OPTIONS, p))
kept = [token for token, _ in top_p_pool(OPTIONS, 0.9)]
print("cut at 0.9:", [token for token, _ in OPTIONS if token not in kept])
```

Output:

```text
top_p 0.5 [('35', 0.63), ('25', 0.37)]
top_p 0.9 [('35', 0.49), ('25', 0.29), ('45', 0.13), ('50', 0.09)]
cut at 0.9: ['250', '0']
```

At 0.5 only two tokens survive. At 0.9 four do, and 250 and 0 are cut. The tail can never be picked at 0.9, but 50 can, so a wrong fee can still get through.

## How is top-p different from top-k and temperature?

- **Top-k: A fixed count.** Keeps a set number of tokens, chosen in advance, whatever the chances look like.
- **Top-p: A total of chances.** Keeps as many tokens as it takes to reach p, so the count moves with the model's confidence.
- **Temperature: Reshapes the chances.** Lower values sharpen all the chances, higher values flatten them, so rare tokens get more or less room.

> "An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass." (OpenAI API reference)
>
> "the nucleus, a small subset of the vocabulary that tends to range between one and a thousand candidates" (Holtzman et al., 2019)

Top-p comes from a 2019 arXiv paper by Ari Holtzman and four co-authors. Its point was that plain sampling from the full chances gave incoherent text, because the unreliable tail of unlikely tokens kept getting picked. Top-p cuts that tail.

> **Tip:** Asked what top-p is for, say it cuts the unlikely tail and leaves the rest to chance. Then say what it does not do: it does not check facts.

OpenAI's guidance is to change one of the two settings, not both, so pick either temperature or top-p for your bot and tune that one.

### How would you set top-p for a bank's fee bot?

Start by saying what must be exact. Fees, dates and amounts should come from code or a policy table, never from the sampler. For the wording around them, a top-p such as 0.9 keeps the sentence natural while cutting the rare tail.

Then test it. Run the bot on real past chats and check every fee it quotes against the policy. The check, not the setting, is what proves the fee is right.

> **Tip:** Don't promise that top-p stops wrong fees. Say the fee comes from the table, and top-p only shapes the wording.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] A plain definition: keep the smallest set of likely tokens whose chances add up to p.
- [ ] How it differs from top-k: the count moves with the model's confidence.
- [ ] What the value does: 0.9 cuts the tail. At the default of 1, nothing is cut.
- [ ] What it cannot do: check facts, or guarantee the same answer every time.
- [ ] The advice: change top-p or temperature, not both, as OpenAI recommends.
- [ ] A real case, such as a fee bot, and the fix in code.

**Common traps**

- Trap: "Top-p is the same as top-k." Better: Top-k keeps a fixed count. Top-p keeps as many tokens as it takes to reach p, so the count moves.
- Trap: "A low top-p makes the answer correct." Better: It narrows the choice. It can't check facts, so a wrong number can still be picked.
- Trap: "Set top-p to zero for facts." Better: Facts come from code and your data. Sampling settings only shape the wording.

## Can you spot the fix?

**Spot the fix:** A fee bot must always quote the policy fee exactly. Which change is the strongest fix?

A. Set top-p to 0.1 and hope the top number wins.
B. Look the fee up from the policy table in code, and let the model word the sentence around it.
C. Raise temperature so the bot sounds more natural.
D. Add a line to the system prompt asking it to quote the fee correctly.

**Answer:** B. The number comes from code, so the model can't invent it. Top-p only trims the choice, and nothing checks the number against the policy, so a top choice can still be wrong.

**Quick check:** A claims-triage agent drafts settlement letters. Which change cuts the rarest word choices?

A. Lower top-p from its default of 1 to 0.9
B. Raise temperature to 1.8
C. Add more examples to the system prompt
D. Switch to a larger model

**Answer:** A. Top-p cuts the least likely candidates from the shortlist. Higher temperature flattens the chances, so rare words get picked more often. A longer prompt or a bigger model does not set the cut-off.

## Can you answer these from memory?

**Flash cards**

- **What is top-p?** Sampling only from the smallest set of likely tokens whose chances add up to p.
- **Top-p vs top-k?** Top-p keeps as many tokens as it takes to reach p. Top-k keeps a fixed count.
- **What does top-p 1 do?** At the default of 1, nothing is cut. Every token stays in the shortlist.
- **Does top-p make output true?** No. It narrows the choice. Facts come from code and your data.
- **Who introduced it?** Holtzman and four co-authors, in "The Curious Case of Neural Text Degeneration" (2019).
- **Top-p or temperature?** OpenAI advises changing one of them, not both.

## Likely follow-up questions

- Q010 What does temperature control? https://designervenkat.online/interview/ai/what-does-temperature-control
- Q011 What is top-k sampling? https://designervenkat.online/interview/ai/what-is-top-k-sampling
- Q013 Greedy vs beam search vs sampling? https://designervenkat.online/interview/ai/greedy-vs-beam-search-vs-sampling
- Q014 Why can one prompt give different answers? https://designervenkat.online/interview/ai/why-can-one-prompt-give-different-answers
- Q022 What are logits, and what does softmax do? https://designervenkat.online/interview/ai/what-are-logits-and-what-does-softmax-do

## Learn it in depth

- [Sampling Parameters](https://designervenkat.online/learn/ai-engineering/sampling-parameters)
