Sub topic 5
How sampling and temperature shape variability
This chapter assumes you have used a chat-based LLM assistant, can read short Python, and know that models are trained on large text collections. It also assumes you have read the earlier chapters on next-token prediction and on why fluent text is not the same as true text. Here you will see where the randomness in a model's output comes from, what the temperature setting does, and why this matters for spotting made-up answers.
From scores to a chosen token
At each step, a model does not pick a word directly. It produces one raw score for every token in its vocabulary. These raw scores are called logits. A logit is any real number, and a higher value means the model considers that token a better continuation.
Logits are not probabilities. They can be negative and they do not add up to 1. A function called softmax converts them into probabilities that are positive and sum to 1. After that, a decoding strategy chooses one token from that distribution. The chosen token is appended to the text, and the whole process repeats for the next token.
Two parts of this pipeline are under your control in most tools: the temperature, and the filter that decides which tokens are allowed to be picked. The model's learned knowledge is not under your control, and neither is its tendency to score a plausible-sounding falsehood highly.
Temperature
Temperature is a number that divides the logits before softmax. A temperature below 1 makes the gaps between scores larger, so the top candidate takes a bigger share of the probability. A temperature above 1 shrinks the gaps, so probability spreads out more evenly.
The following code applies this to three candidate tokens:
import math
def softmax(logits, temperature=1.0):
scaled = [x / temperature for x in logits]
m = max(scaled)
exps = [math.exp(x - m) for x in scaled]
total = sum(exps)
return [e / total for e in exps]
logits = [2.0, 1.0, 0.5]
print(softmax(logits, temperature=1.0))
print(softmax(logits, temperature=0.5))At temperature 1.0 the output is roughly [0.63, 0.23, 0.14]. At temperature 0.5 it is roughly [0.79, 0.11, 0.04]... more precisely, the top token rises to about 0.84 and the others fall to about 0.11 and 0.04. Run the code to see the exact values. The pattern is what matters: lower temperature concentrates probability on the leader.
Two details in the code are worth noting. Subtracting the maximum before calling exp does not change the result, because softmax is unchanged when you subtract the same constant from every score. It does prevent overflow when logits are large. Also, a temperature of exactly 0 would divide by zero, so real systems treat 0 as a special case meaning "always pick the highest-scoring token."
Greedy decoding
Greedy decoding always takes the single most probable token. It is what a temperature of 0 approximates. The output is mostly repeatable, but "repeatable" does not mean "correct." The model's most probable continuation can still be wrong. Greedy decoding only removes the dice roll. It does not add any fact-checking.
Greedy decoding can also be locally short-sighted. The best token at each step does not always lead to the best whole sentence, and greedy output is more prone to repetitive loops.
Higher temperature
Raising the temperature gives lower-ranked tokens a real chance of being chosen. That helps with brainstorming, naming, and fiction, where variety is the goal. It hurts in tasks with one right answer, because a rare token that happens to be a wrong date or a wrong name can be selected, and then every following token is conditioned on that mistake.
Truncation filters: top-k and top-p
Even at moderate temperature, the long tail of very unlikely tokens adds up. Filters cut that tail before sampling.
- Top-k keeps only the k highest-probability tokens, then renormalizes. With k = 40, only 40 candidates can ever be chosen.
- Top-p (also called nucleus sampling) keeps the smallest set of tokens whose probabilities add up to at least p, such as 0.9. The number of candidates changes from step to step. When the model is sure, the set may hold one token. When it is unsure, the set may hold hundreds.
| Setting | What it controls | Lower value means | Typical risk if set too high |
|---|---|---|---|
| Temperature | Sharpness of the distribution | More deterministic output | Odd or wrong tokens get chosen |
| Top-k | Fixed number of candidates | Fewer allowed candidates | Long tail of weak candidates |
| Top-p | Cumulative probability mass kept | Fewer allowed candidates | Long tail of weak candidates |
These settings interact. A low temperature combined with a low top-p is very conservative. Many tools recommend changing one at a time so you can tell which one caused a change in behavior.
Why one wrong token can snowball
Generation is autoregressive: each new token becomes part of the context for the next one. This has a direct consequence for fabrication. Suppose you ask for the year a bridge opened and the sampler picks "1887" when the model's best guess was "1889". The next tokens are now conditioned on text that says 1887. The model does not go back and compare against its alternatives. It continues fluently from what is already written.
So variability is not just cosmetic. A single early divergence can produce a different, internally consistent, and equally confident passage. That is one reason two runs of the same prompt can give different "facts" in the same polished tone.
Using variability as a signal
The distribution has a useful property. When the model has learned a fact well, probability mass concentrates on one answer, and repeated samples agree. When the model has a gap in its knowledge, probability is spread over several plausible answers, and repeated samples disagree. This is the basis for the self-consistency check developed in a later chapter. Here is the core idea in code:
from collections import Counter
def agreement(answers):
normalized = [a.strip().lower().rstrip(".") for a in answers]
value, count = Counter(normalized).most_common(1)[0]
return value, count / len(normalized)
samples = ["1889", "1889.", "1887", "1889", "1901"]
print(agreement(samples))This prints ('1889', 0.6). Three of five samples agree after normalization, which strips whitespace and trailing periods and lowercases. Low agreement suggests the model is guessing.
To collect samples you need a temperature above 0. At temperature 0 every run returns the same answer, so there is nothing to compare.
Common errors when reasoning about temperature
- "Temperature 0 stops hallucination." It stops randomness in the sampler. The most likely continuation can still be a fabrication, and it will be repeated identically every time, which can make it look more trustworthy.
- "Temperature 0 is always identical." In practice, hosted models can still vary slightly between runs. Floating-point arithmetic on parallel hardware, batching, and model updates can change tiny score differences, and a near-tie between two tokens can flip. Treat determinism as approximate unless the provider states otherwise.
- "High temperature is what makes it lie." Temperature adds noise to an already imperfect distribution. A model with a knowledge gap fabricates at low temperature too. Higher temperature raises the odds of picking a less likely continuation, which often makes errors more frequent, but it is not the root cause.
- "One sample is the model's answer." One sample is a single draw from a distribution. Judging the model from one draw hides how uncertain it was.
- Changing several settings at once. If you lower temperature and top-p together and the output improves, you do not know which change mattered.
Practical guidance
- For factual lookups, extraction, and code, use low temperature. This reduces avoidable variation. You still need to verify the content.
- For creative tasks, use moderate or higher temperature, and accept that details will not be reliable facts.
- When checking a factual claim by sampling, use a moderate temperature, such as 0.7 to 1.0, and take several samples. Compare the final answers, not the wording.
- Compare answers after normalizing format. "1889" and "1889." are the same answer, as the code above shows. Free-text answers may need a person or a second model call to decide whether they match.
- Record the settings you used. A result that cannot be reproduced under known settings is hard to debug.
Summary
A model turns logits into probabilities with softmax, and a decoding strategy picks one token. Temperature sharpens or flattens that distribution. Top-k and top-p remove unlikely candidates. Because each chosen token shapes everything after it, small differences in sampling can produce different confident answers. Disagreement across samples is a warning sign of a knowledge gap. Agreement is weaker evidence, and temperature 0 does not guarantee truth.
Exercise
You ask a model for the founding year of a small company. At temperature 0 it answers "1994" three times in a row. At temperature 1.0 you sample ten times and get "1994" four times, "1996" three times, and "1991" three times. What does each result tell you, and can you conclude that 1994 is correct?
Show answer
The temperature 0 result only shows that 1994 is the single most probable continuation. Repeating it three times adds no information, because the sampler removed all randomness. The temperature 1.0 result shows the model's distribution is spread over several years, with agreement of only 0.4 for 1994. That points to a knowledge gap and a likely guess. You cannot conclude 1994 is correct. It is the model's top guess, and you should check it against a primary source such as the company's registration record or official website.
Exercise
A colleague says, "We set temperature to 0, so our summaries cannot contain made-up facts." Give two reasons this is wrong.
Show answer
First, temperature 0 removes sampling randomness but does not change what the model scores highly, so the most likely continuation can still be a fabrication. Second, outputs at temperature 0 can still differ slightly across runs because of hardware and serving details, and a repeated error can look more credible because it is consistent. Summaries still need to be checked against the source text.