Availit World How AI really works, in your language

Lesson 24 of 4625 minFacts checked October 20, 2026

Sampling: how the next token is chosen

At the end of every step, a model does not give one answer. It gives a score to every token it knows, 128,256 of them for Llama 3.1, and then something has to choose. That choice is made again for every single token. It decides whether a reply is dull or lively, sensible or confused, and even whether it is valid JSON. It is also where one of the cleverest speed tricks lives: getting the same answer from a big model two or three times faster.

In this lesson you will

  • Turn a model’s scores into chances with softmax, by hand
  • Explain greedy decoding, temperature, top-k, top-p and min-p, and what each one is for
  • Choose settings for a task, and read the settings a model card recommends
  • Force a model to write valid JSON with constrained decoding
  • Explain speculative decoding, and why it gives exactly the same answers, faster
On this page
  1. From scores to chances
  2. Greedy: always take the top token
  3. Temperature
  4. Cutting off the tail
  5. Stopping the loops: penalties
  6. What the labs recommend
  7. Forcing the format: constrained decoding
  8. Speculative decoding: the same answer, in fewer steps
  9. Same question, different answer
  10. Remember
  11. Check yourself

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.

Softmax, for six tokens after “The sky is”
logits: blue 4.0, clear 2.6, grey 2.1, dark 1.8, full 1.2, falling 0.2

Real 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.2

Every result is positive, and bigger scores grow much faster.

total = 86.8

Add 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.

Softmax with temperature
pᵢ = e^(zᵢ ÷ T) ÷ Σⱼ e^(zⱼ ÷ T)

zᵢ is the logit of token i. T = 1 leaves the model’s own chances unchanged.

The same six tokens at three temperatures
T = 0.5T = 1T = 2
blue90.9 %62.9 %38.3 %
clear5.5 %15.5 %19.0 %
grey2.0 %9.4 %14.8 %
dark1.1 %7.0 %12.7 %
full0.3 %3.8 %9.4 %
fallingless 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

You raise the temperature from 0.7 to 1.5. What happens?

Show the answer

Answer: Unlikely tokens are chosen more often, so replies vary more and make mistakes more often Temperature only reshapes the chances. A higher T flattens them, which adds variety and also lets in more bad picks.

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:

Four ways to cut the tail
RuleFromWeak spot
Top-kKeep the k most likely tokensFacebook AI, 2018The same k whether the model is sure or unsure
Top-p (nucleus)Keep the fewest tokens whose chances add up to pUniversity of Washington and AI2, 2019At high temperature, many poor tokens get in
Min-pKeep tokens with at least min-p × the top token’s chanceNguyen and others, 2024Needs a sensible top token; one more number to tune
Top-nσKeep tokens whose logit is within n standard deviations of the top logitUSTC, China, 2024Newer, 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.

Min-p on the example (T = 1, min-p = 0.1)
threshold = 0.1 × 62.9 % = 6.3 %

10 % of the top token’s chance.

keep: blue, clear, grey, dark

full (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 drops

More choices stay open exactly when there is no clear answer. That is the idea behind min-p.

Try itAll the dials at once

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?

0 of 6 sorted
  • 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.

Recommended settings, from each model card
TemperatureTop-pTop-kNotes
Qwen3, thinking mode0.60.9520Min-p 0. Do not use greedy decoding
Qwen3, non-thinking mode0.70.820Min-p 0
DeepSeek-R10.6 (0.5 to 0.7)0.95–Prevents endless repetition or incoherent output
Kimi K2 Instruct0.6––
gpt-oss1.01.0–The model’s own chances, unchanged
DeepSeek-V41.01.0–For local deployment
llama.cpp defaults0.80.9540Min-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.

  1. Turn the format (a JSON schema, a regular expression or a grammar) into a machine that tracks where in the format the reply is.
  2. Before each step, work out which tokens are allowed next. After {"nights": , only digits are allowed.
  3. Set the chance of every other token to zero, then sample as usual.
  4. Move the machine forward with the chosen token, and repeat.
Asking a server for JSON that fits a schemajson
"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 city text and a whole number of nights.
  • 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.

  1. A small, fast draft model guesses the next few tokens, for example 4.
  2. The big model reads all 4 guesses in a single pass, like a tiny prefill, and computes its own chances at each position.
  3. 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.
  4. 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.
  5. 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.

Tokens per pass of the big model
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.36

Each 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 pass

DeepSeek-V3’s built-in second-token predictor. DeepSeek measured 1.8 times the tokens per second.

Try itGuess, check, repeat

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.

Where the guesses can come from
How it guessesExample
A small model from the same familyA separate model that shares the big model’s tokenizerQwen3-0.6B drafting for Qwen3-32B
Draft headsA tiny network trained to read the big model’s own hidden statesEAGLE (2024), EAGLE-3 (2025)
Built-in predictorsExtra 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 contextLook up text already in the prompt and guess that it comes nextllama.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.

Speculative decoding with llama.cppbash
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
  • -hf downloads the big model, and -hfd the small draft model, from Hugging Face.
  • --spec-draft-n-max is 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.

Check yourself

5 questions. Tap the answer you think is right.

0 of 5 answered

Logits are 2.0 for “yes” and 0.0 for “no”. Roughly what chance does softmax give “yes”?

Show the answer

Answer: About 88 % e² ≈ 7.39 and e⁰ = 1, so “yes” gets 7.39 ÷ 8.39 ≈ 88 %.

Why do reasoning models warn against greedy decoding?

Show the answer

Answer: It can trap the model in endless repetition Always taking the top token makes loops self-reinforcing, especially in long thinking.

With min-p = 0.1, the top token has a 30 % chance. Which tokens survive?

Show the answer

Answer: Those with at least 3 % The threshold is 0.1 × 30 % = 3 %.

What does constrained decoding guarantee?

Show the answer

Answer: That the reply follows the required format It removes tokens that would break the format. It cannot check facts.

Why does speculative decoding not make the answers worse?

Show the answer

Answer: The big model checks every token, and the acceptance rule keeps its own chances exactly Guesses only survive if the big model accepts them, and the rule is designed so the result matches the big model’s distribution.

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
Previous lesson All lessons

Choose your language