Sampling and Temperature
The highest-scoring token is not the only token a model could produce. Sampling and temperature control how we choose from its predictions, changing the output without changing the learned weights.
10 sections · 9 questions · 4 coding challenges
The arrow keys move between sections too.
Why Does Always Choosing the Favourite Produce Dull Text?
BOTIE
Holtzman and colleagues examined this difficulty in work first released in 2019. They showed that decoding choices could strongly change text quality with the same underlying language model, and proposed nucleus sampling to retain a changing set of plausible candidates.
Temperature adjusts how concentrated the probability distribution is before sampling. A lower positive temperature emphasises the larger scores; a higher one spreads probability more broadly. Top-k and nucleus sampling instead restrict which candidates remain available. These controls change how we use the learned distribution. They do not add knowledge or make randomness a substitute for a well-trained model.
Sources for this history
Must a Model Always Choose Its Favorite Word?
Suppose a model thinks both The cat sat and The cat slept are plausible continuations. Always choosing the most probable token can repeat the same wording. Choosing any token equally would ignore what the model learned. We need a way to control how we select from its predictions.
Temperature changes how concentrated the probabilities are. A second control, top-p, restricts sampling to a group of likely candidates. Neither control trains the model or adds new knowledge.
Begin with more than one plausible choice
A prediction distribution divides probability among vocabulary tokens. Sampling draws from that distribution, so a less probable token can still be selected. A token's probability describes its share of repeated draws, not a guarantee about one draw.
Compare both controls on the same scores
The table below holds four logits fixed. It shows the temperature-scaled distribution, which candidates survive top-p, and the final probabilities.
Increasing variety is a selection preference. It does not measure creativity, correctness, or quality by itself.
Explore the full example
First move temperature while top-p stays at one. Then lower top-p and inspect which candidates are retained. The final column is the distribution a sampler would use.
Calculating the example…
Part 1. Distinguish Scores, Probabilities, and Choices
1. A score is not a probability
Three different things are easy to run together here. A model produces scores. The scores are turned into probabilities. A selection rule turns the probabilities into one chosen token. The controls in this lesson act on the second step, and they are easier to follow once the three are held apart.
A logit can be any finite real number. Softmax compares all vocabulary logits to produce nonnegative shares that total one. The absolute size of a score is less important than its difference from other scores.
The live example holds four candidates and their scores fixed. The candidate sat has a logit of 2, slept has 1, ran has 0 and sang has −1. None of those is a probability. They do not total one, and one of them is negative. Softmax turns them into the shares in the last column.
| candidate | logit | probability |
|---|---|---|
| sat | 2 | 0.6439 |
| slept | 1 | 0.2369 |
| ran | 0 | 0.0871 |
| sang | −1 | 0.0321 |
The live table at a temperature of one with top-p at one. Part 2 shows the arithmetic.
Only the gaps between the scores matter. Add 1,000 to every logit and the four probabilities come out the same, because each candidate is exactly as far from the others as before.
Sampling uses these shares to make a random selection. One draw can select a relatively unlikely token. Over many independent draws from an unchanged distribution, selection frequencies approach the assigned probabilities. In text generation, the distribution normally changes after every appended token.
Ten draws, then ten thousand
Drawing from the four shares above with one seeded random stream, the first ten selections were sat, sat, sat, sat, slept, ran, sat, slept, sat, ran. The candidate ran was drawn twice in ten with a share under nine percent, and sang was not drawn at all. Keep drawing from the same stream and the counts settle.
| draws | sat | slept | ran | sang |
|---|---|---|---|---|
| 10 | 6 | 2 | 2 | 0 |
| 100 | 57 | 24 | 14 | 5 |
| 1,000 | 620 | 261 | 86 | 33 |
| 10,000 | 6,404 | 2,436 | 838 | 322 |
| shares × 10,000 | 6,439 | 2,369 | 871 | 321 |
Counts of each candidate as the draws accumulate. The last row is what the shares predict for 10,000 draws.
A probability describes the long run of this table and promises nothing about its first row. Text generation rarely gets beyond the first row with any one distribution, because the next token is drawn from a new one.
2. Use temperature to control concentration
Temperature divides the logits before softmax. A low positive value magnifies score differences and makes the distribution more concentrated. A high value reduces their influence and makes the distribution more even.
| temperature | sat | slept | ran | sang |
|---|---|---|---|---|
| 0.1 | 1.0000 | 0.0000 | 0.0000 | 0.0000 |
| 0.5 | 0.8650 | 0.1171 | 0.0158 | 0.0021 |
| 1 | 0.6439 | 0.2369 | 0.0871 | 0.0321 |
| 2 | 0.4551 | 0.2760 | 0.1674 | 0.1015 |
| 3 | 0.3849 | 0.2758 | 0.1976 | 0.1416 |
The same four logits at five temperatures, from the lowest setting the control offers to the highest. Every row is in the same order.
Reading down a column shows what the control does. The favorite, sat, holds 0.8650 at a temperature of 0.5 and 0.3849 at 3. The least likely candidate, sang, moves the other way, from 0.0021 to 0.1416. The scores are the same in every row. What changes is how strongly the preference they express is acted on.
For finite logits, positive temperature preserves ranking. At very low temperature, sampling concentrates on the maximum-score choices. Greedy decoding is implemented separately here, so there is no division by zero.
Both statements are visible in the table. No row changes the order of the four candidates. And at 0.1 the favorite has everything to four decimal places, so sampling at that setting behaves like always taking the largest share, without a temperature of zero ever being needed.
Part 2. Calculate Temperature and Nucleus Filtering
3. Scale, exponentiate, and normalize
Let T be a strictly positive temperature, and let l contain the logits. Subtracting the maximum before exponentiating leaves the distribution unchanged and avoids overflow from large positive scores. The example holds the following four logits fixed.
l = [2, 1, 0, −1]
At T = 1:
shifted scores = [0, −1, −2, −3]
weights = [1, exp(−1), exp(−2), exp(−3)]
probabilities = weights / sum(weights)
In general:
pᵢ = exp((lᵢ − max(l)) / T)
/ Σⱼ exp((lⱼ − max(l)) / T)The table calculates the normalized probabilities. The same scores and vocabulary remain in place while the temperature changes.
Three temperatures, evaluated
The shifted scores are divided by the temperature, each result is exponentiated into a weight, and each weight is divided by the sum of the four.
T = 1: shifted scores / T = [0, −1, −2, −3]
weights ≈ [1, 0.3679, 0.1353, 0.0498], sum ≈ 1.5530
probabilities ≈ [0.6439, 0.2369, 0.0871, 0.0321]
T = 0.5: shifted scores / T = [0, −2, −4, −6]
weights ≈ [1, 0.1353, 0.0183, 0.0025], sum ≈ 1.1561
probabilities ≈ [0.8650, 0.1171, 0.0158, 0.0021]
T = 2: shifted scores / T = [0, −0.5, −1, −1.5]
weights ≈ [1, 0.6065, 0.3679, 0.2231], sum ≈ 2.1975
probabilities ≈ [0.4551, 0.2760, 0.1674, 0.1015]Dividing by a temperature below one stretches the gaps between the shifted scores, and dividing by a temperature above one shrinks them. The largest score always shifts to zero and keeps a weight of exactly one, so what temperature sets is how small the other weights are beside it.
The logits of sat and slept are one apart, so the ratio of their probabilities is exp(1 / T). That is about 7.39 at a temperature of 0.5, 2.72 at 1 and 1.65 at 2. It stays above one at every positive temperature, which is the ranking being preserved.
The subtraction earns its place when scores are large. With every logit raised by 1,000, exponentiating directly overflows and the division has nothing finite to work with. The shifted calculation returns the same four probabilities as before.
4. Retain enough candidates to reach the threshold
Top-p, also called nucleus sampling, orders tokens by probability. Keep the smallest prefix whose cumulative probability reaches the threshold. Retain the token that crosses it, remove later tokens, and normalize again.
Using the assigned distribution from the guided illustration gives a simple calculation:
Sorted probabilities = [0.50, 0.30, 0.15, 0.05]
Top-p threshold = 0.80
First candidate: cumulative probability = 0.50
Second candidate: cumulative probability = 0.50 + 0.30 = 0.80
Retained shares = [0.50, 0.30]
Final distribution = [0.50 / 0.80, 0.30 / 0.80, 0, 0]
= [0.625, 0.375, 0, 0]These illustrative shares differ from the live table's softmax values. They show the filtering arithmetic without rounding ambiguity. A fixed top-p threshold can retain many tokens for an uncertain distribution and very few for a concentrated one.
The same filter on the live table
At a temperature of one the live table’s probabilities are already in descending order, so the running total can be read straight down.
| candidate | probability | cumulative probability |
|---|---|---|
| sat | 0.6439 | 0.6439 |
| slept | 0.2369 | 0.8808 |
| ran | 0.0871 | 0.9679 |
| sang | 0.0321 | 1.0000 |
A threshold of 0.80 is not reached by sat alone and is reached once slept is added, so two candidates are retained and their shares are divided by what the two hold together.
Retained shares = [0.6439, 0.2369], total = 0.8808
Final distribution = [0.6439 / 0.8808, 0.2369 / 0.8808, 0, 0]
≈ [0.7311, 0.2689, 0, 0]Moving the threshold along the control at this temperature, any setting up to 0.60 keeps sat alone, 0.65 to 0.85 keeps two candidates, 0.90 and 0.95 keep three, and only 1.00 keeps all four.
Now hold the threshold at 0.80 and move the temperature instead.
| temperature | probabilities after temperature | candidates retained | final distribution |
|---|---|---|---|
| 0.5 | [0.8650, 0.1171, 0.0158, 0.0021] | 1 | [1, 0, 0, 0] |
| 1 | [0.6439, 0.2369, 0.0871, 0.0321] | 2 | [0.7311, 0.2689, 0, 0] |
| 2 | [0.4551, 0.2760, 0.1674, 0.1015] | 3 | [0.5065, 0.3072, 0.1863, 0] |
One threshold and three different candidate sets. The more even the distribution, the further down the order the running total has to go.
This is the sense in which top-p adapts to the distribution, and it is also why the two controls have to be read together. Temperature is applied first, so it decides how many candidates a given threshold will reach.
Check yourself
Questions on Parts 1 and 2
Question 1 of 5
Raising the temperature can change which token the model scores highest.
Part 3. What the Controls Can and Cannot Do
5. Apply the selection policy explicitly
A selection policy is a short list of decisions, and each one changes the distribution the sampler finally draws from. Stating them in order is what makes a result repeatable and makes two results comparable.
The SDK applies temperature first and top-p second. Its stable sort preserves vocabulary order when probabilities tie. Passing a random generator into sample keeps ownership of the random stream explicit.
The code below asks for a temperature of 0.8 and a top-p of 0.9 on the page’s four logits, and then draws once from a seeded generator. Followed by hand, it goes like this.
After temperature 0.8: [0.7183, 0.2058, 0.0590, 0.0169]
Running total: 0.7183, then 0.9241
Retained: sat and slept
Final distribution: [0.7773, 0.2227, 0, 0]
Seeded draw: sleptThe order of the two controls changed the answer here. On the unscaled distribution a threshold of 0.9 is reached only at the third candidate, at 0.9679, so filtering first would have kept ran as well. The draw is worth a second look too. It selected slept, which held 0.2227 against 0.7773 for sat. The same policy with a different seed can return sat, and both are correct outputs of the policy.
import numpy as np
from oop_ml.numpy.modern import TokenDistribution
distribution = TokenDistribution.from_logits(
np.array([2.0, 1.0, 0.0, -1.0]),
temperature=0.8, top_p=0.9,
)
token_id = distribution.sample(np.random.default_rng(4))
print(distribution.probabilities)
print(token_id)6. Evaluate the resulting behavior
Lower temperature can reduce variation, but it cannot remove an error already favored by the model. Higher temperature can surface alternatives, including unsuitable ones. Neither should be treated as a direct correctness control.
When the favorite is the mistake
Suppose that for some prompt slept is the suitable continuation, and the model’s scores are the four on this page. Its favorite, sat, is then the mistake. The table follows the mistake, the suitable token and the two weakest candidates as the temperature moves.
| temperature | sat, the favored mistake | slept, the suitable token | ran or sang |
|---|---|---|---|
| 0.1 | 1.0000 | 0.0000 | 0.0000 |
| 0.5 | 0.8650 | 0.1171 | 0.0180 |
| 1 | 0.6439 | 0.2369 | 0.1192 |
| 2 | 0.4551 | 0.2760 | 0.2689 |
| 3 | 0.3849 | 0.2758 | 0.3392 |
The last column is the combined share of the two weakest candidates.
Lowering the temperature makes the output steadier and makes it steadily wrong. At 0.1 the mistake is selected essentially every time. Raising it does give slept more room, from 0.2369 to 0.2760 at a temperature of 2, and it gives the two weakest candidates far more, from 0.1192 to 0.2689. At 3 they are together more likely than slept.
At no setting does slept overtake sat, because temperature preserves ranking. Top-p cannot help either. It removes candidates from the bottom of the order, and this mistake sits at the top. Changing which token the model prefers takes a change to the scores, which means different context or different parameters.
A model's reported next-token probability, the probability after sampling adjustments, and the probability that an answer is factually correct are different quantities. Choose a policy by evaluating complete responses for the task.
This paper introduces nucleus sampling and studies how decoding choices affect generated text. The Curious Case of Neural Text Degeneration.
Continue with Supervised Fine-Tuning.
Check yourself
Questions on Part 3
Question 1 of 4
In what order does the SDK apply the two controls, and how are ties settled?
Try it with Botie
Build with Botie
Write and run Python