From scores to chances
The last layer of a model gives one number for every token in its vocabulary. These raw scores are called logits. They can be any size, positive or negative. To turn them into chances that add up to 100 %, the model uses softmax: raise e (about 2.718) to the power of each score, then divide each result by the total.
logits: blue 4.0, clear 2.6, grey 2.1, dark 1.8, full 1.2, falling 0.2Real models give 128,256 of these; six are enough to see the idea.
e⁴·⁰ = 54.6, e²·⁶ = 13.5, e²·¹ = 8.2, e¹·⁸ = 6.1, e¹·² = 3.3, e⁰·² = 1.2Every result is positive, and bigger scores grow much faster.
total = 86.8Add them up.
blue = 54.6 ÷ 86.8 = 62.9 %Then clear 15.5 %, grey 9.4 %, dark 7.0 %, full 3.8 % and falling 1.4 %.
Now the program that runs the model, not the model itself, has to pick one token. Everything in this lesson happens in that program, after the model has done its work. None of it changes the weights, and all of it can be set per request.
Greedy: always take the top token
The simplest rule is greedy decoding: always take the token with the highest chance. It is fast and predictable, and good for short, factual answers, classification and filling in forms.
For longer text it often goes wrong. In 2019, researchers at the University of Washington showed that text chosen by always going for the most likely words is “bland and strangely repetitive”: models fall into loops, saying the same sentence again and again, because each repeat makes the next one more likely. Reasoning models are especially prone to this. The Qwen3 model card warns in bold: do not use greedy decoding in thinking mode, as it can cause endless repetition.
An older method, beam search, keeps several partial replies at once and picks the one with the best total score. It was standard in machine translation, but it is rarely used for chat: it is slow and it makes the dullness problem worse.
Temperature
Temperature divides every logit by a number T before softmax. A T below 1 makes the gaps between scores bigger, so the favourite gets even more likely. A T above 1 makes them smaller, so the chances even out.
pᵢ = e^(zᵢ ÷ T) ÷ Σⱼ e^(zⱼ ÷ T)zᵢ is the logit of token i. T = 1 leaves the model’s own chances unchanged.
| T = 0.5 | T = 1 | T = 2 | |
|---|---|---|---|
| blue | 90.9 % | 62.9 % | 38.3 % |
| clear | 5.5 % | 15.5 % | 19.0 % |
| grey | 2.0 % | 9.4 % | 14.8 % |
| dark | 1.1 % | 7.0 % | 12.7 % |
| full | 0.3 % | 3.8 % | 9.4 % |
| falling | less than 0.1 % | 1.4 % | 5.7 % |
As T gets closer to 0, sampling becomes greedy. Many APIs treat T = 0 as “always take the top token”.
Quick check
Cutting off the tail
Temperature changes the shape of the chances but keeps every token in play. Truncation methods remove the unlikely tokens completely, then share their chance among the ones that are left. Four are widely used:
| Rule | From | Weak spot | |
|---|---|---|---|
| Top-k | Keep the k most likely tokens | Facebook AI, 2018 | The same k whether the model is sure or unsure |
| Top-p (nucleus) | Keep the fewest tokens whose chances add up to p | University of Washington and AI2, 2019 | At high temperature, many poor tokens get in |
| Min-p | Keep tokens with at least min-p × the top token’s chance | Nguyen and others, 2024 | Needs a sensible top token; one more number to tune |
| Top-nσ | Keep tokens whose logit is within n standard deviations of the top logit | USTC, China, 2024 | Newer, so fewer tools offer it |
Top-nσ works on the logits before softmax, so its choice of tokens stays the same at any temperature. Its paper found it beat greedy decoding on reasoning tests.
threshold = 0.1 × 62.9 % = 6.3 %10 % of the top token’s chance.
keep: blue, clear, grey, darkfull (3.8 %) and falling (1.4 %) are below the threshold and removed.
when the model is unsure, the top chance is low, so the threshold dropsMore choices stay open exactly when there is no clear answer. That is the idea behind min-p.
Set top-k to 3, then try top-p at 0.8 and min-p at 0.2. Watch which tokens are cut. Then raise the temperature: the filters decide which tokens may be chosen, and temperature decides how evenly the chances are spread among them.
This interactive part needs JavaScript.
Which setting fits each task better?
-
Pulling dates and amounts out of invoices
Answer: Low temperature, tight filters
-
Brainstorming 20 names for a bakery
Answer: Higher temperature, looser filters
-
Answering a maths question with one right answer
Answer: Low temperature, tight filters
-
Writing a bedtime story with surprises
Answer: Higher temperature, looser filters
-
Writing a SQL query
Answer: Low temperature, tight filters
-
Writing different versions of a poem to choose from
Answer: Higher temperature, looser filters
Stopping the loops: penalties
Another set of tools pushes the model away from repeating itself, by lowering the scores of tokens it has already used.
- Repetition penalty (from the CTRL paper, 2019): makes the scores of tokens already in the text smaller. The paper found a value of about 1.2 a good balance.
- Frequency penalty: subtracts a little from a token’s score for every time it has already appeared.
- Presence penalty: subtracts a fixed amount from any token that has appeared at least once. Qwen3’s model card suggests 0 to 2 against endless repetition, but warns that high values can make the model mix languages.
- DRY (“don’t repeat yourself”), in llama.cpp: penalises tokens that would continue a sequence already seen, more strongly the longer the repeated sequence.
What the labs recommend
Most model cards say which settings the model was tested with. They differ a lot, so start from the card rather than from habit.
| Temperature | Top-p | Top-k | Notes | |
|---|---|---|---|---|
| Qwen3, thinking mode | 0.6 | 0.95 | 20 | Min-p 0. Do not use greedy decoding |
| Qwen3, non-thinking mode | 0.7 | 0.8 | 20 | Min-p 0 |
| DeepSeek-R1 | 0.6 (0.5 to 0.7) | 0.95 | – | Prevents endless repetition or incoherent output |
| Kimi K2 Instruct | 0.6 | – | – | |
| gpt-oss | 1.0 | 1.0 | – | The model’s own chances, unchanged |
| DeepSeek-V4 | 1.0 | 1.0 | – | For local deployment |
| llama.cpp defaults | 0.8 | 0.95 | 40 | Min-p 0.05. Used when you set nothing |
A dash means the card gives no value. Settings checked on 20 October 2026.
Forcing the format: constrained decoding
Programs often need the reply in an exact format, such as JSON with certain fields. Asking politely in the prompt usually works, but not always, and one missing bracket can break a program. Constrained decoding makes it certain: before each token is chosen, every token that would break the format has its chance set to zero.
- Turn the format (a JSON schema, a regular expression or a grammar) into a machine that tracks where in the format the reply is.
- Before each step, work out which tokens are allowed next. After
{"nights":, only digits are allowed. - Set the chance of every other token to zero, then sample as usual.
- Move the machine forward with the chosen token, and repeat.
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "booking",
"schema": {
"type": "object",
"properties": {
"city": {"type": "string"},
"nights": {"type": "integer"}
},
"required": ["city", "nights"]
}
}
}
- Add this to a chat request. The reply will always be an object with a
citytext and a whole number ofnights. - llama.cpp takes the same idea from the command line with
--json-schema, or any grammar with--grammar-file. - Libraries such as Outlines and XGrammar do the work inside vLLM and SGLang, fast enough that it costs very little.
Speculative decoding: the same answer, in fewer steps
The last lesson showed that decode is memory-bound: the GPU reads all the weights to produce a single token, and its maths units sit idle. Checking five tokens in one pass costs about the same time as writing one. Speculative decoding turns that idle power into speed.
- A small, fast draft model guesses the next few tokens, for example 4.
- The big model reads all 4 guesses in a single pass, like a tiny prefill, and computes its own chances at each position.
- Going from left to right, each guess is accepted with probability min(1, p ÷ q), where p is the big model’s chance for that token and q the small model’s. In greedy decoding this simply means: accept if the big model would have chosen the same token.
- At the first rejected guess, the big model picks the token itself, and the remaining guesses are thrown away. If all 4 are accepted, it adds a fifth token for free.
- Repeat from the new position.
The acceptance rule is chosen so that the final text follows exactly the big model’s own chances. Two teams found this at about the same time: Google in 2022 and DeepMind in 2023. Speculative decoding is not an approximation: the replies are as good as the big model’s, just faster.
expected tokens = (1 − aᵏ⁺¹) ÷ (1 − a)a is how often a guess is accepted, k how many tokens are guessed. From the Google paper.
a = 0.8, k = 4: (1 − 0.8⁵) ÷ 0.2 = 3.36Each pass of the big model gives 3.36 tokens on average instead of 1.
a = 0.85 to 0.9, k = 1: 1.85 to 1.9 tokens per passDeepSeek-V3’s built-in second-token predictor. DeepSeek measured 1.8 times the tokens per second.
Start with the defaults and write a reply. Then lower how often a guess is right to 50 %, and raise the number of guesses to 8: most guesses get thrown away. Find the settings that give the most tokens per pass.
This interactive part needs JavaScript.
| How it guesses | Example | |
|---|---|---|
| A small model from the same family | A separate model that shares the big model’s tokenizer | Qwen3-0.6B drafting for Qwen3-32B |
| Draft heads | A tiny network trained to read the big model’s own hidden states | EAGLE (2024), EAGLE-3 (2025) |
| Built-in predictors | Extra layers trained with the model to predict tokens further ahead (multi-token prediction) | DeepSeek-V3 and DeepSeek-V4 each have one such layer |
| Copying from the context | Look up text already in the prompt and guess that it comes next | llama.cpp’s n-gram modes, great when editing code |
EAGLE reported 2.7 to 3.5 times faster replies for LLaMA2-Chat 70B, and EAGLE-3 up to 6.5 times on some tasks. Gains are biggest on predictable text such as code, and shrink when a server is already busy with large batches.
llama-server -hf Qwen/Qwen3-32B-GGUF:Q4_K_M \
-hfd Qwen/Qwen3-0.6B-GGUF:Q8_0 \
--spec-type draft-simple \
--spec-draft-n-max 8
-hfdownloads the big model, and-hfdthe small draft model, from Hugging Face.--spec-draft-n-maxis the most tokens guessed per pass (the default is 3).- The server prints the draft acceptance rate. If it is low, guess fewer tokens or try another draft model.
Same question, different answer
With a temperature above 0, different replies to the same prompt are expected: that is the randomness doing its job. Many servers accept a seed, a number that fixes the random choices so a test can be repeated.
Surprisingly, even temperature 0 is usually not fully repeatable on a busy server. In September 2025, Thinking Machines asked Qwen3-235B the same question 1,000 times at temperature 0 and got 80 different replies. All of them were identical for the first 102 tokens, then split. The cause is the batch: other people’s requests change how many tokens the GPU processes together, which changes the order in which numbers are added, and floating-point addition gives slightly different results in different orders. Their fix, maths that gives the same result at any batch size, makes replies repeatable at some cost in speed.
Remember
- The model gives a score, a logit, to every token. Softmax turns the scores into chances that add up to 100 %.
- Greedy decoding takes the top token every time. It is good for short answers but causes loops in long text and in thinking.
- Temperature divides the logits by T: below 1 sharpens the chances, above 1 flattens them.
- Top-k, top-p, min-p and top-nσ cut off the unlikely tail. Penalties discourage repeats. Start from the model card’s settings.
- Constrained decoding sets the chance of format-breaking tokens to zero, which guarantees valid JSON, but not a correct answer.
- Speculative decoding lets a small model guess and the big model check several tokens in one pass. Same answers, often two to three times faster.
Words to know
- Logit
- The raw score a model gives each possible next token, before it is turned into a chance.
- Softmax
- The formula that turns a list of scores into chances that add up to 1.
- Greedy decoding
- Always choosing the single most likely next token.
- Temperature
- A number that sharpens (below 1) or flattens (above 1) the chances before a token is picked.
- Top-k
- Keep only the k most likely tokens.
- Top-p (nucleus)
- Keep the fewest tokens whose chances add up to p.
- Min-p
- Keep tokens whose chance is at least a set fraction of the top token’s chance.
- Repetition penalty
- Lowering the scores of tokens that have already appeared, to stop loops.
- Constrained decoding
- Allowing only the tokens that keep the reply in a required format.
- Speculative decoding
- A small model guesses several tokens and the big model checks them all in one pass.
- Draft model
- The small, fast model that makes the guesses in speculative decoding.
- Seed
- A number that fixes the random choices, so the same request gives the same reply.
Go to the source
This lesson is built on these papers and documents. Paper links open arxiv.org, a separate site.
-
The Curious Case of Neural Text Degeneration
Introduces top-p (nucleus) sampling. Figure 1 shows both failures on one prompt: beam search repeats itself, and sampling from every token turns into gibberish.
-
Hierarchical Neural Story Generation
The story-writing paper that made top-k sampling popular.
-
Turning Up the Heat: Min-p Sampling for Creative and Coherent LLM Outputs
Min-p, tested on models from 1B to 123B parameters, for both reasoning and creative writing.
-
Top-nσ: Not All Logits Are You Need
From USTC. Shows that logits split into a noisy part and an informative part, and filters on that.
-
CTRL: A Conditional Transformer Language Model for Controllable Generation
Section 4.1 introduces the repetition penalty most tools still use.
-
Efficient Guided Generation for Large Language Models
The Outlines paper: turns regular expressions and grammars into a fast index over the vocabulary.
-
Fast Inference from Transformers via Speculative Decoding
Google’s speculative decoding paper, with the acceptance rule and the formula for tokens per pass.
-
Accelerating Large Language Model Decoding with Speculative Sampling
DeepMind’s version of the same idea, tested on the 70B Chinchilla: 2 to 2.5 times faster.
-
EAGLE-3: Scaling up Inference Acceleration of Large Language Models via Training-Time Test
The draft-head method many servers now use. Read EAGLE (2401.15077) first if you can.
-
Defeating Nondeterminism in LLM Inference
Why temperature 0 still gives different answers, explained from floating-point addition upwards.
Check yourself
5 questions. Tap the answer you think is right.
0 of 5 answered
Lesson complete
Answer every question above to complete this lesson.
Your progress is saved on this device only.
Next lessonThe KV cache: a model’s working memory