Concepts / Probabilistic Sampling for Next-Token Selection

Probabilistic Sampling for Next-Token Selection

Top-k sampling restricts the candidate tokens to the k most likely ones; it does not force the single highest-scoring token to be chosen.

  • Programming

Why the Highest Score Is Not Always the Answer

When a language model is asked for the next token, it does not hand you a word directly. It produces a raw score for every token in its vocabulary, and those scores must be turned into a choice. The simplest rule would be to always take the token with the highest score. Top-k sampling works differently, and understanding why is the goal of this article.

What do you think happens?

If the model gives the token you the highest score at a given position, will top-k sampling always output the token you?

  • Yes, the highest-scoring token is always chosen

  • No, top-k only narrows the set of candidates, and a token is then drawn from that set

Reveal answer
Answer:

No, top-k only narrows the set of candidates, and a token is then drawn from that set

Top-k sampling restricts the candidate tokens to the k most likely ones. It does not force the single highest-scoring token to be chosen. Narrowing the choices is not the same as choosing one of them. The surviving candidates are passed on to a probabilistic draw.

Keeping the randomness in the final step has a real effect on the text that comes out. Because the sampler can choose less obvious tokens, the generated text can become more varied and sometimes more creative. The same freedom has a cost: lower-probability tokens still have some chance of being selected, and that can push the output toward text that is grammatically broken or nonsensical. The problem is not that the sampler is random. The problem is that the random choice is allowed to reach tokens that should never have been candidates at that position. Top-k sampling exists to draw that boundary.

Tracing the Raw Scores

The process starts with logits. A logit is the raw score the model produces for each vocabulary token before any probabilities are computed. The masking step described later works directly on these logits, so it helps to picture them as a list with one score per vocabulary entry.

The vocabulary used in this lesson has nine tokens: forward, closer, effort, inches, toward, every, moves, pizza, and you. Each one sits at a fixed position in the list. The scores below are illustrative values made up for this lesson, chosen so that the example is easy to follow. They are not outputs of any particular model.

PositionTokenRaw logit
0forward1.2
1closer0.4
2effort0.1
3inches-0.5
4toward0.9
5every-1.0
6moves0.3
7pizza-2.0
8you2.5

Illustrative raw logits for the nine-token vocabulary at one generation step

Notice that these numbers are not yet probabilities. They do not add up to 1, and some of them are negative. Their only job at this stage is to be compared with one another. Higher logits mean the model prefers that token more. The next question is how to decide which entries remain eligible.

The Three Stages of Top-k Masking

Top-k sampling removes tokens from the selection process by masking their scores. The procedure has three stages that always run in the same order. First, find the k largest logits. Second, mask every other logit. Third, apply softmax to convert the result into probabilities over the tokens that survived.

Raw logitsnine scores, one per tokenSelect top-kkeep the 3 largest logitsMask the restother logits becomenegative infinitySoftmaxconvert to probabilitiesProbabilitieszero for every masked tokeninputeligible positionsmasked scoresfinal distribution
In what order do the operations happen, and what does the data look like after each stage?

Read the flow from left to right. The logits are the input. The top-k step decides which positions are eligible. The masking step removes the rest by assigning them negative infinity. The softmax step turns the surviving scores into probabilities. The purpose of this arrangement is that the next token is always sampled from one of the top-k positions.

Masking With Negative Infinity

The masking rule compares each logit with the smallest logit inside the top-k group. Call that smallest value the threshold. Any logit below the threshold is replaced with negative infinity. Logits at or above the threshold are kept exactly as they were.

Negative infinity is a deliberate choice because of how softmax works. Softmax turns each logit into a probability by exponentiating it and dividing by the total of all exponentiated values. The softmax formula is shown below, where z_i is the logit at position i after masking and p_i is the resulting probability.

Formula

When a logit z_j is set to negative infinity, the term e^{z_j} becomes zero. A masked position therefore adds nothing to the sum and ends up with probability 0. The remaining probabilities still add up to 1, because the normalization is carried out only over the unmasked positions. A reader who has met masking in the causal attention material of chapter 3 will recognize the same idea.

forwardkept: logit 1.2,probability 0.185closermasked: -inf, probability 0effortmasked: -inf, probability 0inchesmasked: -inf, probability 0towardkept: logit 0.9,probability 0.137everymasked: -inf, probability 0movesmasked: -inf, probability 0pizzamasked: -inf, probability 0youkept: logit 2.5,probability 0.678
Which vocabulary positions keep their logit values, which become negative infinity, and how do those map to final probabilities of 0?

Worked Example: Nine Tokens, k Equals Three

Worked example

Applying top-k with k = 3 to the nine-token vocabulary

Using the illustrative logits from the table, select the top three, mask the rest, and compute the final next-token probabilities.

  1. 1
    Stage 1: find the top three logits

    The three largest logits are 2.5 for you, 1.2 for forward, and 0.9 for toward. Those three positions are eligible. Every other position is not.

  2. 2
    Find the threshold

    The smallest logit inside the top-k group is 0.9, which belongs to toward. This value is the threshold.

  3. 3
    Stage 2: mask everything below the threshold

    Closer (0.4), effort (0.1), inches (-0.5), every (-1.0), moves (0.3), and pizza (-2.0) are all below 0.9, so each is replaced with negative infinity. Forward, toward, and you keep their values.

  4. 4
    Stage 3: apply softmax over the survivors

    Compute e raised to each surviving logit: e^{2.5} is about 12.182, e^{1.2} is about 3.320, and e^{0.9} is about 2.460. Their sum is about 17.962. The masked positions contribute e^{-inf} = 0 and do not change the sum.

  5. 5
    Divide to get probabilities

    You gets 12.182 / 17.962, which is about 0.678. Forward gets 3.320 / 17.962, which is about 0.185. Toward gets 2.460 / 17.962, which is about 0.137. The three values sum to 1.

Result

The next token is drawn from {you, forward, toward} with probabilities about 0.678, 0.185, and 0.137. Each of the six masked tokens has probability exactly 0.

Notice what the example does not do. It does not simply output you. Token you is the most likely single choice, with a probability of about 0.678, but the other two candidates still have a real chance of being drawn. The sampling step, not the masking step, makes the final decision.

Greedy Choice Versus a Candidate Pool

Greedy selection always takes the single highest-scoring token, so its candidate pool has exactly one member. Top-k sampling keeps a pool of k tokens and then chooses among them probabilistically. The two approaches agree on the highest-scoring token being the most likely outcome, but they differ in what they allow to happen next.

PropertyGreedy choiceTop-k sampling
Candidate poolOne token, the highest scoreThe k highest-scoring tokens
Final drawDeterministic: always the top tokenProbabilistic draw from the surviving k
Treatment of other tokensIgnoredMasked to probability 0 only if outside the top k
Effect on varietySame output for the same scoresLess likely tokens can appear, within the top k

How the candidate pool differs between greedy choice and top-k sampling

Mistakes Beginners Make With Top-k

  • Common mistake

    Treating top-k as a way to pick the single best token

    Why it fails

    Top-k narrows the candidates to k tokens. It does not force the highest-scoring token to be chosen.

    Do this instead

    Think of top-k as setting the boundary of the candidate set, and the probabilistic draw as the step that picks a token inside that boundary.

  • Common mistake

    Setting masked logits to zero instead of negative infinity

    What it looks like

    Replacing 'pizza' with a logit of 0 would still give it an exponential term of e^0 = 1, so it would keep a nonzero share of the probability.

    Why it fails

    A logit of 0 is still a real score that contributes to the softmax sum. Only negative infinity makes the exponential zero.

    Do this instead

    Replace each logit below the threshold with negative infinity so that its probability after softmax is exactly 0.

  • Common mistake

    Applying softmax before masking

    Why it fails

    Once the probabilities are computed over all tokens, the masked positions have already contributed to the normalization. The order of the stages matters.

    Do this instead

    Select the top-k logits, mask the rest, and only then apply softmax.

  • Common mistake

    Assuming masked tokens can still be drawn because they had a nonzero logit before masking

Where Temperature and Multinomial Sampling Fit

Top-k is designed to work alongside probabilistic sampling and temperature scaling. Each part has a separate job. Top-k sets the boundary of the candidate set. Temperature scaling adjusts how evenly the probabilities are spread within that boundary, and a higher temperature spreads them more evenly. Multinomial sampling then makes the final draw from the resulting distribution.

Practice: Shrinking the Pool to Two

MEDIUM

Using the same nine illustrative logits from earlier, set k to 2. Which tokens keep their logits, which are masked, and what is the probability of forward after softmax? Give your answer to two decimal places.

Hints
  • Find the two largest logits first. Only those two positions survive.
  • The threshold is the smaller of the two surviving logits.
  • Compute e^{2.5} and e^{1.2}, then divide e^{1.2} by their sum.

What do you think happens?

With top-k set to 3 on the same logits, what is the probability assigned to pizza after softmax?

  • About 0.01, because pizza has a low logit

  • Exactly 0, because pizza is masked with negative infinity

Reveal answer
Answer:

Exactly 0, because pizza is masked with negative infinity

Pizza's logit of -2.0 is below the threshold of 0.9, so it is replaced with negative infinity. Its exponential term is zero, so it contributes nothing to the softmax sum and its probability is exactly 0.

Key Takeaways

  • Top-k sampling restricts the candidate tokens to the k most likely ones. It does not force the single highest-scoring token to be chosen.
  • The procedure has three stages: select the top-k logits, mask every other logit by replacing it with negative infinity, and apply softmax to the result.
  • The masking threshold is the smallest logit inside the top-k group. Logits below it are masked, and logits at or above it are kept.
  • Negative infinity makes the exponential term zero, so masked tokens get probability exactly 0 and the surviving probabilities still sum to 1.
  • Top-k sets the candidate boundary, temperature scaling adjusts how evenly probabilities are spread inside it, and multinomial sampling makes the final draw.

Related concepts

More concepts starting with P