Temperature: sharper probabilities can make a wrong answer more likely
温度与采样
Derive temperature probabilities and entropy, handle ties at zero and test a wrong-highest-logit example.
sampling-temperatureMaking a model more certain does not make it right
Imagine a three-answer task. The model assigns probabilities 0.6, 0.3 and 0.1, but the authored reference answer is the second option. Lowering temperature to one half changes the probabilities to approximately 0.782609, 0.195652 and 0.021739. The distribution is sharper; the chance of sampling the correct answer has fallen.
Temperature controls the shape of a model distribution. It does not check facts, repair a misleading prompt or identify the reference answer. This deliberately wrong-top-token example separates two things that often get merged: confidence and task correctness.
Holtzman and colleagues, section 3.3, describe temperature sampling in text generation. Fan, Lewis and Dauphin, section 5.4, tune temperature for their story-generation models alongside top-k sampling. These are uses under particular experimental conditions, not evidence of a universally best temperature.
Scale log-odds, not knowledge
Let be a fixed finite logit for token and let temperature be strictly positive. Temperature sampling uses:
At this is the original softmax. Lower positive temperatures enlarge logit differences; higher ones reduce them. The model parameters and the ranking of finite logits stay unchanged. Temperature affects which outcomes are sampled, not which finite-logit token has the largest probability.
If is the original distribution, the same transformation can be written:
For weights 6, 3 and 1, squares them to 36, 9 and 1 and normalizes by 46. This is not multiplying each probability by a common constant: a common multiplication would cancel during normalization and change nothing.
The odds relationship makes the effect precise:
Changing therefore scales every log-odds difference by the same positive factor. Adding one constant to all logits leaves the distribution unchanged. In implementation, subtracting the largest logit normally uses that invariance to avoid exponential overflow.
Zero is not a valid divisor in the softmax formula. With a fixed finite vocabulary, the positive-temperature limit is uniform over the set of maximizing logits:
For logits 2, 2 and 0, the limit is . A deterministic argmax returning the first maximum adds a separate tie rule. A library option called “temperature zero” may switch to greedy decoding rather than evaluate this formula. As tends to infinity, fixed finite logits approach a uniform distribution over the whole vocabulary; permanently masked tokens require a separate support convention.
Entropy, measured here in nats, describes spread:
Write . Differentiating softmax with respect to temperature gives:
A logit above the current mean loses probability as temperature rises; one below it gains probability. A middle token can change direction because the mean changes too. Do not assume that every nonmaximum token rises monotonically for all temperatures.
Using with and , the entropy derivative is:
The result assumes fixed finite logits and fixed support, with no intervening top-p or other changing truncation. It is a statement about distribution entropy, not a guarantee that generated sentences become more useful or more factually correct.
Measure spread and correctness separately
The complete NumPy example evaluates logits equal to the natural logarithms of 6, 3 and 1. It prints distributions, entropy, the probability of the declared correct second token and analytic derivatives at five temperatures. There is no trained model or text-generation benchmark in this calculation.
"""Finite-logit temperature distributions, entropy and a declared wrong-top-token example."""
import json
import numpy as np
def probabilities(logits,temperature):
z=np.asarray(logits,dtype=float)
if z.ndim!=1 or not len(z) or not np.isfinite(z).all():raise ValueError('Finite nonempty logits required')
if not np.isfinite(temperature) or temperature<=0:raise ValueError('Temperature must be finite and positive')
# Normally shift first. If opposite extreme signs overflow subtraction,
# divide those entries first; their scaled difference cannot be inf-inf.
with np.errstate(over='ignore',under='ignore'):
delta=z-z.max();scaled=delta/temperature
overflow=~np.isfinite(delta)
scaled[overflow]=z[overflow]/temperature-z.max()/temperature
e=np.exp(scaled)
return e/e.sum()
def zero_limit(logits):
z=np.asarray(logits,dtype=float)
if z.ndim!=1 or not len(z) or not np.isfinite(z).all():raise ValueError('Finite nonempty logits required')
keep=(z==z.max()).astype(float)
return keep/keep.sum()
def entropy(p):
a=np.asarray(p,dtype=float);a=a[a>0]
return float(-np.sum(a*np.log(a)))
def derivatives(logits,t):
z=np.asarray(logits,dtype=float);p=probabilities(z,t);mean=float(p@z)
variance=float(p@((z-mean)**2))
return dict(dp=(p*(mean-z)/t**2).tolist(),dH=variance/t**3)
def demo():
z=np.log([6.,3.,1.]);rows=[]
for t in [.25,.5,1.,2.,4.]:
p=probabilities(z,t)
rows.append(dict(temperature=t,probabilities=p.tolist(),entropy=entropy(p),
correct_token_probability=float(p[1]),derivatives=derivatives(z,t)))
return dict(logits=z.tolist(),results=rows,declared_correct_token=1,
tied_zero_limit=zero_limit([2,2,0]).tolist(),
deterministic_argmax=int(np.argmax([2,2,0])),
scope='Correct token is assigned by the authored task, not inferred from model confidence')
if __name__=='__main__':print(json.dumps(demo()))
At temperatures 0.5, 1 and 2, entropy is approximately 0.594257, 0.897946 and 1.037971 nats. The correct-token probabilities are approximately 0.195652, 0.300000 and 0.334273. At temperature 0.25, that probability is only 0.058781. These numbers verify the counterexample without assuming a relationship between model confidence and ground truth.
The tests compare analytic probability and entropy derivatives with central finite differences. They check shift invariance, ranking, tied zero limits and the high-temperature uniform limit. Finite differences are numerical checks of this derivation, not a substitute for stating its assumptions.
Subtracting extreme logits can itself overflow before exponentiation. For logits − and at temperature , the intended scaled difference is −2, not negative infinity. The program detects overflow in that subtraction and divides those opposite-sign entries before subtracting. It returns approximately 0.119203 and 0.880797. Underflow of extremely small nonmaximum probabilities is allowed. The derivative demonstrations use moderate logits; arbitrary extremes can still exceed representable precision in variance calculations.
Each distribution and entropy evaluation takes linear work and storage in vocabulary size. Sorting is unnecessary. The entropy helper expects an already valid normalized distribution, as supplied by probabilities; it is not a general validator for arbitrary inputs.
The same knob serves different goals
Sampling temperature is chosen to shape generation. Calibration temperature is fitted using held-out labels to improve the relationship between predicted probabilities and empirical correctness. They share a mathematical scaling operation but have different objectives and evidence requirements. Manually selecting a lower generation temperature does not establish calibration.
Low temperature can make an incorrect high-logit answer more frequent. High temperature can increase variety while admitting unsuitable tokens. The useful range depends on the task, model, prompt and other decoding filters. The story-generation and text-degeneration papers supply examples of evaluation, not a universal setting for factual question answering or code.
Changing temperature before nucleus truncation can change which tokens are retained. Applying it after truncation cannot restore discarded support. See top-k/top-p for an explicit order counterexample. Evaluate the whole sampling policy, including tie rules and stopping conditions, rather than treating temperature as an isolated quality score.
Check the limit and the objective
- Starting from probabilities 0.6, 0.3 and 0.1, calculate the distribution at temperature one half. Answer: Square and normalize: , or . The second token falls from 0.3 to approximately 0.195652.
- Why does adding 100 to every logit leave the result unchanged? Answer: Every numerator and the denominator acquire the common factor , which cancels. The implementation uses this invariance in a numerically safer form.
- What is the zero-temperature limit for logits 2, 2 and 0, and how does first-index
argmaxdiffer? Answer: The softmax limit splits mass equally between the first two tokens. First-indexargmaxreturns only index zero because it imposes an additional deterministic tie convention. - Does increasing entropy prove better factual accuracy? Answer: No. Entropy measures spread, not agreement with reference facts. Conversely, the example shows that decreasing entropy can reduce the probability of a known correct answer when the top logit is wrong.
Report the distribution and the task result
Holtzman and colleagues formalize temperature alongside nucleus and top-k sampling, then evaluate generated text under specified model conditions. Fan and colleagues tune generation temperature in their story system. A useful experiment likewise records the entire decoding setup and distinguishes diversity, repetition, task success and probability calibration.
For a new model, begin with fixed inputs and reproducible sampling settings. Inspect how support, entropy and task outcomes change together. The derivation explains what the knob does to probabilities; the evaluation must determine whether that change helps the intended task.
Make a prediction, then check
What happens as temperature approaches zero when two logits share the maximum?
Learning objectives
- Derive the power transformation and log-odds scaling.
- Show entropy increases with positive temperature for fixed logits.
- Distinguish confidence, task correctness and tie-breaking conventions.
Prerequisites & connections
Explore related knowledge →References
- The Curious Case of Neural Text Degeneration — arXiv v2, ICLR 2020 text
Ari Holtzman; Jan Buys; Li Du; Maxwell Forbes; Yejin Choi · 2020 - Hierarchical Neural Story Generation
Angela Fan; Mike Lewis; Yann Dauphin · 2018
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author read Holtzman v2 PDF4–6 sections3.1–3.3 and Fan PDF5/6 section5.4. Seven paired equations and four explained exercises. Original finite logits, analytic derivatives versus central differences, shift/rank checks, zero-temperature ties, high-temperature limit and extreme subtraction-overflow correction. Fixed support assumptions and confidence-versus-correctness counterexample. No quality benchmark or learned calibration.
- Single AI author read Holtzman v2 PDF4–6 sections3.1–3.3 and Fan PDF5/6 section5.4. Seven paired equations and four explained exercises. Original finite logits, analytic derivatives versus central differences, shift/rank checks, zero-temperature ties, high-temperature limit and extreme subtraction-overflow correction. Fixed support assumptions and confidence-versus-correctness counterexample. No quality benchmark or learned calibration.
- Four computed SVG variants per topic;9 numeric/geometry tests and24 responsive cases passed. Eight final Chinese-mobile/English-desktop screenshots actually inspected. Full article acceptance recorded separately.
Source locations checked:
- The Curious Case of Neural Text Degeneration — arXiv v2, ICLR 2020 text · Visually read PDF4–6, sections3.1–3.3/equations2–4 and4.1 setup. Nucleus minimal prefix, truncation renormalization and temperature; reported quality is task/model-specific. No text generation experiment reproduced.
- Hierarchical Neural Story Generation · Visually read PDF5–6, especially section5.4: authors use top-10 random sampling and tune temperature for their story models. Not evidence of a universal best k or temperature. No story-model benchmark reproduced.
Related topics