An LLM's temperature changes how probability is distributed among candidate tokens. It does not verify facts or turn a likely answer into a correct answer. top_p performs a different operation: it limits the candidate set based on their cumulative probability. To choose a configuration, it is useful to separate these two decisions and measure the result on your task.
This guide explains LLM temperature using four invented logits and Python code run on a CPU on November 23, 2026. It is a mathematical illustration of one generation step, not a test of a model, provider, or quality improvement. You will then find a protocol for evaluating your model without changing multiple parameters at once.
What temperature changes
A model produces scores for possible next tokens. For a positive temperature T, our example converts each score z into a probability using:
p(token i) = exp(z_i / T) / sum_j(exp(z_j / T))
Subtracting the maximum before calculating the exponentials preserves the result and avoids unnecessarily large numbers. In this example there are only four candidates; a real model uses its vocabulary and may apply other logit processors.
- A lower temperature concentrates mass on candidates that already had high scores.
- A higher temperature spreads more mass among other candidates.
- Temperature does not change the order of these four logits. It changes the relative distance between their probabilities.
Selecting a token affects the context of the next step. Therefore, a small initial difference can end up producing different texts; this one-step table does not predict the quality of a complete response.
Reproducible example: the same logits, three temperatures
We use the synthetic logits A=3, B=2, C=1, and D=0. The letters identify candidates, not good or bad answers. There is no truth label in this data.
| Temperature | A | B | C | D |
|---|---|---|---|---|
| 0.5 | 86.50% | 11.71% | 1.58% | 0.21% |
| 1.0 | 64.39% | 23.69% | 8.71% | 3.21% |
| 2.0 | 45.51% | 27.60% | 16.74% | 10.15% |
The percentages are rounded. The code retains the full values. With T=0.5, A is much more likely than D, but we still do not know whether A is factual, useful, or valid for your schema. With T=2, D receives more probability; that also does not prove it is more creative or better.
What top-p does after temperature
In our implementation, we sort probabilities from highest to lowest, retain the smallest prefix whose sum reaches top_p, and renormalize it. This procedure makes the order of operations in the example explicit. Check your engine's order, along with additional filters and the minimum number of retained tokens.
With top_p=0.8, the three distributions above retain different sets:
| Temperature | Retained candidates | Probabilities after truncation |
|---|---|---|
| 0.5 | A | A: 100% |
| 1.0 | A, B | A: 73.11%; B: 26.89% |
| 2.0 | A, B, C | A: 50.65%; B: 30.72%; C: 18.63% |
In the first row, A alone already exceeds the threshold. In the second, A does not reach it, so we need to add B. In the third, A+B total approximately 73.11%, so C is included as well. This explains why changing temperature and top_p simultaneously makes it difficult to attribute a difference to the correct parameter.
top_p=0.8 does not mean “each token has 80% confidence,” “80% of the vocabulary is retained,” or “the answer will be correct 80% of the time.” It is a threshold on the probability mass of candidates at that step.
Complete code with no external dependencies
Save the following file as sampling_demo.py and run it with python3 sampling_demo.py. This guide was checked with Python 3.14.6 and the standard library. It does not download models, use keys, or call an API.
import math
def softmax(logits, temperature):
if temperature <= 0:
raise ValueError("Use a positive temperature")
scaled = [x / temperature for x in logits]
peak = max(scaled)
weights = [math.exp(x - peak) for x in scaled]
total = sum(weights)
return [x / total for x in weights]
def nucleus(probabilities, top_p):
if not 0 < top_p <= 1:
raise ValueError("top_p must be in (0, 1]")
selected, cumulative = [], 0.0
order = sorted(range(len(probabilities)),
key=lambda i: probabilities[i],
reverse=True)
for index in order:
selected.append(index)
cumulative += probabilities[index]
if cumulative >= top_p:
break
retained = sum(probabilities[i] for i in selected)
filtered = [probabilities[i] / retained
if i in selected else 0.0
for i in range(len(probabilities))]
return selected, filtered
for temperature in [0.5, 1.0, 2.0]:
p = softmax([3.0, 2.0, 1.0, 0.0], temperature)
selected, filtered = nucleus(p, 0.8)
assert math.isclose(sum(p), 1.0)
assert math.isclose(sum(filtered), 1.0)
print("T:", temperature)
print("p:", [round(x, 6) for x in p])
print("kept:", selected)
print("filtered:", [round(x, 6) for x in filtered])
For T=1, the kept line should be [0, 1] and filtered should be [0.731059, 0.268941, 0.0, 0.0]. Also test a non-positive temperature: the program must reject it. This exception prevents pretending that division by zero implements a server's greedy decoding.
Zero temperature, sampling, and reproducibility
The official Transformers generation configuration distinguishes sampling from greedy selection through do_sample. Do not assume that temperature=0 has the same interpretation in every API or version. It may activate a special path, be invalid, or not be supported by a particular model.
Even when a system selects the most likely candidate, stable output does not establish its truthfulness. Moreover, reproducing results requires recording the model and its revision, engine, tokenizer, precision, hardware, and configuration. A seed only controls the components documented by the implementation; it does not replace preserving that data.
Before sending requests, check the model and endpoint documentation for which parameters they accept, their limits, and their default values. A field present in the SDK does not prove that every model behind that client uses it. If an API rejects a parameter, save the error and correct the configuration according to its contract; do not silently remove fields and then mix the results as if they were the same test.
How to choose temperature in your application
Use a one-variable-at-a-time evaluation. This is a proposed design; it has not been run against a model in this guide and does not represent a universal recommendation of values.
- Freeze the system. Record the model ID and revision when available, endpoint, SDK version, full messages, tools, schema, output limit, and retry policy. Redact any keys before archiving logs.
- Prepare cases with observable criteria. For example, field extraction with expected values, answers supported by a document, or variants of a text assessed with a rubric. Include predictable errors and difficult cases; do not use only your favorite examples.
- Keep top-p and the other controls fixed. Select three temperatures supported by that model and repeat each case several times. An initial pilot could use 20 cases and five repetitions per configuration; these are design choices, not a guaranteed statistical sample size.
- Save all results. Record valid requests, errors, retries, time, reported usage, and truncated results. A timeout is not an ordinary incorrect response or a trial that should disappear from the denominator.
- Evaluate without seeing the configuration. For extraction, compare with the reference; for open text, apply the rubric and review disagreements. Count valid format, faithfulness, omissions, and useful diversity separately.
- Choose with constraints. A configuration that produces more variants may fail your schema. Another may repeat exactly one incorrect response. Keep the configurations that meet your criteria and then compare their actual cost and latency.
- Test top-p in a second phase. Fix the selected temperature, vary only supported thresholds, and evaluate again. Then validate the final combination on a set you have not used for tuning.
| Log field | What it lets you verify |
|---|---|
| Model, revision, and date | Whether the comparison uses the same system |
| Case ID and repetition | Variation within the same problem |
| Temperature, top-p, and other filters | Whether only the intended variable changes |
| Original response and finish | Truncation, format, and content |
| Rubric result | Task quality, separate from fluency |
| Time, usage, and errors | Operational cost and failures that must not be hidden |
To prepare the calls, see the example of chat completions with cURL across multiple models. Keep each model's conditions; do not interpret a shared parameter name as equivalence across providers. If you also compare speed, the speculative decoding guide helps distinguish generation configuration from engine techniques.
Frequently asked questions
What temperature is best for programming or extracting data?
There is no number that this guide can guarantee. Start with a supported configuration, a schema or verifiable tests, and a representative set. Compare several configurations and review failures; lowering the temperature does not add knowledge or correct an incorrect reference.
Does a high temperature always generate more creativity?
In the calculation, it increases the probability of less dominant candidates. “Useful creativity” needs a definition and an evaluation of complete responses. It can also increase useless variations. Measure it with your rubric instead of using diversity as a synonym for quality.
Can I change temperature and top-p at the same time?
It can be a valid configuration if the model supports it, but it makes it harder to explain what caused the change. Adjust one at a time for diagnosis, and then evaluate the full combination. The order of the engine's processors also matters.
Does this example measure hallucinations or Flatkey performance?
No. It only recalculates probabilities for four synthetic logits on CPU. There are no model calls, accuracy measurements, or commercial comparisons. To evaluate a service, you need authorized real requests, references, and an appropriate methodology.
Sources and responsibility
The conceptual explanation was cross-checked against IBM on LLM temperature; the names and documented behavior of the controls were cross-checked against Transformers. These are external sources; their examples are not experiments conducted by Flatkey. The preceding code and tables are a reproducible work by Flatkey Team, verified on November 23, 2026.
Flatkey Team is responsible for this content; you can see who we are and how to contact us. Flatkey markets AI services. This relationship does not make the illustration independent proof of its performance. For the next step, start with your evaluation and the model's parameter contracts, or return to the English blog to explore related guides.



