One model, three decoders. Greedy repeats “the cat sat on” forever. Temperature 1.5 takes about half its words from the junk tail. Temperature 0.8 with top-p 0.9 takes about 1 in 200.
Pick a decoder, then press Generate. Each step, watch which tokens the decoder keeps and which one it picks. Then we build, piece by piece, softmax, temperature, top-k, top-p, min-p, beam search and the repetition penalties.
You need what a probability is and a little Python. We build the rest from zero.
An illustrative toy bigram model: 17 words, each with 2 to 5 likely next words, plus 20 junk tokens and every other word at a low logit of −1.5. Averaged over the 17 words, the tail holds 47% of the probability at temperature 1.5 and 0.5% after temperature 0.8 and top-p 0.9. Red words are off-context.
Chapter 0
See that a model returns a probability for every token, and that a separate rule picks the word
You type “The capital of France is”. The model does not answer with a word. It returns one probability for every token it knows. A token is a piece of text the model reads and writes, often a word or part of a word. GPT-2 knows 50,257 of them.
Something else must turn that list into one token. That rule is the decoder, and choosing the rule is decoding. Text comes out of a loop:
Teal bars are next-token probabilities. Choose a context. Press Greedy to take the tallest bar, or Sample 20 to draw 20 tokens at random by their odds.
Both distributions are illustrative. “Other” collects every token outside the top few.
On the confident context, greedy and sampling agree 9 times in 10. On the open context, the top token holds only 14%. Greedy then gives the same story every time, and sampling gives a new one each run.
So decoding is a trade between two failures:
| Decoder | Text | Risk |
|---|---|---|
| Always the top token | safe, the same each run | loops on long output |
| Sample from everything | varied | picks junk from the tail |
| Reshape, cut, then sample | varied and on topic | knobs to set |
The failure. Symptom: a chatbot repeats one sentence until it hits its length limit. Measure: count repeated 4-word sequences in a batch of outputs. Fix: change the decoder, not the model. Chapters 3 to 8 give the tools.
Chapter 1
Turn raw scores into odds with softmax, and see why it exaggerates the leader
The model's last layer does not output probabilities. It outputs one raw score per token, called a logit. A logit can be any real number: 8.2 for “Paris”, −1.5 for “banana”. Only the gaps between logits matter.
We need numbers that are positive and add up to 1. Call the logit of token i zi and its probability pi. Make each logit positive with the exponential, e to the z. Then divide by the total.
P-i equals e to the z-i, divided by the sum over j of e to the z-j.
Raise e to each logit z-j. Add the results. Divide each one by that total. The result p-i is positive and all of them add to 1.
With made-up logits 2.0, 1.0 and 0.1: e to each is 7.39, 2.72 and 1.11. The total is 11.21. So the probabilities are 0.659, 0.242 and 0.099. A gap of 1 in logit became odds of almost 3 to 1.
Blue bars are logits, drawn from a zero line. Teal bars are the probabilities. Drag a slider, then press Add 5 to every logit.
The logit of C stays at 0.1. The numbers are the worked example above.
Adding 5 to every logit moves the blue bars and leaves the teal bars still. Every e to the z gets the same factor, e to the 5, and the division cancels it.
Code uses that fact. A logit of 1,000 makes e to the z overflow to infinity, and infinity over infinity is NaN.
pythonimport numpy as np def softmax(z): # z: logits, shape (vocab,) e = np.exp(z - z.max()) # shift so the largest is 0: no overflow return e / e.sum() # shape (vocab,), sums to 1
The failure. Symptom: NaN probabilities, and the sampler crashes or always picks token 0. Measure: check np.isfinite(p).all(). Fix: subtract the largest logit before the exponential. The answer does not change.
Chapter 2
Take the top token every step, and watch a repeated phrase feed itself
The simplest decoder picks the token with the highest probability, every step, with no chance involved. This is greedy decoding. For “2 + 2 =” it gives “4” every time, which is what you want.
On long, open text it fails. Holtzman and colleagues (2019) measured why: the probability of a repeated phrase rises with each repetition (their Figure 4). Each copy enters the text, the model sees it, and the next copy gets more likely. Greedy always takes the top token, so once a loop leads, greedy never leaves.
The text ends with “I don't know.” The bars are the odds of the next word. Red “I” starts the loop again. Step with Greedy, then reset and step with Sample.
An illustrative toy: each repetition adds 0.9 to the logit of “I”. The rising shape follows Holtzman et al., Figure 4; the numbers are made up.
Work the toy. “I” starts with probability 0.29, the largest, so greedy picks it. After one repeat it has 0.50, then 0.71, 0.86 and 0.94.
A sampler escapes at each step with the leftover chance. The chance that it stays through six steps is 0.29 × 0.50 × 0.71 × 0.86 × 0.94 × 0.97, which is 0.08. Sampling escapes 92% of the time. Greedy escapes 0% of the time.
The same paper scored each token of human writing and of beam-searched text by the model's own probability (Figure 2). Machine text stays high and flat. Human text jumps around, with many low-probability words. People do not pick the most likely word. A good decoder adds the right amount of chance.
Greedy has a second flaw: it cannot see ahead. A first token with lower probability can lead to a more likely sentence. Chapter 7 fixes that with beam search.
The failure. Symptom: the same phrase repeats until the length limit. Measure: the share of 4-word sequences in an output that appear more than once. Fix: sample (Chapters 3 to 6) or penalize repeats (Chapter 8).
Chapter 3
Divide every logit by one number, and sharpen or flatten the whole distribution
A writing assistant should be sure on facts and loose on poems. One knob does both. Call it the temperature T, a positive number. Divide every logit zi by T before the softmax.
P-i equals e to the z-i over T, divided by the sum over j of e to the z-j over T.
Divide each logit z-i by T. Then run softmax as before. A small T stretches the gaps between logits, so the leader takes more. A large T shrinks the gaps, so the tail gets more.
The logits 2.0, 1.0, 0.1 give 0.659, 0.242, 0.099 at T = 1. At T = 0.5 they become 4.0, 2.0, 0.2, and the probabilities 0.864, 0.117, 0.019. At T = 2 they become 1.0, 0.5, 0.05, and the probabilities 0.502, 0.304, 0.194. The last token's chance doubles at T = 2.
Purple bars are the probabilities at your temperature. The dashed outlines are T = 1. Slide T from near 0 to 2.5.
Illustrative logits for “The weather today is”. “banana” and “purple” stand for the junk tail.
The limits make sense. As T goes to 0, the top token takes all the probability: that is greedy. As T grows large, every token gets the same chance. Code must treat T = 0 as greedy, because you cannot divide by zero. Hugging Face and the OpenAI API both default to T = 1, the model's own distribution.
The failure. Symptom: at high T, sentences drift into odd words and broken grammar. Measure: the share of sampled tokens that fall outside the top 10 by probability. Fix: lower T, or keep T and cut the tail (Chapters 4 to 6).
Chapter 4
Cut every token below rank k, then share the leftover probability among the rest
Temperature never removes the tail. Say 50,000 tail tokens hold 0.000001 each. Together they hold 5% of the probability. One draw in 20 lands there, and one bad word can wreck a sentence.
Top-k sampling keeps only the k most likely tokens. Call that set K. Every other token gets probability 0. The kept probabilities pi no longer add to 1, so divide each by their sum.
P-prime-i equals p-i divided by the sum over j in K of p-j, for every token i in K.
Sort the tokens by p. Keep the first k as the set K. Add their probabilities. Divide each kept p-i by that sum to get p-prime-i. Sample from those.
With made-up probabilities 0.46, 0.25, 0.15, 0.08, 0.04, 0.02 and k = 3: the kept sum is 0.86. So p-prime is 0.46 / 0.86 = 0.535, then 0.291 and 0.174. The sampler can never draw the last three tokens.
Teal bars survive, scaled up to add to 1. Grey bars are cut. The yellow line is the cut at rank k. Change k, then change the shape.
Illustrative distributions. Medium is the worked example above.
The weakness shows on the other shapes. On the peaked shape, k = 3 keeps two tokens at 0.04 and 0.02 that should go. On the flat shape, k = 3 cuts nine tokens that are almost as good as the top one. A fixed count cannot follow the shape. Hugging Face uses k = 50 when sampling, unless the model sets its own value.
The failure. Symptom: a fixed k gives junk on easy steps and dull text on open steps. Measure: log the kept probability mass at each step; with a good cut it should stay near the same value. Fix: cut by mass instead (Chapter 5).
Chapter 5
Add tokens from the top until their probability reaches p, and let the set resize itself
Holtzman and colleagues proposed a cut that follows the shape: nucleus sampling, also called top-p sampling. Fix a share of probability p, such as 0.9. Keep the smallest set of top tokens whose probabilities add up to at least p. That set is the nucleus, V(p).
The sum over x in V-of-p of P-of-x is at least p, where V-of-p is the smallest set that does this.
Sort tokens by P-of-x. Add them from the top. Stop at the first token where the running sum reaches p. Those tokens are V-of-p. Renormalize them as in top-k and sample.
The same probabilities 0.46, 0.25, 0.15, 0.08, 0.04, 0.02 with p = 0.9: the running sums are 0.46, 0.71, 0.86, 0.94. The sum first reaches 0.9 at the fourth token, so V-of-p has 4 tokens. Divide by 0.94: 0.489, 0.266, 0.160, 0.085.
The strip on top stacks the probabilities from the left; the yellow line marks p. Teal tokens are in the nucleus. Keep p = 0.9 and change the shape.
The same illustrative distributions as Chapter 4.
At p = 0.9 the peaked shape keeps 1 token, because 0.91 alone reaches the line. The flat shape keeps 11 of 12. Same p, a different set size at every step. The paper ran its experiments with p = 0.95 on GPT-2 Large.
Top-p and top-k can run together: top-k caps the count, then top-p trims by mass. Hugging Face and the OpenAI API both default to p = 1, which cuts nothing.
The failure. Symptom: at high temperature, top-p text still drifts. Measure: count the nucleus size; it climbs toward the whole tail. The cause: high T makes the tail fat, so reaching 90% takes many junk tokens. Fix: Chapter 6.
Chapter 6
Keep a token only if it is a fair fraction as likely as the top token, even at high temperature
You want varied text, so you raise the temperature to 2. Top-p 0.9 now lets in dozens of junk tokens. Min-p sampling (Nguyen and colleagues, ICLR 2025) uses a different test. Call the probability of the top token pmax and pick a fraction pmin. Keep token i only if its probability pi passes a floor.
Keep token i if p-i is at least p-min times p-max.
Find the top probability p-max. Multiply it by p-min to get the floor. Drop every token whose p-i is below the floor. Renormalize the rest and sample.
With made-up logits 3.0, 2.2, 1.5, 0.5 and 40 junk tokens at −2.0, at T = 2: p-max is 0.175, so with p-min = 0.1 the floor is 0.0175. Each junk token has 0.0144, under the floor, so min-p keeps the 4 good tokens. Top-p 0.9 at the same T keeps 38 tokens, and 34 of them are junk.
Four labelled tokens, then 40 thin junk bars. Raise T. Compare the cuts: the yellow line is the min-p floor.
Illustrative logits, the worked example above.
The floor scales with the leader. When the model is sure, p-max is high and the floor is strict. When it is unsure, the floor drops and more tokens pass. Junk stays far below the leader at any T, so it stays out.
The Mode Collapse lesson uses this exact knob: min-p 0.1 at temperature 2, to ask whether more randomness makes models give more varied answers.
The failure. Symptom: p-min near 0.5 makes text as flat as greedy. Measure: the average number of kept tokens per step; near 1 means you sampled nothing. Fix: stay in the 0.01 to 0.2 range.
Chapter 7
Keep the B best partial sentences at every step, and find what greedy cannot see
Greedy commits to each token before it sees what follows. Beam search keeps several partial sentences alive. The number it keeps is the beam width B. Each step, it extends every kept sentence by every next token, scores them all, and keeps the best B.
The score of a sentence y is its probability: the product of the probability of each token yt given the tokens before it, y<t. A product of many small numbers underflows to 0, so code adds logarithms instead.
Score of y equals the sum over t of the log of p of y-t given y-before-t.
For each token y-t in the sentence, take the log of its probability. Add them up. That is score of y. Beam search keeps the B sentences with the highest scores.
With made-up odds: greedy takes “cat” at 0.45, then “sat” at 0.40. Its score is −0.799 + (−0.916) = −1.715, a probability of 0.18. “dog” at 0.40, then “barked” at 0.85, scores −0.916 + (−0.163) = −1.079, a probability of 0.34. A beam of 2 finds it.
Each box shows a token and the score of the sentence so far. Teal boxes stay, grey boxes drop out, the warm path wins. Pick B and press Expand twice.
Illustrative probabilities, the worked example above.
Every added token adds a negative number, so the raw score prefers short outputs. Hugging Face divides the score by the length raised to a length_penalty to offset that.
Beam search suits tasks with one right answer, such as translation, where the input fixes the output. For open writing it makes the bland, looping text of Chapter 2. Test-Time Scaling uses beam search over reasoning steps, scored by a reward model instead of by probability.
The failure. Symptom: a wider beam gives shorter, more generic answers. Measure: average output length and repeated 4-word sequences as B grows. Fix: sample for open text; for closed tasks, add a length penalty.
Chapter 8
Lower the logits of tokens that already appeared, and break the loop at its source
Chapter 2's loop grows because a repeated token gets more likely. A penalty pushes back: it lowers the logit of every token that already appears in the text. There are two common forms.
The repetition penalty comes from the CTRL paper (Keskar and colleagues, 2019). Call it θ, a number above 1. For each token already in the text, take its logit z.
Z-prime equals z over theta if z is above zero, and z times theta if not.
If the logit z is positive, divide it by theta. If it is negative, multiply it by theta. Both moves push z down. The count does not matter: one appearance or ten get the same penalty.
With theta = 1.2: a logit of 2.0 becomes 2.0 / 1.2 = 1.667. A logit of −1.0 becomes −1.2. Dividing a negative logit would raise it, which is why the rule splits on the sign.
The second form has two knobs, as in the OpenAI API. Call the count of a token c. The frequency penalty αf grows with c. The presence penalty αp is paid once if c is above 0.
Z-prime equals z, minus c times alpha-f, minus alpha-p times one if c is above zero.
Subtract alpha-f once for each of the c appearances. Subtract alpha-p once more if c is above 0. A word said often drops far; a word said once drops a little.
With made-up values: “the” has logit 2.0 and c = 3. With alpha-f = 0.5 and alpha-p = 0.5, z-prime is 2.0 − 1.5 − 0.5 = 0.0. Its probability among four tokens falls from 0.455 to 0.123.
Pink marks a penalized token, with its count. Dashed outlines are the odds before any penalty. Move the three sliders.
Illustrative logits: the 2.0 (seen 3 times), cat 1.5, a 1.0 (seen once), sky 0.5. The sliders stack: repetition first, then frequency and presence.
Two details from real code. OpenAI documents both knobs from −2 to 2, default 0, and describes only their direction; the subtraction above is the common way to build them. Hugging Face's repetition penalty also counts the prompt's tokens, unless you set prompt_ignore_length.
The failure. Symptom: odd synonyms, or code that renames its own variables. A strong penalty also hits words the text must repeat. Measure: compare outputs at penalty 1.0 and at your setting on a task with a right answer. Fix: keep theta near 1.2, or the OpenAI knobs well under 1.
Chapter 9
Run every knob in the order a library applies them, and draw a hundred tokens
A real sampler is a chain of steps on one logit vector. Hugging Face's generate builds it in this order:
The order matters. Temperature runs before the cuts, so it decides how fat the tail is before any cut sees it. That is why top-p fails at high T and min-p does not. Other libraries may order the steps differently; check before you compare settings.
Bars are the final odds after every step; grey bars are cut. Set the knobs, then press Sample 100. Warm ticks count the draws.
Illustrative logits for “The weather today is”; the last three tokens stand for the junk tail. Draws are random.
Three runs teach the chain:
The failure. Symptom: two teams report different results for “the same settings”. Measure: print the full chain, its order and each value, from both runs. Fix: pin every knob and the library version in the experiment log.
Chapter 10
Keep the terms, the numbers, the settings and the code in one place
The model gives logits. Penalties push repeats down, temperature sets the spread, a cut removes the tail, and a draw picks the token. Beam search replaces the draw when one right answer exists.
| Term | What it does | Number from this page |
|---|---|---|
| Softmax | ezi / Σj ezj | 2.0, 1.0, 0.1 → 0.659, 0.242, 0.099 |
| Greedy | the top token every step | loop odds 0.29 → 0.94 in four repeats |
| Temperature | divide logits by T | T = 0.5: 0.864; T = 2: 0.502 |
| Top-k | keep the k most likely, renormalize | k = 3 keeps 0.86, gives 0.535 |
| Top-p | smallest top set with mass ≥ p | p = 0.9 keeps 4 tokens (0.94) |
| Min-p | keep pi ≥ pmin · pmax | T = 2: floor 0.0175, keeps 4 of 44 |
| Beam search | keep the B best by Σ log p | −1.079 (0.34) beats greedy −1.715 (0.18) |
| Repetition penalty | z/θ if z > 0, else z·θ | θ = 1.2: 2.0 → 1.667 |
| Frequency, presence | z − c·αf − αp·[c > 0] | 2.0 → 0.0; odds 0.455 → 0.123 |
| Where | Defaults |
|---|---|
Hugging Face GenerationConfig | temperature 1.0, top_k 50, top_p 1.0, repetition_penalty 1.0, num_beams 1, unless the model's own config sets them |
| OpenAI chat API | temperature 1 (range 0 to 2), top_p 1, frequency and presence penalty 0 (range −2 to 2) |
| Min-p | off; Hugging Face suggests 0.01 to 0.2 |
| Nucleus paper | ran p = 0.95 on GPT-2 Large |
A starting point, not a rule. Use greedy or a low temperature for code and maths with one answer. Use a temperature near 1 with min-p or top-p for open writing. Use beam search for translation. Tune on your own outputs.
pythonimport numpy as np rng = np.random.default_rng(0) def sample(z, counts, T=1.0, k=0, p=1.0, min_p=0.0, theta=1.0): z = z.astype(float).copy() # z: logits (vocab,), counts: (vocab,) seen = counts > 0 z[seen] = np.where(z[seen] > 0, z[seen] / theta, z[seen] * theta) if T == 0: return int(np.argmax(z)) # greedy q = np.exp((z - z.max()) / T); q /= q.sum() # softmax with temperature order = np.argsort(-q) if k > 0: q[order[k:]] = 0; q /= q.sum() # top-k if p < 1: cum = np.cumsum(q[order]) n = np.searchsorted(cum, p) + 1 # first index where the sum reaches p q[order[n:]] = 0; q /= q.sum() # top-p if min_p > 0: q[q < min_p * q.max()] = 0; q /= q.sum() # min-p return int(rng.choice(len(q), p=q))
Tokenization (where the token IDs come from) · The Transformer (where the logits come from) · Mode Collapse (temperature and min-p against near-identical answers) · Test-Time Scaling (best-of-N and beam search with a verifier) · Test-Time Compute · Speculative decoding · LLM inference (making the loop fast)
Sources: Holtzman, Buys, Du, Forbes and Choi, “The Curious Case of Neural Text Degeneration” (ICLR 2020, arXiv); Nguyen and colleagues, “Turning Up the Heat: Min-p Sampling for Creative and Coherent LLM Outputs” (ICLR 2025, arXiv); Keskar and colleagues, “CTRL” (2019, arXiv); Meister and colleagues, “Locally Typical Sampling” (arXiv), another cut that Hugging Face offers as typical_p; the Hugging Face generation docs.
Now press Present or Teach and explain from memory: softmax, temperature, the three cuts, beam scores and the two penalties. Then go back to the hero, run all three decoders, and say which chapter explains each result.