Decoding: temperature, top-k, top-p
- Say why greedy decoding gets stuck repeating itself
- Divide by the temperature, and say what that does to the spread of the probabilities
- Keep the k largest scores, without the off-by-one or the trap with ties
- Keep the token that crosses p in top-p, and put each score back at its own token id
- Run temperature, top-k and top-p in the right order, and say which of them can swap
- Seed the draws so a run repeats, and answer the follow-ups on beam search, repetition penalties, min-p and speculative decoding
Decoding with temperature, top-k and top-p
A model's last layer gives a score to every token in its vocabulary, and something has to turn those scores into the next word. That something is the sampler. A fundamentals screen can ask how you'd make a model's output more or less creative, and the answer is the sampler's settings. A coding round can ask you to write it:
logitsis a(B, V)tensor: one row per sequence, and one score for each of theVtokens in the vocabulary. Write a sampler in four levels.
filter_logits(logits, temperature=1.0)divides by the temperature, andsample(logits, temperature=1.0, top_k=None, top_p=None, generator=None)returns one token id per row, shape(B,), drawn from the filtered distribution.temperature == 0means greedy: take the highest score.top_k: set to-infevery score outside thetop_klargest.top_p: then set to-infevery score outside the nucleus, the smallest set of most likely tokens whose probabilities add up to at leasttop_p. Always keep at least one token.penalize(logits, prev_ids, penalty): lower the score of every token already in that row'sprev_ids, once each, whatever its sign.Then tell me why greedy decoding repeats itself, and when you'd pick beam search.
Here are both functions on one row. The model has read The cat sat on the, and six words are left, with the scores [3.0, 2.0, 1.0, 0.5, 0.0, -1.0] for mat, floor, sofa, bed, roof and moon. The probabilities are the softmax of what filter_logits returns:
| Call | Words left, with their probabilities |
|---|---|
filter_logits(row) | all six: mat 0.605, floor 0.222, sofa 0.082, bed 0.050, roof 0.030, moon 0.011 |
filter_logits(row, top_k=3) | mat 0.665, floor 0.245, sofa 0.090 |
filter_logits(row, top_k=3, top_p=0.9) | mat 0.731, floor 0.269 |
filter_logits(row, temperature=2.0, top_p=0.9) | mat 0.403, floor 0.244, sofa 0.148, bed 0.115, roof 0.090 |
sample(row, temperature=0) | tensor([0]): mat, every time |
Each function is a few lines. The bugs that cost the round raise no error: a knob that turns backwards, a filter that keeps one token too many or too few, a draw from the wrong probabilities. The lesson takes one piece at a time on these six words: greedy, temperature, top-k, top-p, then the whole sampler and the follow-ups. At the end you write all four levels yourself, as the practice problem, in about 35 minutes.
From logits to one token
A trained model doesn't write text. At each position it outputs a score for every token in its vocabulary, called the logits. Decoding is the loop that turns those scores into text, one token per step.
1@torch.no_grad()2def generate(3 model: nn.Module, idx: torch.Tensor, max_new_tokens: int, **decoding4) -> torch.Tensor:5 """idx: (B, T) token ids. Returns (B, T + max_new_tokens)."""6 for _ in range(max_new_tokens):7 logits, _ = model(idx[:, -model.block_size:]) # (B, T, V)8 next_id = sample(logits[:, -1, :], **decoding) # (B,)9 idx = torch.cat([idx, next_id[:, None]], dim=1) # (B, T + 1)10 return idxThis is the whole loop that writes text with a GPT. Each step runs the model, keeps the scores at the last position, picks one token and adds it to the end. Step through it above.
B is the number of sequences, T the tokens in each, and V the number of tokens in the vocabulary. A token is a word or a piece of a word.
The logits are the model's raw scores, before any softmax.
Decoding is the rule inside sample that turns a (B, V) row of scores into one token id per sequence. The weights never change. Still, the same model can write something sharp, something bland or pure nonsense, and that one function decides which.
Greedy decoding takes the top score every time
The model has read The cat sat on the and scores six candidates. Pretend they are the whole vocabulary.
import torch
words = ["mat", "floor", "sofa", "bed", "roof", "moon"]
row = torch.tensor([[3.0, 2.0, 1.0, 0.5, 0.0, -1.0]])
print(row.softmax(dim=-1).round(decimals=3))
print(words[row.argmax(dim=-1).item()])
Six scores, [3.0, 2.0, 1.0, 0.5, 0.0, -1.0], for mat to moon. About how much probability does the softmax give mat, and which word does the argmax pick?
Greedy gets stuck repeating itself
On open-ended text, greedy falls into loops: the same phrase, again and again.
Greedy has just repeated a phrase once. What happens to the chance that it repeats again?
The best next token doesn't always start the best pair
Greedy has a second problem: it looks only one token ahead.
Greedy compares only the first step, and 0.6 beats 0.4. It never scores what comes after B, so it can't know whether a pair that starts with B is the more likely one.
Beam search does. Switch the figure to a beam of width 2 to see it.
In the editor, first holds the figure's chances for the first token, A or B. second holds the chances of each next token, after A and after B. Set greedy_pair: the top first token, then its top second token, as (first, second, probability). Set best_pair: the most likely pair of all, found by trying every pair.
Raschka shows why his generate loop writes the same text on every run, because it always takes the highest score, and sets up two ways to add controlled randomness: temperature and top-k.
Temperature divides the scores before the softmax
The first knob for leaving greedy behind is temperature.
for T in (0.5, 1.0, 2.0):
print(T, (row / T).softmax(dim=-1).round(decimals=3))
Divide the logits by T = 0.5, 1 and 2 before the softmax. What happens to mat's 0.605?
Can a temperature above 0 change which token is the argmax?
A higher temperature always spreads the weight more
How spread out is a distribution? Entropy puts a number on it.
def bits(p: torch.Tensor) -> float:
"""p: probabilities that sum to 1. Returns their entropy in bits."""
return -(p * p.log2()).sum().item()
for T in (0.5, 1.0, 2.0):
print(T, round(bits((row / T).softmax(dim=-1)), 2))
0.5 0.71
1.0 1.66
2.0 2.29
Entropy is : 0 when one token takes everything, and at its largest, log V, when every token is equal.
- Tokens kept
- 6 of 6
- Top token
- 0.60
- Entropy
- 1.66 bits
Entropy rises with T and never falls. If asked why: the slope is the variance of the logits divided by T³, and neither can be negative.
is the variance of the logits, weighted by the tempered probabilities . The slope is exactly 0 only when every logit is the same. (The formula uses log base e, so it counts in nats. One nat is about 1.44 bits.)
In the editor, write tempered_probs(logits, temperature): (B, V) logits in, the probabilities at that temperature out. At temperature == 0, put all of each row's weight on its argmax.
Write tempered_probs(logits, temperature): (B, V) logits in, the probabilities at that temperature out, same shape. At temperature == 0, put all of each row's weight on its argmax.
Top-k keeps the k highest scores
Temperature reshapes every token's chance, the bad ones included. Top-k removes the bad ones.
def keep_top_k(logits: torch.Tensor, k: int) -> torch.Tensor:
"""logits: (B, V). Keeps each row's k largest and sets the rest to -inf."""
kth = torch.topk(logits, k, dim=-1).values[..., -1:]
return logits.masked_fill(logits < kth, float("-inf"))
print(torch.topk(row, 3, dim=-1).values)
print(keep_top_k(row, 3))
print(keep_top_k(row, 3).softmax(dim=-1).round(decimals=3))
tensor([[3., 2., 1.]])
tensor([[3., 2., 1., -inf, -inf, -inf]])
tensor([[0.6650, 0.2450, 0.0900, 0.0000, 0.0000, 0.0000]])
With k = 3, mat, floor and sofa stay. The other three become minus infinity.
- Tokens kept
- 3 of 6
- Top token
- 0.67
- Entropy
- 1.20 bits
torch.topk returns the k largest values, largest first. So the last of them is the k-th largest, and that's the threshold: everything strictly below it goes.
Why cut at all? Even a good model gives every token some probability, and over a large vocabulary that adds up. Holtzman et al. call it the unreliable tail: tens of thousands of unlikely tokens that, added together, get more weight than they should. Sample from the full distribution and sooner or later you draw one.
Top-k is the bluntest fix: keep the k largest logits and drop the rest. Fan et al. (2018) sampled their stories from the 10 most likely candidates.
In the editor are keep_top_k from above and row, the six words' scores. Set after: the softmax of keep_top_k(row, 3). Set renorm: the first three probabilities of the full softmax, divided by their sum. Set same: whether renorm matches the first three entries of after. Compare floats with torch.allclose, because == can miss in the last digit.
Each row needs its own threshold, as a column
In a batch, every row has its own k-th largest score.
rows = torch.tensor([[0.3, 2.0, -1.0, 1.5, 0.0],
[5.0, 1.0, 4.0, 3.0, 2.0],
[-2.0, -1.0, 0.5, -3.0, 1.0]])
print(torch.topk(rows, 2, dim=-1).values[..., -1:])
print(torch.topk(rows, 2, dim=-1).values[..., -1])
Each row's 2nd largest value is its threshold. What shapes are values[..., -1:] and values[..., -1]?
Equal scores can let more than k through
A threshold compare has one edge case: ties.
ties = torch.tensor([[2.0, 1.0, 1.0, 0.0]])
print(keep_top_k(ties, 2))
ties is [2.0, 1.0, 1.0, 0.0] and k = 2, so the threshold is 1. How many tokens stay?
400 rows of random logits over GPT-2's 50,257 tokens, cut to the top 50. In float32, every row keeps exactly 50. Round the rows to bf16. How many keep more than 50?
A fixed k is too many one time and too few the next
Ties are a small problem. The big one shows up across prompts.
- Tokens kept
- 3 of 6
- Top token
- 0.95
- Entropy
- 0.31 bits
Top-k's real weakness is that k is fixed.
With k = 3, what goes wrong on My favorite color is, where blue down to yellow score 1.0 down to 0.5?
Top-p keeps the fewest tokens that reach p
A real vocabulary isn't sorted by score. Now give the six candidates ids in alphabetical order, the way a tokenizer might: bed 0, floor 1, mat 2, moon 3, roof 4 and sofa 5. by_id holds the same six scores in that order.
vocab = ["bed", "floor", "mat", "moon", "roof", "sofa"]
by_id = torch.tensor([[0.5, 2.0, 3.0, -1.0, 0.0, 1.0]])
sorted_logits, order = torch.sort(by_id, descending=True, dim=-1)
sorted_p = sorted_logits.softmax(dim=-1)
print(order)
print(sorted_p.round(decimals=3))
print(sorted_p.cumsum(dim=-1).round(decimals=3))
The same six scores, in alphabetical id order: bed 0, floor 1, mat 2, moon 3, roof 4, sofa 5. What does order, the sort's second output, print?
At p = 0.9, how many tokens does the nucleus hold on Two plus two is, The cat sat on the and My favorite color is?
Drop a token only when the tokens before it already reach p
Top-p needs a careful rule for the token that crosses p.
The rule that works: drop a token only when the mass before it already reaches p. Mat has 0 before it, floor 0.605, sofa 0.827 and bed 0.909. At p = 0.9, sofa stays and bed goes.
The top token always has exactly 0 before it. So it stays for any p above 0, and keeping at least one token comes for free.
In the editor, sorted_p holds the six probabilities, largest first. Write drop_mask(sorted_p, p): True where a token goes, because the tokens before it already reach p.
Put each kept score back at its own token id
Top-p works on sorted probabilities, but the model's token ids aren't sorted.
print(keep_top_p(by_id, 0.9).softmax(dim=-1).round(decimals=3))
The result comes back in id order: bed, floor, mat, moon, roof, sofa. Which entries are not 0?
The order is temperature, then top-k, then top-p
With all three filters written, the order you apply them in matters.
The practice problem fixes this order, and it's the standard one. Hugging Face's generate runs temperature, then top-k, then top-p, then min-p, with any repetition penalty applied before all of them.
The sampler comes as two functions. filter_logits(logits, temperature, top_k, top_p) returns the (B, V) logits after all three steps, in that order. sample(logits, temperature, top_k, top_p, generator) softmaxes what filter_logits returns and draws one token id per row, or returns the argmax at temperature == 0. You write both in a few steps. Here is sample on the six words:
g = torch.Generator().manual_seed(0)
print(sample(row, temperature=0))
print(sample(row.repeat(8, 1), top_k=3, generator=g))
sample(row, temperature=0), then 8 draws with top_k=3. Which ids can the 8 draws hold?
Temperature and top-k can swap places, top-p can't
Does the order really matter? Test each pair.
for T in (0.5, 1.0, 2.0):
print(T, torch.isfinite(filter_logits(row, T, top_p=0.9)).sum().item())
Top-p 0.9 after dividing by T = 0.5, 1 and 2. How many tokens does the nucleus hold?
After top-k, p is a share of what top-k kept
When top-k runs first, top-p sees fewer tokens, and that changes what p means. Top-k 3 keeps mat, floor and sofa, and the softmax spreads all the weight over those three. Top-p then reads that renormalized row, not the full distribution.
Flip top-k 3 first off and on, and watch sofa come and go.
So after top-k, p is a share of what top-k kept, not of the whole vocabulary.
In the editor are keep_top_k and keep_top_p again. Set full_share: the probability that mat and floor hold in the full softmax. Set kept_share: the share they hold after top-k 3. Set both: the words that survive top-k 3 and then top-p 0.9, as a list.
A worked example: six tokens, every setting
Here are all the settings at once, on the six-word row.
| Token | Logit | |||
|---|---|---|---|---|
| mat | 3.0 | 0.860 | 0.605 | 0.382 |
| floor | 2.0 | 0.116 | 0.222 | 0.232 |
| sofa | 1.0 | 0.016 | 0.082 | 0.140 |
| bed | 0.5 | 0.006 | 0.050 | 0.109 |
| roof | 0.0 | 0.002 | 0.030 | 0.085 |
| moon | -1.0 | 0.0003 | 0.011 | 0.052 |
| Entropy | 0.71 bits | 1.66 bits | 2.29 bits |
Uniform over six tokens would be bits. Greedy says mat at every temperature. Square the T = 1 column and renormalize, and you get the T = 0.5 column, because dividing the logits by 0.5 squares the probabilities.
The same six tokens, live. Set the sliders to any row of the two tables here, and the bars match it.
- Tokens kept
- 6 of 6
- Top token
- 0.60
- Entropy
- 1.66 bits
Now the filters, each renormalized over what survives:
| Setting | Kept | Probabilities |
|---|---|---|
| , top-k 3 | mat, floor, sofa | 0.665, 0.245, 0.090 |
| , top-p 0.9 | mat, floor | 0.881, 0.119 |
| , top-p 0.9 | mat, floor, sofa | 0.665, 0.245, 0.090 |
| , top-p 0.9 | mat, floor, sofa, bed, roof | 0.403, 0.244, 0.148, 0.115, 0.090 |
| , top-k 3, then top-p 0.9 | mat, floor | 0.731, 0.269 |
Walk the T = 1, top-p 0.9 row. The running totals are 0.605, 0.827, 0.909. Sofa takes the total past 0.9, so it stays. The mass before bed is already 0.909, so bed goes.
Here's what each mistake does to this example. For the scatter row, the ids are alphabetical, bed 0 to sofa 5. With mat as id 0, the row is already sorted, and that hides the bug.
| Mistake | What you get |
|---|---|
logits * T at | the column, 0.71 bits instead of 2.29 |
cumsum >= p at , | mat and floor only, 0.827 of the mass |
| with | bed survives too |
| no scatter back at , | bed, id 0, gets mat's 0.665, and sofa can never be drawn |
| sampling unfiltered at , top-k 3 | 9.1% of draws are bed, roof or moon |
In the editor, keep_top_k and keep_top_p are done. Finish filter_logits(logits, temperature=1.0, top_k=None, top_p=None): divide by the temperature, then top-k, then top-p, and skip a filter that is None.
Finish filter_logits(logits, temperature=1.0, top_k=None, top_p=None): divide by the temperature, then top-k, then top-p, skipping a filter that's None. The tests use this lesson's six candidates, mat to moon, as ids 0 to 5.
Seeding: the same draws every run
Random draws make tests flaky unless you control the randomness.
g = torch.Generator().manual_seed(0)
print(sample(row.repeat(8, 1), generator=g))
print(sample(row.repeat(8, 1), generator=g))
g = torch.Generator().manual_seed(0)
print(sample(row.repeat(8, 1), generator=g))
Seed a generator with 0 and draw 8 tokens, twice. Then seed a fresh one with 0 and draw once more. Which lines match?
Beam search keeps the b best sequences so far
Interviewers often go past the sampler. Four follow-ups come up: beam search, repetition penalties, min-p and speculative decoding.
Beam search keeps the b best partial sequences by total log-probability, where b is the beam width. Each step extends every one of them by every token and keeps the best b again.
Width 1 is greedy. On the two-step example from the greedy section, a beam of 2 keeps both first tokens and finds the 0.36 pair that greedy missed.
It's the right tool when the input pins the output down, as in translation or summarization. There, repetition and blandness matter less.
Open-ended text is different. Beam search has greedy's problems, worse, because it's a better maximizer:
- Holtzman et al. conclude that maximizing probability is the wrong goal for open-ended text.
- Fan et al. found that beam search tends to produce common phrases and repetitive text from the training set.
- It runs b sequences per prompt, each with its own KV cache, the stored keys and values of the tokens so far.
In the editor are the two-step example's chances again: first for the first token, and second for the token after it. Finish beam(width): set starts, the width most likely first tokens, and pairs, every (first, second, probability) that extends one of them.
Greedy decoding and beam search on a small tree, including a case where greedy misses the most likely sequence and a beam of two finds it.
A repetition penalty has to push down, whatever the sign
Another knob fights the repetition that greedy falls into.
logit, penalty = torch.tensor([2.0, -1.0]), 1.2
print(logit / penalty)
print(torch.where(logit > 0, logit / penalty, logit * penalty))
A repetition penalty of 1.2 should make both tokens less likely. What does dividing [2.0, -1.0] by 1.2 do?
Min-p cuts at a share of the top token
A newer filter, min-p, sets its cut from the top token's probability.
probs = row.softmax(dim=-1)
cut = 0.1 * probs.max()
print(round(cut.item(), 4))
print([w for w, q in zip(words, probs[0]) if q >= cut])
0.0605
['mat', 'floor', 'sofa']
Here the bars are the model's own probabilities, and the line is the cutoff.
- Tokens kept
- 3 of 6
- Cutoff
- 0.0605
- Top token
- 0.67
- Entropy
- 1.20 bits
Min-p keeps every token whose probability is at least times the top token's:
is token 's probability, is the top token's, and is the base you pick. A sure model raises the cutoff, and an unsure one lowers it. Switch the prompts above: the line always sits at a tenth of the top bar, so the sure prompt keeps 1 token and the torn one keeps all 6.
- Nguyen et al. proposed it, and tested of 0.05 and 0.1.
- Hugging Face and vLLM both expose it as
min_p, and they don't even agree on where it goes. Hugging Face applies it after top-p, vLLM before top-k and top-p. - Know the mechanism, and don't oversell it. A 2025 re-analysis by Schaeffer et al. found that the original evidence "fails to support claims that min-p improves quality, diversity, or a trade-off between quality and diversity."
In the editor, rows holds the scores for two prompts, and keep_min_p(logits, base) already has the probabilities. Set cut: base times each row's top probability, as a (B, 1) column. Return the logits with -inf wherever a token's probability is below its row's cut.
Speculative decoding: a small model guesses, the big one checks
Decoding is serial: one pass of the big model per token. Speculative decoding has a small draft model guess the next few tokens, then runs the big model once over all of them.
The draft guesses 4 tokens, and the big model rejects the 3rd. How many tokens does the round add?
The practice problem, start to finish
That's every piece the practice problem needs. It asks for the four levels from the start of the lesson, from a blank file, and the interviewer follows up after each one.
1.You write
logits * temperatureand call it with T = 2. What comes out?2.You sort the logits largest first and drop everything below
sorted_logits[..., k]. With k = 3 and no ties, how many tokens survive?3.Sorted probabilities are 0.5, 0.3, 0.15 and 0.05, and
top_pis 0.7. Which tokens form the nucleus?4.Your top-p code sorts the logits, masks the sorted tensor and returns it without scattering back. What do you sample?
5.
sample()callsfilter_logits()but then draws from(logits / temperature).softmax(-1). Withtop_k=3, the kept tokens hold 91% of the probability. How often does it draw a token top-k removed?
Practice
Sources (7)
- The Curious Case of Neural Text Degeneration · arXiv 1904.09751 · Apr 22, 2019
“The size of the sampling set will adjust dynamically based on the shape of the probability distribution at each time step.”
- Hierarchical Neural Story Generation · arXiv 1805.04833 · May 13, 2018
“The restriction of sampling from the 10 most likely candidates reduces the risk of these low-probability samples.”
- Reproducibility · PyTorch 2.15 documentation · May 14, 2026
“results may not be reproducible between CPU and GPU executions, even when using identical seeds”
- CTRL: A Conditional Transformer Language Model for Controllable Generation · arXiv 1909.05858 · Sep 11, 2019
“This penalized sampling works by discounting the scores of previously generated tokens.”
- Turning Up the Heat: Min-p Sampling for Creative and Coherent LLM Outputs · arXiv 2407.01082 · Jul 1, 2024
“a dynamic truncation method that adjusts the sampling threshold based on the model's confidence by using the top token's probability as a scaling factor”
- Min-p, Max Exaggeration: A Critical Analysis of Min-p Sampling in Language Models · arXiv 2506.13681 · Jun 16, 2025
“We conclude that evidence presented in the original paper fails to support claims that min-p improves quality, diversity, or a trade-off between quality and diversity.”
- Fast Inference from Transformers via Speculative Decoding · arXiv 2211.17192 · Nov 30, 2022
“they can all easily be cast into standard sampling from an adjusted probability distribution”