Techniqueintro
Temperature sampling
Also called softmax temperature.
Sample the next token from softmax(z / T). T below 1 sharpens the distribution toward greedy, T above 1 flattens it toward uniform.
Temperature sampling draws the next token of an autoregressive language model from the softmax of the logits divided by a number , the temperature: . With it is plain ancestral sampling from the model. A temperature below 1 makes the distribution sharper, so the likely tokens get even more of the mass, and as it becomes greedy decoding. A temperature above 1 makes it flatter, and as it becomes uniform over the allowed tokens. The order of the tokens never changes; only how strongly the draw follows it. The name comes from the Boltzmann distribution of statistical physics, where the same formula with an energy in place of the logit describes a system at a temperature. The temperature is a heuristic setting, tuned by hand for each use; no value is correct in general.
In plain words
The model gives every possible next word a score. Temperature is a knob that sets how much you trust those scores when you draw the next word at random. Turn it down and you almost always get the top word, so the text is safe but can be dull and repeat itself. Turn it up and the weaker words get more chances, so the text is more varied but can drift into nonsense. At the middle setting of 1 you draw words with exactly the chances that the model gives.
When it applies
Temperature applies whenever a token is drawn at random from a softmax over logits: plain sampling, and also top-k sampling, nucleus sampling and typical sampling, which apply it before they cut the distribution. It does not change greedy decoding or beam search on its own, because dividing all logits by the same positive keeps their order. The same formula appears outside decoding, for example to soften the outputs of a teacher model in knowledge distillation, and as the acceptance rule of simulated annealing.
The template
The step takes the logits and a number drawn uniformly from .
TEMPERATURE-SAMPLE(z, T, u) ▷ z = logits, T > 0, u uniform in [0, 1)- 1
m ← max over i of z[i] ▷ subtract it so that no exp overflows - 2
for each i do w[i] ← exp((z[i] − m) / T) - 3
Z ← sum of w[i] - 4
r ← u · Z - 5
return the first i with w[1] + ... + w[i] > r
Each weight is at most 1 and the largest is exactly 1, so the sum is at least 1 and nothing overflows or divides by 0. A logit of , as used to forbid a token, gets weight 0 and is never drawn. The proof is in proofs/correctness.md: the step draws from , the entropy of never decreases as grows, and the limits for and are the uniform distributions on the tokens of largest logit and on the allowed tokens.
Classic examples
Three logits. For the logits :
| entropy (nats) | ||
|---|---|---|
| 0.25 | (0.98169, 0.01798, 0.00033) | 0.0930 |
| 0.5 | (0.86681, 0.11731, 0.01588) | 0.4411 |
| 1 | (0.66524, 0.24473, 0.09003) | 0.8324 |
| 2 | (0.50648, 0.30720, 0.18632) | 1.0202 |
| 4 | (0.41923, 0.32650, 0.25428) | 1.0781 |
| 100 | (0.33667, 0.33332, 0.33001) | 1.0986 |
The entropy rises from near 0 toward , the entropy of the uniform distribution on three tokens.
The power form. If is the distribution at , then . At , the probabilities are squared and renormalized: , , , with sum , which gives again. So temperature can be applied to probabilities as well as to logits.
Ties. For , a temperature near 0 does not pick one token; it gives . The limit of temperature sampling is greedy decoding only when the largest logit is unique.
In practice. Holtzman et al. 2020 compared sampling at and top-k = 40 at with other decoders on GPT-2 Large. Lowering the temperature reduced the incoherent text of pure sampling but brought back some of the repetition of greedy decoding: top-k = 40 at repeated 8.86% of the time, against 0.78% for top-k = 40 at .
Variations
- Temperature with truncation. Apply to the logits, then top-k, top-p or typical truncation. The kept set of top-k does not depend on ; those of top-p and typical sampling do.
- The Gumbel-max form. Draw from a standard Gumbel distribution and return the argmax of . This draws from too (Gumbel-max trick), and it is the basis of stochastic beam search.
- Schedules. Change during the generation, for example a higher temperature for the first tokens of a story and a lower one later. This is a heuristic with no general result.
- Entropy targets. Pick at each step so that the entropy of hits a target value. Theorem 4 of the proof (the entropy grows with ) makes a bisection on work.
- Temperature in training. Divide the logits by in the loss, as in knowledge distillation, to give more weight to the small probabilities of a teacher.
Pitfalls
- Overflow. Computing directly overflows for a small : with and the exponent is . Subtract the largest logit first, as in line L1.
- . The formula divides by 0. Treat as greedy decoding with a stated tie rule, not as a temperature.
- The order of operations. Temperature then top-p and top-p then temperature give different distributions, because the nucleus depends on the values. Libraries differ; state what you do.
- High temperature with a large vocabulary. With tens of thousands of tokens, even moves a lot of mass to the tail, and the output can fall apart within a few tokens. Combine a high temperature with truncation.
- No single best value. The best temperature depends on the model, the task and how the output is judged. Values from 0.7 to 1 are common for open-ended text, and 0 (greedy) for tasks with one answer.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Log-space arithmetic and semirings for the natural-language-and-speech pages.
Every log is the natural log. A probability of 0 is NEG_INF (float("-inf")),
never a large negative number. A cost is -log p, so a probability of 0 is a
cost of POS_INF.
The semirings are (K, plus, times, zero, one) as on the weighted-automaton page:
PROB probabilities plus = + times = * zero = 0 one = 1
LOG log probabilities plus = log_add times = + zero = -inf one = 0
VITERBI log probabilities plus = max times = + zero = -inf one = 0
TROPICAL costs -log p plus = min times = + zero = +inf one = 0
LOG_COST costs -log p plus = -log_add(-a, -b), times = +, zero = +inf, one = 0
BOOLEAN truth values plus = or times = and zero = False one = True
COUNTING path counts plus = + times = * zero = 0 one = 1
This module holds no algorithm of any page: no forward, Viterbi, CKY, Eisner,
CTC or DTW recursion. The pages build their dynamic programs on top of it.
"""
import math
from dataclasses import dataclass
from typing import Any, Callable, Iterable, List, Sequence
NEG_INF = float("-inf")
POS_INF = float("inf")
def safe_log(p) -> float:
"""Return log p, and NEG_INF for p = 0. Raise ValueError for p < 0."""
if p < 0:
raise ValueError("log of a negative number")
if p == 0:
return NEG_INF
return math.log(p)
def log_add(a: float, b: float) -> float:
"""Return log(exp(a) + exp(b)) = max(a, b) + log(1 + exp(-|a - b|)).
log_add(NEG_INF, NEG_INF) is NEG_INF. No exp of a large number is taken.
"""
if a < b:
a, b = b, a
if b == NEG_INF or a == POS_INF:
return a
return a + math.log1p(math.exp(b - a))
def log_sum(xs: Iterable[float]) -> float:
"""Return log(sum of exp(x)) over xs. An empty input gives NEG_INF."""
xs = list(xs)
if not xs:
return NEG_INF
m = max(xs)
if m == NEG_INF or m == POS_INF:
return m
return m + math.log(math.fsum(math.exp(x - m) for x in xs))
def log_normalize(xs: Sequence[float]) -> List[float]:
"""Return the list x - log_sum(xs): log values whose exps sum to 1.
Raise ValueError if every value is NEG_INF (nothing to normalize).
"""
z = log_sum(xs)
if z == NEG_INF:
raise ValueError("every weight is zero")
return [x - z for x in xs]
def log_softmax(xs: Sequence[float]) -> List[float]:
"""Return log softmax(xs): the logits xs turned into log probabilities."""
return log_normalize(xs)
def softmax(xs: Sequence[float], temperature: float = 1.0) -> List[float]:
"""Return the probabilities exp(x / temperature) / sum, computed stably.
The temperature must be positive. Logits of NEG_INF get probability 0.
"""
if not temperature > 0:
raise ValueError("the temperature must be positive")
m = max(xs)
if m == NEG_INF:
raise ValueError("every logit is -inf")
es = [math.exp((x - m) / temperature) for x in xs]
s = math.fsum(es)
return [e / s for e in es]
def argmax(xs: Sequence[Any]) -> int:
"""Return the first index of a largest value. Raise ValueError if xs is empty."""
if len(xs) == 0:
raise ValueError("argmax of an empty sequence")
best = 0
for i in range(1, len(xs)):
if xs[i] > xs[best]:
best = i
return best
@dataclass(frozen=True)
class Semiring:
"""A semiring (K, plus, times, zero, one). idempotent is True when a plus a = a."""
name: str
plus: Callable[[Any, Any], Any]
times: Callable[[Any, Any], Any]
zero: Any
one: Any
idempotent: bool
def _add(a, b):
return a + b
def _mul(a, b):
return a * b
def _log_add_cost(a: float, b: float) -> float:
return -log_add(-a, -b)
PROB = Semiring("probability", _add, _mul, 0, 1, False)
LOG = Semiring("log", log_add, _add, NEG_INF, 0.0, False)
VITERBI = Semiring("viterbi", max, _add, NEG_INF, 0.0, True)
TROPICAL = Semiring("tropical", min, _add, POS_INF, 0.0, True)
LOG_COST = Semiring("log-cost", _log_add_cost, _add, POS_INF, 0.0, False)
BOOLEAN = Semiring("boolean", lambda a, b: a or b, lambda a, b: a and b, False, True, True)
COUNTING = Semiring("counting", _add, _mul, 0, 1, False)
def sr_sum(sr: Semiring, xs: Iterable[Any]) -> Any:
"""Return the semiring sum of xs, and sr.zero for an empty input."""
acc = sr.zero
for x in xs:
acc = sr.plus(acc, x)
return acc
def sr_prod(sr: Semiring, xs: Iterable[Any]) -> Any:
"""Return the semiring product of xs, and sr.one for an empty input."""
acc = sr.one
for x in xs:
acc = sr.times(acc, x)
return acc
temperature_sampling.py 60 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/temperature-sampling/. The authors are listed in prov/C3YE2Y.jsonl.
"""Temperature sampling of the next token.
The input is a list of logits z, one per token of the vocabulary, in the
order of the vocabulary. A logit of float("-inf") means a token that is
not allowed. The random source is any object with a random() method that
returns u in [0, 1), such as random.Random(seed). The code takes the logits
of the model as given; it does not run or train a network.
"""
import math
from typing import List, Sequence
from nlslog import NEG_INF, softmax
def temperature_distribution(logits: Sequence[float], temperature: float) -> List[float]:
"""Return softmax(z / T), computed after subtracting the largest logit."""
return softmax(logits, temperature)
def temperature_sample(logits: Sequence[float], temperature: float, rng) -> int:
"""Draw one token index from softmax(z / T) without forming the normalized list.
The weights exp((z_i - m) / T) are at most 1, so nothing overflows, and
r = u Z replaces the division by Z.
"""
if not temperature > 0:
raise ValueError("the temperature must be positive")
m = max(logits) # @line L1
if m == NEG_INF:
raise ValueError("every logit is -inf")
w = [math.exp((x - m) / temperature) for x in logits] # @line L2
z = math.fsum(w) # @line L3
r = rng.random() * z # @line L4
c = 0.0
for i, x in enumerate(w): # @line L5
c += x
if r < c:
return i
return max(i for i, x in enumerate(w) if x > 0)
def limit_distribution(logits: Sequence[float], which: str) -> List[float]:
"""Return the limit of softmax(z / T) as T goes to 0 ("zero") or to infinity ("inf").
As T goes to 0, the mass goes uniformly to the tokens of largest logit.
As T grows, it goes uniformly to the tokens of finite logit.
"""
m = max(logits)
if which == "zero":
keep = [x == m for x in logits]
elif which == "inf":
keep = [x != NEG_INF for x in logits]
else:
raise ValueError("which must be 'zero' or 'inf'")
n = sum(keep)
return [1.0 / n if k else 0.0 for k in keep]
test_temperature_sampling.py 110 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/temperature-sampling/. The authors are listed in prov/C3YE2Y.jsonl.
import math
import random
from nlslog import NEG_INF, argmax
from temperature_sampling import limit_distribution, temperature_distribution, temperature_sample
Z = [2.0, 1.0, 0.0]
def entropy(p):
return -math.fsum(x * math.log(x) for x in p if x > 0)
def test_check_values() -> None:
for t, want in (
(1.0, (0.66524, 0.24473, 0.09003)),
(0.5, (0.86681, 0.11731, 0.01588)),
(2.0, (0.50648, 0.30720, 0.18632)),
):
got = temperature_distribution(Z, t)
for g, w in zip(got, want):
assert abs(g - w) < 5e-6
assert abs(entropy(temperature_distribution(Z, 1.0)) - 0.8324) < 1e-4
def test_power_form_is_the_same() -> None:
# softmax(z / T) equals p^(1/T) renormalized, with p = softmax(z)
rng = random.Random(1)
for _ in range(200):
z = [rng.uniform(-4, 4) for _ in range(6)]
t = rng.uniform(0.2, 5)
p = temperature_distribution(z, 1.0)
powered = [x ** (1 / t) for x in p]
s = math.fsum(powered)
for a, b in zip(temperature_distribution(z, t), (x / s for x in powered)):
assert abs(a - b) < 1e-12
def test_entropy_grows_with_the_temperature() -> None:
rng = random.Random(2)
temps = [0.05 * j for j in range(1, 101)]
for _ in range(100):
z = [rng.uniform(-3, 3) for _ in range(5)]
hs = [entropy(temperature_distribution(z, t)) for t in temps]
for a, b in zip(hs, hs[1:]):
assert b >= a - 1e-12
assert hs[-1] <= math.log(5) + 1e-12
def test_limits() -> None:
assert limit_distribution(Z, "zero") == [1.0, 0.0, 0.0]
assert limit_distribution([2.0, 2.0, 0.0], "zero") == [0.5, 0.5, 0.0]
assert limit_distribution([2.0, NEG_INF, 0.0], "inf") == [0.5, 0.0, 0.5]
for z in (Z, [2.0, 2.0, 0.0], [3.0, NEG_INF, 1.0, 0.5]):
cold = temperature_distribution(z, 0.01)
hot = temperature_distribution(z, 1e6)
for a, b in zip(cold, limit_distribution(z, "zero")):
assert abs(a - b) < 1e-6
for a, b in zip(hot, limit_distribution(z, "inf")):
assert abs(a - b) < 1e-5
def test_shift_does_not_matter_and_masked_tokens_stay_out() -> None:
rng = random.Random(3)
for _ in range(100):
z = [rng.uniform(-3, 3) for _ in range(4)]
c = rng.uniform(-100, 100)
for a, b in zip(temperature_distribution(z, 0.7), temperature_distribution([x + c for x in z], 0.7)):
assert abs(a - b) < 1e-9
z = [1.0, NEG_INF, 0.0]
for t in (0.1, 1.0, 50.0):
assert temperature_distribution(z, t)[1] == 0.0
assert all(temperature_sample(z, t, rng) != 1 for _ in range(300))
def test_sampling_frequencies_and_gumbel_max() -> None:
rng = random.Random(4)
draws = 20000
for t in (0.5, 2.0):
want = temperature_distribution(Z, t)
direct = [0, 0, 0]
gumbel = [0, 0, 0]
for _ in range(draws):
direct[temperature_sample(Z, t, rng)] += 1
# a second method: argmax of z / T plus Gumbel noise
g = [x / t - math.log(-math.log(1.0 - rng.random())) for x in Z]
gumbel[argmax(g)] += 1
for a, b, w in zip(direct, gumbel, want):
assert abs(a / draws - w) < 0.01
assert abs(b / draws - w) < 0.01
def test_huge_logits_do_not_overflow() -> None:
p = temperature_distribution([1000.0, 999.0], 0.01)
assert p[0] > 0.999999 and p[1] < 1e-6
rng = random.Random(5)
assert temperature_sample([1e6, 0.0], 1.0, rng) == 0
def test_bad_temperature() -> None:
for t in (0.0, -1.0):
try:
temperature_sample(Z, t, random.Random(6))
except ValueError:
pass
else:
raise AssertionError("no ValueError")
Exercises
- Show that adding the same constant to all logits does not change , and use it to justify line L1.
- Prove that , where .
- Show that the entropy of satisfies with , and conclude that it does not decrease in .
- For , find the temperature at which the most probable token has probability exactly 0.5. (Use bisection, since the probability is monotone in .)
- Show that the argmax of , with independent standard Gumbel , has the distribution .
Proof: Temperature sampling draws from softmax(z / T), its entropy grows with T, and its limits are greedy and uniformfull
We use the notation of the page. The logits are , with at least one finite value; a logit of marks a token that is not allowed. The temperature is , and we write . The distribution is
with . All logs are natural logs.
Lemma 1 (the draw). TEMPERATURE-SAMPLE returns each token with probability , and never returns a token with .
Proof. Let (line L1), which is finite. Line L2 computes , so the are the numerators of times the same positive constant, and . Each lies in , so no exponential overflows, and the token of largest logit has , so the sum of line L3 is at least 1. Lines L4 and L5 are inverse transform sampling with uniform on : the walk returns when falls in an interval of length , which happens with probability . A token with has and an empty interval.
Lemma 2 (the power form). Let be the distribution at . Then .
Proof. with , so . The factor is the same for all and cancels in the ratio.
Lemma 3 (shift). Adding the same constant to every logit does not change .
Proof. Every numerator and the denominator are multiplied by .
Theorem 4 (the entropy grows with the temperature). Let be the entropy of . Then does not decrease in , and it is strictly increasing unless all the finite logits are equal.
Proof. Restrict to the tokens of finite logit; the others have probability 0 at every . Write with . Then
where is the mean under . Since and ,
So does not increase in , and since decreases as grows, does not decrease in . The variance is 0 only when is constant on the support, which is the case where is uniform for every ; otherwise it is positive for every and is strictly increasing in .
The family is an exponential family with the logits as the sufficient statistic, and Theorem 4 is the standard fact that the derivative of its mean is its variance.
Theorem 5 (the limits). Let and . As , tends to the uniform distribution on . As , tends to the uniform distribution on .
Proof. Use the weights of Lemma 1. For , at every . For with finite, and as . So and on and 0 elsewhere. As , for every and outside , so on .
So a small temperature gives the argmax of greedy decoding when the largest logit is unique, and a uniform choice among the tied tokens otherwise; a large temperature gives the uniform distribution over the allowed tokens, whatever the model says. The tests check Lemma 1 by sampling and by a second method, the Gumbel-max trick, Lemma 2 and Lemma 3 numerically, Theorem 4 on a fine grid of temperatures, and Theorem 5 at and .
References
- Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes and Yejin Choi, The curious case of neural text degeneration, ICLR 2020, Section 3.3 (sampling with temperature, Equation 4, with the reference to Ackley, Hinton and Sejnowski 1985) and Table 1 (sampling with t = 0.9 and top-k = 40 with t = 0.7)
- Nitish Shirish Keskar, Bryan McCann, Lav R. Varshney, Caiming Xiong and Richard Socher, CTRL, a conditional transformer language model for controllable generation, arXiv 1909.05858, 2019, Section 4.1 (Sampling), Equation 1, with the remarks that T near 0 approximates greedy decoding and a large T flattens the distribution toward uniform
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag C3YE2Y Edit this page History Report an error Markdown