Top-k Sampling › Worked Example: Step-by-Step Numerical Trace
Language AI HandbookAll chapters Top-k Sampling › Worked Example: Step-by-Step Numerical TraceOne section · Sections in this chapter4 / 13 ↓
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
To make the algorithm fully concrete, let us trace through a complete top-k sampling step with small, explicit numbers. This example uses a toy vocabulary of 8 tokens so we can inspect every calculation by hand.
Suppose we have just processed the context "The sky is" and our language model outputs the following raw logits over 8 vocabulary tokens:
| Token | Logit |
|---|---|
| blue | 3.2 |
| clear | 2.8 |
| dark | 1.5 |
| gray | 1.1 |
| red | 0.4 |
| green | -0.3 |
| loud | -1.2 |
| empty | -2.5 |
Step 1: Convert logits to probabilities using softmax. For each logit , compute , then divide by the sum of all exponentials.
The exponentials are:
- blue:
- clear:
- dark:
- gray:
- red:
- green:
- loud:
- empty:
The sum of all exponentials is .
Dividing each exponential by 51.06 gives the probability distribution:
| Token | Probability |
|---|---|
| blue | 0.480 |
| clear | 0.322 |
| dark | 0.088 |
| gray | 0.059 |
| red | 0.029 |
| green | 0.014 |
| loud | 0.006 |
| empty | 0.002 |
Step 2: Select the top tokens. Ranking by probability, the top 4 are: blue (0.480), clear (0.322), dark (0.088), gray (0.059). The remaining tokens (red, green, loud, empty) are excluded.
Step 3: Compute the normalization constant. We sum the probabilities of the kept tokens:
Step 4: Renormalize. Divide each kept token's probability by :
| Token | Original Probability | Renormalized Probability |
|---|---|---|
| blue | 0.480 | 0.480 / 0.949 = 0.506 |
| clear | 0.322 | 0.322 / 0.949 = 0.339 |
| dark | 0.088 | 0.088 / 0.949 = 0.093 |
| gray | 0.059 | 0.059 / 0.949 = 0.062 |
| Sum | 0.949 | 1.000 |
Step 5: Sample. We now draw one token from this renormalized distribution. With probability 0.506 we select "blue"; with probability 0.339, "clear"; with probability 0.093, "dark"; and with probability 0.062, "gray". The tokens "red", "green", "loud", and "empty" can never be selected.
Verification of ratio preservation. Let us check that the ratio of "blue" to "clear" is preserved. Originally: . After renormalization: . The tiny difference is rounding error; the ratio is preserved because both are divided by the same . The model's belief that "blue" is about 1.5 times more likely than "clear" is fully honored.
This numerical trace shows every operation explicitly: softmax converts logits to probabilities, top- selection identifies the candidates, summation computes the normalization constant, division produces a valid probability distribution, and multinomial sampling draws the final token.