Sub topic 10
Generating text: greedy decoding, temperature, and top-k sampling
This chapter assumes you know what a logit vector is (the raw scores the model outputs at each position), how softmax turns scores into probabilities, and how to read short NumPy code. The previous chapters built a model that maps a token sequence to a probability distribution over the next token. Here you learn how to turn that distribution into actual text.
From distribution to token
A decoder-only model does not output text. At each position it outputs one logit per vocabulary entry. For generation, only the last position matters, because it holds the prediction for the next token.
Softmax converts the logits into probabilities. A decoding strategy is the rule that picks one token ID from that distribution. The model itself is the same in every case. Only the picking rule changes.
Generation is a loop:
- Run the model on the tokens so far.
- Take the logits at the last position.
- Pick one token with the decoding rule.
- Append it to the sequence.
- Repeat until an end-of-sequence token appears or a length limit is reached.
Each pick depends on every earlier pick. This is why generation is called autoregressive: the model's own outputs become its next inputs. An early unlucky choice cannot be revised later. It stays in the context and shapes everything after it.
Greedy decoding
Greedy decoding always picks the token with the highest probability. In NumPy that is int(np.argmax(logits)). You do not even need softmax, because softmax preserves ordering.
Greedy decoding is deterministic. The same prompt and the same model give the same output, apart from small numerical differences in floating-point arithmetic on parallel hardware. That makes it useful for tests, extraction, and classification-style tasks.
It also has known problems:
- Repetition loops. Once a phrase repeats, the repeated context makes the same phrase more likely, and greedy decoding never escapes.
- Locally best, globally poor. The most likely token now can lead to a worse full sentence than a slightly less likely token would.
- Flat, generic text. The model's most probable continuation is often the blandest one.
Beam search keeps several candidate sequences and scores whole sequences. It reduces the second problem, but it is mostly used in translation and summarization. Chat-style generation typically uses sampling instead.
Temperature
Sampling means drawing a token at random in proportion to its probability. If a token has probability 0.25, it is picked about a quarter of the time.
Temperature T reshapes the distribution before sampling. You divide the logits by T, then apply softmax:
p_i = exp(z_i / T) / sum_j exp(z_j / T)
T = 1leaves the distribution as the model produced it.T < 1makes it sharper. The top token gains probability.T > 1makes it flatter. Unlikely tokens gain probability.T → 0approaches greedy decoding.
Temperature never changes the ranking of tokens. It changes only how far apart their probabilities are. The code below shows the effect on the logits used in the chapter's sampler.
import numpy as np
def softmax(logits, temperature=1.0):
z = np.asarray(logits, dtype=float) / temperature
z = z - z.max()
p = np.exp(z)
return p / p.sum()
logits = [3.0, 2.0, 0.5, -1.0]
for t in (0.5, 1.0, 2.0):
print(t, np.round(softmax(logits, t), 3))For these logits, the probabilities come out approximately as follows.
| Temperature | Token 0 | Token 1 | Token 2 | Token 3 |
|---|---|---|---|---|
| 0.5 | 0.875 | 0.118 | 0.006 | 0.000 |
| 1.0 | 0.681 | 0.251 | 0.056 | 0.012 |
| 2.0 | 0.493 | 0.299 | 0.141 | 0.067 |
At T = 2, the worst token is picked about 7% of the time. Over a 200-token answer, that means several poor choices on average.
Top-k sampling
Pure sampling at T = 1 has a weakness. The vocabulary may hold tens of thousands of tokens, and the tail (the many tokens with tiny probabilities) adds up. If the tail holds 5% of the total probability, then about one token in twenty comes from it, and tail tokens are often nonsense in context.
Top-k sampling removes the tail. Keep only the k highest-scoring tokens, set the others to -inf, and sample from what remains. After softmax, the removed tokens have probability exactly 0, and the survivors are renormalized to sum to 1.
Using the logits above at T = 1 with k = 2, the survivors have probabilities 20.09 / 27.47 ≈ 0.731 and 7.39 / 27.47 ≈ 0.269.
Here is the sampler from this chapter's reference code, with the steps in the order they run:
import numpy as np
def sample_next(logits, temperature=1.0, top_k=None, rng=None):
# temperature must be greater than 0
rng = rng or np.random.default_rng()
logits = np.asarray(logits, dtype=float) / temperature
if top_k is not None:
cutoff = np.sort(logits)[-top_k]
logits = np.where(logits < cutoff, -np.inf, logits)
probs = np.exp(logits - logits.max())
probs /= probs.sum()
return int(rng.choice(len(probs), p=probs))
logits = [3.0, 2.0, 0.5, -1.0]
print(sample_next(logits, temperature=0.7, top_k=2, rng=np.random.default_rng(0)))The function returns 0 or 1, never 2 or 3. Which one you get depends on the random generator's seed.
Order of operations
Temperature is applied first, then the top-k filter, then softmax. Dividing by a positive temperature does not change which tokens rank in the top k, so the order of those first two steps does not change the result. Softmax must come after masking, so the masked tokens get probability 0 and the rest sum to 1.
Edge cases
top_k = 1is greedy decoding. Only the maximum survives.top_klarger than the vocabulary breaks this implementation, becausenp.sort(logits)[-top_k]raises anIndexError. Clamp it withmin(top_k, len(logits)).- Ties at the cutoff. The filter keeps everything with
logits >= cutoff. If several tokens tie at thek-th score, more thanktokens survive. With real-valued model outputs this is rare, but it can occur with low-precision arithmetic. top_k = 0is not valid here. Many libraries use 0 to mean "disabled", which is a convention you must implement yourself.- Fixed
kignores the shape of the distribution. When the model is nearly certain,k = 50still admits 49 tokens that have almost no probability. When the model is genuinely unsure among 200 reasonable tokens,k = 50cuts off good options.
That last limitation is why many systems also offer top-p (nucleus) sampling, which keeps the smallest set of tokens whose probabilities add up to p. It is outside this chapter's scope, but you will see it next to top-k in most APIs.
Reproducibility
Sampling is random, so two runs on the same prompt can differ. To reproduce a run, fix the random seed and keep every other setting the same. Even then, hosted services may give different results across calls because of batching and hardware differences, so treat seeds as best effort.
Choosing settings for a task
No setting is correct in general. Match it to how much variation the task tolerates.
| Task | Typical choice | Reason |
|---|---|---|
| Extracting fields from text | Greedy, or `T` near 0 | One right answer, and you want repeatable output |
| Code generation | Low `T` (about 0.2 to 0.5) | Syntax errors from unlikely tokens are costly |
| Question answering from provided text | Low `T` | Lower variation reduces invented details |
| Summarization | `T` about 0.3 to 0.7 | Some phrasing freedom, little drift |
| Brainstorming, fiction | `T` about 0.8 to 1.2, moderate top-k | Variety matters more than precision |
| Generating many candidates to compare | `T` about 1.0 | Diverse samples give a useful spread |
These ranges are rules of thumb. Models and providers differ, so test on your own prompts.
Cost of the loop
Each loop iteration needs a forward pass, so a 500-token answer needs 500 passes. Recomputing attention over the whole sequence every time would waste work, because earlier positions do not change. The next chapter explains how a key-value cache avoids that. The decoding rule itself is cheap by comparison. Sorting or masking a vocabulary-sized vector takes little time next to a transformer forward pass.
Exercises
Exercise
Using the logits [2.0, 1.0, 0.0] at temperature 1, compute the probabilities after top-k filtering with k = 2. Give both values to two decimal places.
Show answer
Only the first two tokens survive. exp(2) ≈ 7.389 and exp(1) ≈ 2.718, and their sum is ≈ 10.107. The probabilities are 7.389 / 10.107 ≈ 0.73 and 2.718 / 10.107 ≈ 0.27. The third token gets probability 0.
Exercise
A teammate says that lowering the temperature from 1.0 to 0.2 will change which token the model considers most likely. Is that correct? What does change?
Show answer
No. Dividing logits by a positive number keeps their ranking, so the most likely token stays the same. What changes is the gap between probabilities: the top token becomes much more probable and the others less so, which makes sampling closer to greedy decoding.
Exercise
Your sampler is called with top_k=50 on a model whose vocabulary has 30 tokens in a toy test. What happens with the implementation in this chapter, and how do you fix it?
Show answer
np.sort(logits)[-50] raises an IndexError because the array has only 30 elements. Clamp the value first, for example k = min(top_k, len(logits)), and use k when computing the cutoff.