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.
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?
Reveal 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.
| Position | Token | Raw logit |
|---|---|---|
| 0 | forward | 1.2 |
| 1 | closer | 0.4 |
| 2 | effort | 0.1 |
| 3 | inches | -0.5 |
| 4 | toward | 0.9 |
| 5 | every | -1.0 |
| 6 | moves | 0.3 |
| 7 | pizza | -2.0 |
| 8 | you | 2.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.
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.
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.
Worked Example: Nine Tokens, k Equals Three
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.
- 1Stage 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.
- 2Find the threshold
The smallest logit inside the top-k group is 0.9, which belongs to toward. This value is the threshold.
- 3Stage 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.
- 4Stage 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.
- 5Divide 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.
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.
| Property | Greedy choice | Top-k sampling |
|---|---|---|
| Candidate pool | One token, the highest score | The k highest-scoring tokens |
| Final draw | Deterministic: always the top token | Probabilistic draw from the surviving k |
| Treatment of other tokens | Ignored | Masked to probability 0 only if outside the top k |
| Effect on variety | Same output for the same scores | Less 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 failsTop-k narrows the candidates to k tokens. It does not force the highest-scoring token to be chosen.
Do this insteadThink 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 likeReplacing '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 failsA logit of 0 is still a real score that contributes to the softmax sum. Only negative infinity makes the exponential zero.
Do this insteadReplace 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 failsOnce the probabilities are computed over all tokens, the masked positions have already contributed to the normalization. The order of the stages matters.
Do this insteadSelect 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
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?
Reveal 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.