esc
  • WorkflowsPages
  • Case studiesPages
  • Machine Learning FoundationsLearn
  • AI EngineeringLearn
  • AI Guardrails & Red TeamingLearn
  • UI/UXLearn
  • Design SystemsLearn
  • Production System DesignLearn
  • AI papersPages
  • Interview KitPages
  • Book a callContact
  • Download ResumeContact
Let’s talk

I’ll build the agent for it.

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.

11 min readBeginnerVery common · estimateFacts checked 26 November 2026

Say it out loud

Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.

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.

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.

Key words

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

    Score every token

    The model gives each possible next token a probability.

  2. 2

    Keep the top k

    Sort by probability and drop everything after the first k.

  3. 3

    Rescale what is left

    Scale the kept probabilities so they add up to 100%.

  4. 4

    Draw one

    Pick one token at random from the kept set, by its share.

How top-k picks the next token

Model's probabilities

every token it knows, with a share

Keep the top k

Sort, most likely first

the list is ordered by share

Drop the rest

everything after the first k

Rescale the kept shares

so the shares add up to 100%

Draw one token

the next word of the answer

  1. 1The scores are sorted, most likely first.
  2. 2Everything past the first k is dropped.
  3. 3The kept shares are rescaled to add up to 100%.
  4. 4One token is drawn at random from what is left.
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.
  • “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

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.

Why one fixed k can go wrong

Peaked step

One clear winner

one token takes most of the share

Flat step

Six close options

each one a fair choice

Same fixed k = 3

ignores how sure the model is

Wrong word list

too loose or too tight

  1. 1On a peaked step, k = 3 keeps two weak tokens with the winner.
  2. 2On a flat step, k = 3 drops three options that were all fair.
  3. 3One setting is too loose in one case and too tight in the other.
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.

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

    BetterIt 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."

    BetterTop-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."

    BetterA 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?

Quick check

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

Can you answer these from memory?

Flash cards · tap a card to flip it

1 / 6

What will they ask next?

  1. Q010What does temperature control?10 min
  2. Q012What is top-p (nucleus) sampling?10 min
  3. Q013Greedy vs beam search vs sampling?12 min
  4. Q014Why can one prompt give different answers?11 min
  5. Q002What does "predict the next token" mean?10 min

Learn it in depth

Last updated on 26 November 2026

Building an assistant that writes customer letters?

I design and build AI products and agents: the UI and the system behind them. Book a short call and tell me which facts your letters must get right.