# What Is Top-k Sampling?

> What top-k sampling is, how it picks the next word, why one fixed k can go wrong, and how to explain it in your AI interview.

**In short:** Top-k sampling keeps only the k most likely next tokens, rescales them, and picks one at random. It cannot make a fact true, a wide k can let a wrong word in, and a fixed k ignores how sure the model is.

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

## Say it in 30 seconds

Top-k sampling is a setting for how an AI model picks its next word. The model gives every possible next token a probability. Top-k keeps only the k most likely ones, rescales them, and draws one at random. With k set to 1, it always takes the top choice. A fixed k is the weak point, because it ignores whether the model is sure or unsure. Top-k cannot make a fact true, and a wide k can let a wrong word in, so the facts must come from our code.

## Say it in 2 minutes

A language model writes one token at a time. Before each one, it gives every token it knows a probability, from likely to very unlikely. Top-k sampling is the rule for what happens next. It keeps only the k most likely tokens, scales their probabilities so they add up to one, and draws one of them at random. With k set to 40, any word ranked 41st or lower never gets picked.

Think of a credit officer who shortlists the three best applicants out of forty, then draws one, where the strongest of the three have the best odds. The shortlist keeps the choice sensible, and the draw keeps it varied. With k set to 1 there is no draw at all. The model always takes the top choice, which is called greedy decoding.

The weak point is that k is fixed. If the model is almost sure of the next word, a big k lets in weak options. If the options are about equally good, a small k throws good ones away. Top-p sampling, the next question, is the usual alternative: it keeps the smallest set whose probabilities add up to a target.

In a claims assistant, a customer letter might say approved, processed or accepted. Top-k only sets which words can come out, so a wide k can let a wrong word in. The payout amount and the decision must come from the claims system in code, never from the model's guess. I would also check the sampling settings in the provider's current docs, because some newer Google models ignore custom top-k values.

## What is top-k sampling, in plain words?

A language model writes one token at a time. A token is a chunk of text, often a word or part of one. Before each token, the model gives every token it knows a probability, from very likely to very unlikely. Sampling is how it picks one of them.

Top-k sampling is a rule for that pick. It keeps only the k most likely tokens, scales their probabilities so they add up to 100%, and draws one of them at random. A credit officer might shortlist the three best applicants out of forty, then draw one, where the strongest of the three have the best odds. The shortlist keeps the choice sensible, and the draw keeps it varied.

- **Token:** A chunk of text the model reads and writes, often a word or part of a word.
- **Vocabulary:** Every token the model knows how to pick from.
- **Probability:** How likely the model thinks each next token is, from 0 to 100%.
- **Greedy decoding:** Always taking the single most likely token. Top-k with k of 1 does this.

Here is the case we use all the way through. A claims assistant writes a letter to a customer. The claim is already approved, because the claims system decided that. The model only chooses the wording.

## How does top-k pick the next token?

1. **Score every token:** The model gives each possible next token a probability.
2. **Keep the top k:** Sort by probability and drop everything after the first k.
3. **Rescale what is left:** Scale the kept probabilities so they add up to 100%.
4. **Draw one:** Pick one token at random from the kept set, by its share.

*Diagram, How top-k picks the next token: The model scores every token. Top-k keeps the first k in the sorted list, rescales them, and draws one. Only the draw is random; the cut is always the same size when there are at least k tokens.*
1. The scores are sorted, most likely first.
2. Everything past the first k is dropped.
3. The kept shares are rescaled to add up to 100%.
4. One token is drawn at random from what is left.

> "The model considers only the top k most probable tokens for the next token." (Google Cloud model reference)

## What does a worked example look like?

A claims assistant has just written 'Good news, your claim has been' and must pick the next word. Our code uses made-up probabilities: 'approved' 55%, 'processed' 15%, 'accepted' 10%, and five more words with smaller shares, including 'denied' at 3%. The code applies top-k at four settings and prints what is kept.

```python
# A claims assistant drafts a customer letter. The claim is already approved in code;
# the model only picks the wording, one token at a time. Made-up probabilities.
NEXT = {"approved": 0.55, "processed": 0.15, "accepted": 0.10, "settled": 0.06,
        "reviewed": 0.05, "delayed": 0.04, "denied": 0.03, "lost": 0.02}

def top_k(probs, k):
    # Keep the k most likely tokens, then rescale them so they add up to 1.
    kept = sorted(probs.items(), key=lambda item: item[1], reverse=True)[:k]
    total = sum(p for _, p in kept)
    return [(token, p / total) for token, p in kept]

for k in (1, 3, 6, 7):
    picks = top_k(NEXT, k)
    print(f"k={k}:", ", ".join(f"{t} {p:.3f}" for t, p in picks))
    print("  can pick 'denied':", any(t == "denied" for t, _ in picks))
```

Output:

```text
k=1: approved 1.000
  can pick 'denied': False
k=3: approved 0.688, processed 0.187, accepted 0.125
  can pick 'denied': False
k=6: approved 0.579, processed 0.158, accepted 0.105, settled 0.063, reviewed 0.053, delayed 0.042
  can pick 'denied': False
k=7: approved 0.561, processed 0.153, accepted 0.102, settled 0.061, reviewed 0.051, delayed 0.041, denied 0.031
  can pick 'denied': True
```

Read the output. At k = 1 the letter always says 'approved', which is greedy decoding. At k = 3 the rescaled shares are 0.688, 0.187 and 0.125, so the wording stays steady. At k = 7 the word 'denied' gets in at about 3%.

The lesson: a wider k lets rare, wrong words in. Keep k small where the words carry facts, and never let a sampled word carry the decision.

## Why is a fixed k a weak point?

The number k stays the same whatever the model is thinking. Amazon's Bedrock documentation says a lower value considers fewer candidates, regardless of how the probability is distributed. That is the flaw in a fixed cut.

> "Choose a lower value to consider fewer candidate tokens, regardless of how the probability is distributed across them." (Amazon Bedrock)
>
> "By sampling text from the dynamic nucleus of the probability distribution, which allows for diversity while effectively truncating the less reliable tail of the distribution" (Holtzman et al., 2019)

Holtzman and colleagues argued that a constant k is sub-optimal, and proposed a fix that changes the pool size at each step. Their paper calls it nucleus sampling, which is top-p, and the pool grows and shrinks with the shape of the distribution.

*Diagram, Why one fixed k can go wrong: Two kinds of next-word step, one fixed setting. On a peaked step the cut lets in weak options; on a flat step it throws away fair ones.*
1. On a peaked step, k = 3 keeps two weak tokens with the winner.
2. On a flat step, k = 3 drops three options that were all fair.
3. One setting is too loose in one case and too tight in the other.

> **Tip:** Asked about the weakness? Say the fixed k ignores how sure the model is, then name top-p as the next idea. Don't say top-k is broken: it is a simple rule that needs a sensible k.

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

- **Top-k: Keep k tokens.** A fixed count of the most likely tokens, whatever their shares are.
- **Top-p: Keep a share.** The smallest set whose probabilities add up to a target p, so its size changes from step to step.
- **Temperature: Control the randomness.** Controls how random the final pick is. Lower values give steadier, less varied wording.

Each setting changes the list of tokens in its own way, so check the docs for the library you use.

> **Tip:** Check the current docs before you tune top-k. Google's docs say that for Gemini 3.6 Flash and later models, custom values for temperature, topP and topK are ignored if set.

### How would you set top-k for a claims letter bot?

I would keep k small for letter wording, and leave every amount and decision to code. The letter template fixes the payout figure and the status, so the model only writes the sentences around them. I would also log the settings with each letter, so a complaint can be traced.

- **Fix facts in code:** The amount and the decision come from the claims system, never from the model's words.
- **Keep k small:** Test the letters with real claim files and widen k only if the wording reads too flat.
- **Log every letter:** Store the settings and the final text, so a wrong letter can be traced.
- **Re-test on change:** Run the same tests again whenever the model or the provider changes.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] A plain definition: keep the k most likely tokens, rescale, draw one.
- [ ] What k = 1 means: greedy decoding, always the top token.
- [ ] The weak point: a fixed k ignores how spread out the probabilities are.
- [ ] The fix: top-p, or a cut that depends on the step.
- [ ] Facts come from code, not from the sampled words.
- [ ] Settings can change by model, so check the current docs.

**Common traps**

- Trap: "Top-k makes the answer more accurate." Better: It only changes which words are likely to be picked. Facts still come from your data and code.
- Trap: "Top-k and top-p are the same thing." Better: Top-k counts a fixed number of tokens. Top-p keeps a set whose probabilities add up to a target.
- Trap: "A bigger k is always safer." Better: A bigger k lets less likely words in. It trades variety for the risk of odd wording.

## Can you spot the problem?

**Spot the problem:** A claims team reads four setups for the customer letter bot. Which one is the real problem?

A. The letter template is fixed, and the model fills only the greeting sentence.
B. The model writes the payout amount itself, with top_k = 40, and nothing checks it against the claims system.
C. Temperature is set to 0.2 for the summary of the medical notes.
D. A claims officer reads every letter before it goes to the customer.

**Answer:** B. The payout amount is a fact. Code should read it from the claims system and insert it into the letter. Top-k only changes the odds of which word comes next, so a sampled digit can be wrong.

**Quick check:** A claims bot must always state the payout amount held by the claims system. Which change fixes it?

A. Set top-k to 1, so it always picks the most likely word
B. Read the amount from the claims system in code and insert it into the letter
C. Raise top-k to 100 for more variety
D. Add 'be accurate' to the system prompt

**Answer:** B. Only code reads the amount reliably. Top-k 1 still lets the model guess the number in its own words, and a bigger k or a better prompt does not make the figure true.

## Can you answer these from memory?

**Flash cards**

- **What is top-k sampling?** Keep the k most likely next tokens, rescale them, then draw one at random.
- **What does k = 1 mean?** Greedy decoding: always the single most likely token.
- **What is the weak point?** A fixed k ignores how spread out the probabilities are.
- **What is the usual alternative?** Top-p: keep the smallest set whose probabilities add up to a target.
- **Does top-k make an answer true?** No. A wide k can let a wrong word in. Code must check the facts.
- **What does temperature control?** The degree of randomness in token selection.

## Likely follow-up questions

- Q010 What does temperature control? https://designervenkat.online/interview/ai/what-does-temperature-control
- Q012 What is top-p (nucleus) sampling? https://designervenkat.online/interview/ai/what-is-top-p-nucleus-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
- Q002 What does "predict the next token" mean? https://designervenkat.online/interview/ai/what-does-predict-the-next-token-mean

## Learn it in depth

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