Sub topic 10
Generating text: greedy decoding, temperature, and top-k sampling
This chapter assumes you know that a decoder-only model outputs one vector of logits (raw scores, one per vocabulary token) at each position, and that softmax turns logits into probabilities. You should also be comfortable reading short NumPy code.
From probabilities to a token
A trained model never writes a whole sentence at once. For a given prefix it produces a probability distribution over the next token. A decoding strategy picks one token from that distribution. The token is appended to the prefix, and the loop repeats until the model emits an end-of-sequence token or reaches a length limit.
Greedy decoding
Greedy decoding always takes the token with the highest probability, which is the argmax of the logits. It is deterministic: the same prefix gives the same output every time.
It is a good fit for tasks with one right answer, such as extraction or classification. For open-ended writing it tends to produce flat, repetitive text and can get stuck in loops. It is also not guaranteed to find the most probable full sequence, because the best first token does not always lead to the best continuation.
Temperature
Temperature rescales logits before softmax. With temperature T, each logit is divided by T.
- T below 1 sharpens the distribution. High-probability tokens become more likely.
- T equal to 1 leaves the model's distribution unchanged.
- T above 1 flattens the distribution. Unlikely tokens get more chance.
- As T approaches 0, sampling approaches greedy decoding.
Temperature must be greater than 0, because dividing by 0 is undefined. Systems that offer "temperature 0" usually switch to argmax.
Top-k sampling
Even at moderate temperature, a vocabulary of tens of thousands of tokens has a long tail of poor choices. Each is individually unlikely, but together they can hold noticeable probability. Top-k sampling keeps only the k highest logits, sets the rest to negative infinity, and samples from the renormalized distribution. This cuts off the tail while keeping variety among the plausible tokens.
Putting it together
This function applies temperature, then top-k, then samples.
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)))Subtracting logits.max() before np.exp prevents overflow and does not change the result. With top_k=2, only tokens 0 and 1 can ever be chosen. Token 0 is much more likely, since after dividing by 0.7 its logit leads by about 1.43.
Choosing settings
| Task | Suggested setting | Reason |
|---|---|---|
| Extraction, classification, code fixes | Greedy or temperature near 0 | One correct answer, repeatability matters |
| Question answering | Temperature 0.2 to 0.5 | Mostly faithful, slight variation |
| Brainstorming, fiction | Temperature 0.8 to 1.2, top-k 40 to 100 | Variety matters more than precision |
These ranges are starting points. Test them on your own model and task.
Common errors
- Setting temperature to exactly 0 in your own code. This divides by zero. Use argmax instead.
- Setting
top_klarger than the vocabulary. Indexingnp.sort(logits)[-top_k]then fails. - Expecting identical outputs from sampling. Without a fixed random seed, results differ between runs.
- Assuming high temperature adds creativity. It adds randomness, which also raises the chance of incoherent or false text.
Exercise
Given logits [2.0, 1.0, 0.0], does temperature 0.5 make the top token more or less likely than temperature 1.0? What happens with temperature 2.0, and what does top_k=1 do?
Show answer
Temperature 0.5 doubles the logits to [4, 2, 0], which widens the gaps, so the top token becomes more likely. Temperature 2.0 gives [1, 0.5, 0], which flattens the distribution, so the top token becomes less likely. With top_k=1, only the highest logit survives, so the result is always that token, which is the same as greedy decoding.