intermediate decoding-generation 40 min read

Sampling: Temperature, Top-k, and Nucleus

Ancestral sampling draws exactly from the model; temperature tilts it toward a Gibbs distribution and truncation cuts its tail, each at a cost we can compute exactly, and neither can add knowledge the model lacks

Overview & Motivation

Go back to the beam-search topic’s small example. After “revenue” the model says “rose” with probability 0.450.45, “was” with 0.350.35, and “fell” with 0.200.20. The most probable sentence, the mode, is “revenue was flat” at 0.2380.238; greedy decoding finds “revenue rose sharply” at 0.08640.0864. Neither is what the model says about revenue. The model says that thirteen different sentences are possible, and how often each should turn up. To hear that, we draw from it.

That topic left a gap that motivates this one. On the shared filings, the trigram’s exact modes cost 0.8350.835 nats per word and the held-out sentences cost 2.5762.576. This page adds a third number: the model’s own samples cost 2.3482.348 (all pooled per word, the end mark included). The mode is far more predictable than what the model usually writes. Sampling closes most of that gap, and we develop it in order:

  1. Sampling is exact. Drawing one token at a time returns every string with exactly its probability, and a draw is the argmax of noisy log-probabilities, so greedy decoding is sampling with the noise turned off.
  2. Temperature is a Gibbs distribution. Dividing logits by τ\tau trades expected score against entropy. The entropy only rises with τ\tau, and the log–log slope of the distribution divides by τ\tau.
  3. Per-step temperature is not a tempered model. Its cold limit is greedy decoding, not the mode, and above τ=1\tau = 1 the tempered model may not exist.
  4. Truncation has an exact price. A cut that keeps mass mm costs 1−m1 - m in total variation and −log⁡m-\log m in KL, and over a sentence the KL adds up exactly.
  5. Truncation is desmoothing, imperfectly. A Kneser–Ney model knows which words it saw, but no setting of any truncation rule recovers them on every prompt.

Then we measure every rule on two models trained on the shared filings, and ask what temperature does to a model’s facts.


Sampling is exact; search is not

We write eos\mathrm{eos} for the end mark </s>, and hth_t for the prefix before step tt.

Definition 1 (Ancestral sampling).

Given a prompt xx, draw Y1∼p(⋅∣x)Y_1 \sim p(\cdot \mid x), then Yt∼p(⋅∣x,Y<t)Y_t \sim p(\cdot \mid x, Y_{\lt t}) for t=2,3,…t = 2, 3, \dots, until eos\mathrm{eos} is drawn.

Theorem 1 (Sampling is exact).

(i) For every finite string yy ending in eos\mathrm{eos}, ancestral sampling returns yy with probability exactly p(y∣x)p(y \mid x).

(ii) It halts with probability ∑yp(y∣x)\sum_y p(y \mid x), so it halts almost surely if and only if the model is consistent.

Proof.

(i) Given the prefix y<ty_{\lt t}, the draw YtY_t has law p(⋅∣x,y<t)p(\cdot \mid x, y_{\lt t}). So the probability of drawing y1,…,yny_1, \dots, y_n in order is the product of these conditional probabilities, ∏tp(yt∣x,y<t)=p(y∣x)\prod_t p(y_t \mid x, y_{\lt t}) = p(y \mid x), by the chain rule.

(ii) The events “the sampler returns yy” are disjoint for different finite yy, and their union is the event that it halts. By (i), Pr⁡(halt)=∑yp(y∣x)\Pr(\text{halt}) = \sum_y p(y \mid x).

∎

The neural-language-models topic proves that a softmax recurrent model with bounded state is consistent (its Theorem 4), so for such models (ii) is never an issue. The harness draws 20,00020{,}000 samples from the lab tree and from 3030 random trees, and tests each tree’s fit by χ2\chi^2. It also checks every leaf with an expected count of at least 55 against p(y)p(y); on the random trees the other 1,8491{,}849 of 3,6303{,}630 leaves are pooled into one χ2\chi^2 cell. On the beam-search topic’s stationary model it checks that lengths are geometric.

Greedy decoding and sampling look like different algorithms. One fact about extreme-value noise shows that they differ only in what is added to the scores before taking a maximum.

Proposition 1 (Gumbel-max).

Let z∈RVz \in \mathbb{R}^V and let GwG_w be independent standard Gumbel variables, with CDF exp⁡(−e−g)\exp(-e^{-g}). Then arg⁡max⁡w(zw+Gw)∼softmax⁡(z)\arg\max_w (z_w + G_w) \sim \operatorname{softmax}(z), and max⁡w(zw+Gw)\max_w (z_w + G_w) is Gumbel with location log⁡∑wezw\log \sum_w e^{z_w}, independent of the argmax.

Proof.

Write Z=∑wezwZ = \sum_w e^{z_w}. The density of zi+Giz_i + G_i at gg is ezi−gexp⁡(−ezi−g)e^{z_i - g}\exp(-e^{z_i - g}), and Pr⁡(zj+Gj≤g)=exp⁡(−ezj−g)\Pr(z_j + G_j \le g) = \exp(-e^{z_j - g}). So

Pr⁡(arg⁡max⁡=i, max⁡≤m)=∫−∞mezi−gexp⁡(−∑jezj−g) dg=eziZexp⁡(−Ze−m),\Pr\big(\arg\max = i,\ \max \le m\big) = \int_{-\infty}^{m} e^{z_i - g} \exp\Big(-\sum_j e^{z_j - g}\Big)\, dg = \frac{e^{z_i}}{Z} \exp\big(-Z e^{-m}\big),

which factors into softmax⁡(z)i\operatorname{softmax}(z)_i times the Gumbel CDF with location log⁡Z\log Z at mm.

∎

So a draw from p(⋅∣h)p(\cdot \mid h) is the argmax of log⁡p(⋅∣h)\log p(\cdot \mid h) plus noise, and greedy decoding is the same argmax with the noise set to zero. The argmax half goes back to Yellott (1977); Maddison, Tarlow, and Minka (2014) state both halves. Kool, van Hoof, and Welling (2019) push the idea to whole sequences: perturb every prefix consistently, run beam search on the perturbed scores, and the top kk strings are an exact sample without replacement (their Theorem 1, Gumbel-top-kk). So sampling and greedy decoding are one loop with a dial for per-step noise. That dial does not reach the mode: noise off gives greedy’s string, which is Theorem 3’s point.


Temperature as a Gibbs distribution

Definition 2 (Temperature).

For a next-token distribution with log-probabilities z=log⁡p(⋅∣h)z = \log p(\cdot \mid h) and τ>0\tau \gt 0,

pτ(w∣h)  =  p(w∣h)1/τZτ(h)  =  softmax⁡(z/τ)w,Zτ(h)=∑wp(w∣h)1/τ.p_\tau(w \mid h) \;=\; \frac{p(w \mid h)^{1/\tau}}{Z_\tau(h)} \;=\; \operatorname{softmax}(z / \tau)_w, \qquad Z_\tau(h) = \sum_w p(w \mid h)^{1/\tau}.

Figure A of the laboratory below shows one such distribution as τ\tau slides. Near τ=0\tau = 0 the mass sits on the likeliest token; at large τ\tau it spreads evenly over the support. Everything between is a single curve, and it has three exact properties.

Theorem 2 (Temperature is a Gibbs distribution).

For any z∈RVz \in \mathbb{R}^V and τ>0\tau \gt 0:

(a) pτp_\tau is the unique maximizer over the simplex of ⟨q,z⟩+τH(q)\langle q, z\rangle + \tau H(q), and the maximum is τlog⁡∑wezw/τ\tau \log \sum_w e^{z_w/\tau}.

(b) ddτH(pτ)=Var⁡pτ(z)τ3≥0\dfrac{d}{d\tau} H(p_\tau) = \dfrac{\operatorname{Var}_{p_\tau}(z)}{\tau^3} \ge 0, with equality only when zz is constant on the support. The expected score Epτ[z]\mathbb{E}_{p_\tau}[z] is nonincreasing in τ\tau.

(c) As τ→0\tau \to 0, pτp_\tau tends to the uniform distribution on arg⁡max⁡z\arg\max z; as τ→∞\tau \to \infty, to the uniform distribution on the support.

Proof.

(a) Write L=log⁡∑wezw/τ\mathcal{L} = \log \sum_w e^{z_w/\tau}, so that log⁡pτ(w)=zw/τ−L\log p_\tau(w) = z_w/\tau - \mathcal{L}. For any qq, ⟨q,z⟩+τH(q)=τL−τ KL(q ∥ pτ)\langle q, z\rangle + \tau H(q) = \tau \mathcal{L} - \tau\, \mathrm{KL}(q \,\|\, p_\tau). Gibbs’ inequality makes the KL term non-negative, and zero only at q=pτq = p_\tau.

(b) Put β=1/τ\beta = 1/\tau and A(β)=log⁡∑weβzwA(\beta) = \log \sum_w e^{\beta z_w}. This is a log-partition function, so A′(β)=EβzA'(\beta) = \mathbb{E}_\beta z and A′′(β)=Var⁡βzA''(\beta) = \operatorname{Var}_\beta z. Since H=A(β)−βA′(β)H = A(\beta) - \beta A'(\beta), we get dH/dβ=−βVar⁡βzdH/d\beta = -\beta \operatorname{Var}_\beta z, and dβ/dτ=−1/τ2d\beta/d\tau = -1/\tau^2 turns this into dH/dτ=Var⁡(z)/τ3dH/d\tau = \operatorname{Var}(z)/\tau^3. Also d Eβz/dβ=Var⁡βz≥0d\,\mathbb{E}_\beta z / d\beta = \operatorname{Var}_\beta z \ge 0.

(c) Divide numerator and denominator of pτ(w)p_\tau(w) by eβmax⁡ze^{\beta \max z} and let β→∞\beta \to \infty or β→0\beta \to 0.

∎

Part (a) is the maximum-entropy principle of Jaynes (1957) with −z-z as the energy: temperature prices entropy against expected score. Part (b) is formalStatistics’ log-partition theorem (its Theorem 7.1) applied to the family {pτ}\{p_\tau\}, an exponential family with sufficient statistic log⁡p\log p and natural parameter 1/τ1/\tau. Annealing walks along that one curve (Kirkpatrick, Gelatt, and Vecchi 1983), and Ackley, Hinton, and Sejnowski (1985) brought the word “temperature” into neural networks. The harness checks (a) against a numerical optimizer on 5050 random score vectors, and (b) as monotone entropy on a 200200-point grid of τ\tau for every trigram prompt.

Temperature also has a picture on the Zipf topic’s log–log plot.

Proposition 2 (Temperature is the Zipf slope).

For any distribution, the least-squares slope of log⁡pτ\log p_\tau against log⁡(rank)\log(\text{rank}) is the slope of log⁡p\log p divided by τ\tau. A Zipf(ss) distribution becomes a Zipf(s/τs/\tau) distribution.

Proof.

Tempering preserves ranks, and log⁡pτ=1τlog⁡p−log⁡Zτ\log p_\tau = \tfrac{1}{\tau} \log p - \log Z_\tau. Least squares is linear in the response and ignores an added constant.

∎

So temperature divides the slope of the rank–frequency line, exactly, for one distribution. It moves the intercept too, because log⁡Zτ\log Z_\tau shifts the whole line: on a Zipf(1.11.1) row over 6060 ranks, τ=0.5\tau = 0.5 takes the log-probability at rank 11 from −1.374-1.374 to −0.395-0.395, and the two lines cross near rank 2.42.4. Sampled text mixes many contexts, so its own rank–frequency slope only roughly follows s/τs/\tau.


Local against global temperature

In practice temperature is applied at every step. That is not the same as tempering the model.

Theorem 3 (Local temperature is not global temperature).

Let qτ(y)=∏tpτ(yt∣ht)q_\tau(y) = \prod_t p_\tau(y_t \mid h_t) be the per-step tempered sampler, and πτ(y)=p(y)1/τ/Zτ\pi_\tau(y) = p(y)^{1/\tau}/\mathcal{Z}_\tau, with Zτ=∑yp(y)1/τ\mathcal{Z}_\tau = \sum_y p(y)^{1/\tau}, the tempered sequence distribution, when that sum is finite.

(a) qτ(y)=p(y)1/τ/∏tZτ(ht)q_\tau(y) = p(y)^{1/\tau} \big/ \prod_t Z_\tau(h_t). So qτ=πτq_\tau = \pi_\tau if and only if ∏tZτ(ht)\prod_t Z_\tau(h_t) takes the same value for every string in the support.

(b) With α=1/τ\alpha = 1/\tau and HαH_\alpha the Rényi entropy of order α\alpha,

log⁡qτ(y)πτ(y)  =  log⁡Zτ+(α−1)∑tHα(p(⋅∣ht)).\log \frac{q_\tau(y)}{\pi_\tau(y)} \;=\; \log \mathcal{Z}_\tau + (\alpha - 1) \sum_t H_\alpha\big(p(\cdot \mid h_t)\big).

For τ<1\tau \lt 1, local tempering upweights the strings whose prefixes carry more accumulated Rényi entropy.

(c) On a finite tree, if the mode and the argmaxes along greedy’s path are unique, then as τ→0\tau \to 0, qτq_\tau concentrates on greedy’s string and πτ\pi_\tau on the mode.

Proof.

(a) Substitute Definition 2 into the product; the numerators multiply to p(y)1/τp(y)^{1/\tau}.

(b) By definition Hα(p)=11−αlog⁡∑wpwαH_\alpha(p) = \frac{1}{1 - \alpha} \log \sum_w p_w^\alpha, so log⁡Zτ(h)=(1−α)Hα(p(⋅∣h))\log Z_\tau(h) = (1 - \alpha) H_\alpha(p(\cdot \mid h)). Divide (a) by πτ\pi_\tau and take logarithms.

(c) Along greedy’s path, each pτ(⋅∣h)p_\tau(\cdot \mid h) tends to the point mass on that prefix’s unique argmax. The path has finitely many steps, so qτq_\tau of greedy’s string tends to 11. Likewise πτ∝p(y)1/τ\pi_\tau \propto p(y)^{1/\tau} over finitely many strings tends to the point mass on the unique mode.

∎

The condition in (a) holds when, for instance, every string ends in a forced end mark at one fixed depth and every row before that is a permutation of one vector: those rows share one ZτZ_\tau, and the forced row contributes 11. The forced row has to be excepted, because the last row of a same-length string puts all its mass on eos\mathrm{eos}. The harness checks the equality on such trees, and checks the identity in (b) on 3030 random trees at three temperatures. Part (c) asks only about greedy’s path because the lab tree has ties elsewhere, at “rose on” and “rose in”. On the lab tree, Figure C shows the two samplers parting as the dial cools. At τ=0.1\tau = 0.1 they are 0.9250.925 apart in total variation: the per-step sampler puts 0.7050.705 on greedy’s “rose sharply” while the tempered model puts 0.9990.999 on the mode “was flat”. Caccia and colleagues (2020, §3) and Shih, Sadigh, and Ermon (2023, §2.1) observe that per-token temperature differs from tempering the joint distribution, and Shih and colleagues write out the per-step normalizer (their Eqs. 2–3). What this section adds is the reading of that normalizer as accumulated Rényi entropy, and the remark that follows. The gap is a relative of the label bias of locally normalized models (Andor and colleagues 2016): both come from normalizing step by step, though label bias limits what a model can express, while this gap is in how a sampler reshapes a fixed one.

The tempered model need not exist. For τ>1\tau \gt 1, Zτ\mathcal{Z}_\tau can be infinite. Take the beam-search topic’s stationary model: kk words of probability (1−ε)/k(1 - \varepsilon)/k each and eos\mathrm{eos} of probability ε\varepsilon, after every prefix. Then

Zτ=∑t≥0kt(1−εk)t/τε1/τ,\mathcal{Z}_\tau = \sum_{t \ge 0} k^t \Big(\frac{1 - \varepsilon}{k}\Big)^{t/\tau} \varepsilon^{1/\tau},

a geometric series with ratio k1−1/τ(1−ε)1/τk^{1 - 1/\tau}(1 - \varepsilon)^{1/\tau}. For k=5k = 5 and ε=0.05\varepsilon = 0.05 it diverges once τ≥1.032\tau \ge 1.032. The per-step sampler exists at every temperature; “the model at temperature 1.11.1” does not.


Truncation: top-k, nucleus, min-p, η, and typical

Definition 3 (Truncation).

A truncation rule keeps a set S(h)S(h) at each prefix and samples from pS(w∣h)=p(w∣h) 1[w∈S(h)]/m(h)p_S(w \mid h) = p(w \mid h)\, \mathbf{1}[w \in S(h)] / m(h), where m(h)=p(S(h)∣h)m(h) = p(S(h) \mid h) is the kept mass. With the probabilities sorted as p(1)≥p(2)≥⋯p_{(1)} \ge p_{(2)} \ge \cdots:

  • top-kk keeps the kk largest;
  • nucleus(pp) keeps the shortest prefix of the sorted order whose mass reaches pp;
  • min-pp(ρ\rho) keeps every ww with pw≥ρ p(1)p_w \ge \rho\, p_{(1)};
  • η\eta keeps every ww with pw>min⁡(η,η e−H)p_w \gt \min(\eta, \sqrt{\eta}\, e^{-H}), where HH is the row’s entropy;
  • typical sorts tokens by ∣−log⁡pw−H∣|{-\log p_w} - H| and keeps them until their mass reaches the typical mass.

Ties go to the lower token id.

Fan, Lewis, and Dauphin (2018) popularized top-kk; Holtzman and colleagues (2020) introduced the nucleus; Nguyen and colleagues (2025) min-pp; Hewitt, Manning, and Liang (2022) η\eta; and Meister and colleagues (2023) locally typical sampling, which we implement in the greedy form of their erratum.

Theorem 4 (What truncation costs).

(a) The nucleus has the fewest tokens of any set with mass at least pp, and the most mass among sets of its size. Top-kk has the most mass among sets of kk tokens.

(b) At one step, TV(pS,p)=1−m\mathrm{TV}(p_S, p) = 1 - m and KL(pS ∥ p)=−log⁡m\mathrm{KL}(p_S \,\|\, p) = -\log m, while KL(p ∥ pS)=∞\mathrm{KL}(p \,\|\, p_S) = \infty whenever m<1m \lt 1.

(c) Over a sequence, for the truncated sampler qq,

KL(q ∥ p)=Eq[∑t−log⁡m(ht)],TV(q,p)≤Eq[∑t(1−m(ht))],\mathrm{KL}(q \,\|\, p) = \mathbb{E}_q\Big[\sum_t -\log m(h_t)\Big], \qquad \mathrm{TV}(q, p) \le \mathbb{E}_q\Big[\sum_t \big(1 - m(h_t)\big)\Big],

and the probability that pure sampling never leaves the kept sets is Eq[∏tm(ht)]\mathbb{E}_q\big[\prod_t m(h_t)\big].

(d) If every kept mass is at most 1−ε1 - \varepsilon, pure sampling reaches step nn inside the kept sets with probability at most (1−ε)n(1 - \varepsilon)^n. That is, the first nn draws happen and are all kept.

Proof.

(a) Any kk entries sum to at most the kk largest, so a set of mass at least pp has at least as many tokens as the shortest sorted prefix reaching pp.

(b) On SS, pS−p=p (1/m−1)≥0p_S - p = p\,(1/m - 1) \ge 0, so TV=m (1/m−1)=1−m\mathrm{TV} = m\,(1/m - 1) = 1 - m, and KL(pS ∥ p)=∑w∈SpS(w)log⁡(1/m)=−log⁡m\mathrm{KL}(p_S \,\|\, p) = \sum_{w \in S} p_S(w) \log(1/m) = -\log m. In the other direction pSp_S is zero where pp is not.

(c) The KL identity is the chain rule for KL: step tt contributes −log⁡m(ht)-\log m(h_t), averaged over the prefixes qq visits. For TV, couple the two samplers step by step with a maximal coupling; they agree until the first decoupling, which happens at step tt with probability 1−m(ht)1 - m(h_t) given agreement so far, and a union bound finishes. For the last identity, ∑y∈supp⁡qp(y)=∑yq(y) p(y)/q(y)\sum_{y \in \operatorname{supp} q} p(y) = \sum_y q(y)\, p(y)/q(y) with p(y)/q(y)=∏tm(ht)p(y)/q(y) = \prod_t m(h_t).

(d) Let AnA_n be the event in the statement. Given An−1A_{n-1} and its prefix hnh_n, the nn-th draw is kept with probability m(hn)≤1−εm(h_n) \le 1 - \varepsilon, so Pr⁡(An)≤(1−ε)Pr⁡(An−1)\Pr(A_n) \le (1 - \varepsilon) \Pr(A_{n-1}). A string that halts before step nn is not in AnA_n, and it has to be left out: if the root gives eos\mathrm{eos} probability 0.90.9 and only eos\mathrm{eos} is kept, 0.90.9 of draws never leave the kept sets.

∎

The harness checks (a) against every subset of 200200 random eight-token distributions, and (c) by exact enumeration on 3030 random trees under every rule. Parts (c) and (d) make Holtzman and colleagues’ “unreliable tail” exact, and over a whole sentence it is not rare. On the trigram, a pure sample stays inside the 0.950.95-nucleus at every step with probability 0.7830.783, measured directly, or 0.7750.775 through the identity in (c) under nucleus sampling. So about one continuation in five draws at least one tail token. That figure comes from (c): a row’s nucleus can keep nearly all of its mass, so (d) gives no useful bound here.

A · The temperature dial — one next-token distribution as τ slides
1.00
the twelve likeliest of 3426 tokens, at τ = 1.0000.20.40.60.81cloudsoftwarechiefand</s>hasisaoutlookheldguidedreported
entropy H(p_τ), nats
1.461
log–log (Zipf) slope
-0.954
log–log slope at τ = 1
-0.954
expected log-probability E[log p]
-1.461

Entropy only rises as τ rises (Theorem 2), and the log–log slope is always the τ = 1 slope divided by τ (Proposition 2): temperature tilts Topic 1’s rank–frequency line, and its intercept moves too. Near τ = 0 the mass sits on the likeliest token; at large τ it spreads over all 3426 tokens.

B · Where each rule cuts — kept tokens, the cost of the cut, and the seen set
0.9
kept tokens in color; a green dot marks a word seen after this context in training00.20.40.60.81cloudsoftwarechiefand</s>hasisaoutlookheldguidedreported
tokens kept
4 of 3426
kept mass m
0.907
TV = 1 − m
0.093
KL(p_S ‖ p) = −log m
0.098
precision vs seen set
0.750
recall vs seen set
1.000
words seen after this context
3

Every cut costs exactly 1 − m in total variation and −log m in KL (Theorem 4). The Kneser–Ney row knows which words it saw after this context (Proposition 4), but the rules see only probabilities: no single setting of any rule keeps exactly the seen words on every prompt.

C · Local against global temperature — #14’s lab tree
1.00
after “revenue”: each finished string’s probability under the two samplerswas flat (mode)0.238 / 0.238fell sharply0.110 / 0.110fell0.090 / 0.090rose slightly0.088 / 0.088rose sharply (greedy)0.086 / 0.086was lower0.070 / 0.070rose sharply on demand0.058 / 0.058rose on demand0.050 / 0.050rose on pricing0.050 / 0.050was flat on pricing0.042 / 0.042rose in asia0.041 / 0.041rose in europe0.041 / 0.041rose slightly on pricing0.038 / 0.038
per-step sampler q_τ (temper every row)tempered model π_τ ∝ p(y)^(1/τ)
TV(q_τ, π_τ)
0.000
q_τ on greedy’s “rose sharply”
0.086
π_τ on the mode “was flat”
0.238

At τ = 1 the two coincide. Cool the dial and they part (Theorem 3): the per-step sampler collapses onto greedy’s string, the tempered model onto the mode.

D · One frontier — 188 prompts × 8 draws per setting
1
each setting’s samples: nats per word under the model (x) and under the oracle (y)11.522.533.540.511.522.533.5held-out textexact mode (#14)per-word NLL under the generating model (→ further into its tail)per-word NLL under the oracle
temperaturetop-knucleusmin-pηtypical
NLL under the model
2.348
NLL under the oracle
2.500
distinct-2
0.384
a training sentence verbatim
0.125
KL(q ‖ p) per word
0.000
mean words
7.900

Every rule lands on nearly the same curve: how much it cuts matters more than how. The held-out text (2.576 under the model, 1.968 under the oracle) is out of reach of these settings. At its own model NLL the curve runs well above it, partly because of rare words the oracle lumps together, and partly through the model’s error.

E · Boilerplate against fabrication — what lowering τ does to a fact the model half knows
1.00
P(the knowledge base’s answer), solid, and P(another answer), dashed — exact00.20.40.60.810.050.10.20.512510temperature τ (log scale)
seen twice or more (30 probes)seen once (33 probes)never seen (48 probes)
seen twice or more: correct / wrong
0.727 / 0.198
seen once: correct / wrong
0.240 / 0.544
never seen: correct / wrong
0.064 / 0.699
Ashcombe Controls operates in the …seen twice or more (5×)KB: industrials
banking 0.008energy 0.008healthcare 0.008industrials 0.881retail 0.008technology 0.050
P(“industrials”) at τ = 1.00: 0.881
Copperleaf Markets operates in the …seen once (1×)KB: retail
banking 0.038energy 0.038healthcare 0.038industrials 0.283retail 0.161technology 0.248
P(“retail”) at τ = 1.00: 0.161
Brackenbury Lending operates in the …never seen (0×)KB: banking
banking 0.043energy 0.043healthcare 0.043industrials 0.323retail 0.043technology 0.283
P(“banking”) at τ = 1.00: 0.043

Lowering τ sharpens whatever the model believes. For contexts it saw twice or more, that removes the smoothing mass and with it every fabrication. For a context it saw once, the discounted count competes with the prior, and where the prior wins, a cold sampler states the wrong answer with certainty; on the way there, a little cooling raises fabrication before a lot of it lowers it. For contexts it never saw, cooling moves the mass on non-answers onto answers, and fabrication rises.


Truncation as desmoothing

Hewitt, Manning, and Liang (2022) read truncation as undoing smoothing. They model a language model as a mixture of a true distribution with a near-uniform smoothing distribution (their Eq. 3), argue for absolute and relative probability thresholds (§3.4), and describe recovering the true support (§4.4, App. A.2). The uniform case is exact.

Proposition 3 (Uniform desmoothing).

If p=(1−λ)p⋆+λ/∣V∣p = (1 - \lambda)p^\star + \lambda/|V| with λ<1\lambda \lt 1, then {w:pw>λ/∣V∣}=supp⁡p⋆\{w : p_w \gt \lambda/|V|\} = \operatorname{supp} p^\star.

Proof.

pw=λ/∣V∣p_w = \lambda/|V| exactly when pw⋆=0p^\star_w = 0, and pw>λ/∣V∣p_w \gt \lambda/|V| otherwise.

∎

A Kneser–Ney model wears its smoothing openly, which lets us test the reading on a real decomposition.

Proposition 4 (Kneser–Ney desmoothing).

For interpolated Kneser–Ney with discount D<1D \lt 1 and a context hh with c(h)>0c(h) \gt 0,

p(w∣h)  =  max⁡(c(hw)−D,0)c(h)+γ(h) plower(w∣h−),p(w \mid h) \;=\; \frac{\max(c(hw) - D, 0)}{c(h)} + \gamma(h)\, p_{\mathrm{lower}}(w \mid h^-),

and the seen set {w:c(hw)>0}\{w : c(hw) \gt 0\} is exactly {w:p(w∣h)>γ(h) plower(w∣h−)}\{w : p(w \mid h) \gt \gamma(h)\, p_{\mathrm{lower}}(w \mid h^-)\}. The backoff term varies from word to word, so no single threshold on p(w∣h)p(w \mid h) recovers the seen set in general.

Proof.

This is the n-gram topic’s recursion. A seen word has c(hw)≥1>Dc(hw) \ge 1 \gt D, so its first term is positive; an unseen word has first term zero.

∎

On the 177177 prompt rows whose context the trigram has seen, the seen set averages 5.3455.345 words. On 0.8470.847 of those rows every seen word outranks every unseen one, so a threshold chosen for that row would recover it. But no setting of any of the five rules recovers the seen set on every row: each trades precision against recall, as Figure B shows on five prompts. Truncation rules see only probabilities, and probability alone does not say which mass is smoothing.


Typicality

Proposition 5 (Samples are typical of the model).

Under the model, Ep[−log⁡p(Y∣x)]=Ep[∑tH(p(⋅∣ht))]\mathbb{E}_p[-\log p(Y \mid x)] = \mathbb{E}_p\big[\sum_t H(p(\cdot \mid h_t))\big], and Mn=∑t≤n(−log⁡p(Yt∣ht)−H(ht))M_n = \sum_{t \le n} \big(-\log p(Y_t \mid h_t) - H(h_t)\big) is a martingale.

Proof.

Given hth_t, the surprisal −log⁡p(Yt∣ht)-\log p(Y_t \mid h_t) has conditional mean H(ht)H(h_t), so every increment of MnM_n has conditional mean zero. Taking expectations gives the identity.

∎

A sample’s NLL tracks its own path’s entropy, and on a finite vocabulary with a probability floor the increments are bounded, so formalStatistics’ Azuma–Hoeffding inequality (its Theorem 7) makes the concentration exponential. For i.i.d. and stationary ergodic sources this is the asymptotic equipartition property (Cover and Thomas 2006, §3.1 and §16.8). The harness confirms E[M]=0\mathbb{E}[M] = 0 within four standard errors on both engines.

Proposition 5 places the samples. It says nothing about the text, which is a cross-entropy: the text’s own entropy plus a penalty for the model’s error. On the trigram the three per-word NLLs are 0.8350.835 for the exact mode, 2.3482.348 for pure samples, and 2.5762.576 for the held-out text, and they come from three different pools. The modes cover all 188188 prompts, the samples are 88 draws on each, and the text is the 417417 of 443443 sentences the trigram can score, on 182182 prompts at 11 to 1616 sentences each. Give the samples the text’s weights and, over five random streams, they cost 2.262.26–2.392.39 nats per word against the text’s 2.5762.576, and 20.120.1–22.722.7 nats per string on average against its 22.1722.17. That mean hides the shape. The median string costs 12.212.2–14.214.2 nats against the text’s 20.020.0, and strings of 66 to 1212 tokens cost 1.931.93–2.072.07 per word against its 2.542.54. At matched length the model finds the real text more surprising than its own output. The mode is nothing like a typical sample.

Definition 4 (Locally typical sampling).

Sort tokens by ∣−log⁡pw−H(h)∣|{-\log p_w} - H(h)| and keep them until their mass reaches the typical mass (Meister and colleagues 2023, Algorithm 5.3, greedy form).

Unlike the other rules, typical sampling can drop the head of a distribution: the likeliest token is also the most typical one on only 0.6170.617 of prompt rows, and on about 0.480.48 of the steps along pure samples. So tightening this rule need not make text more predictable. On the trigram, on all five streams, cost is U-shaped in the typical mass, with means of 1.651.65, 1.501.50, and 1.741.74 nats per word at masses 0.20.2, 0.50.5, and 0.90.9. On the decoder, masses 0.20.2 and 0.50.5 tie on the page’s training seed, and on three other seeds 0.20.2 is a little cheaper, so the U is the trigram’s and not a law of the rule.


Quality against diversity

We now sample both of the beam-search topic’s engines, the Kneser–Ney trigram over 3,4273{,}427 words and the toy causal transformer over 509509, 88 times on each of the same 188188 held-out MD&A prompts, under 2525 settings of the six families. Both are renormalized at each step to never emit the unknown-word token. Each setting becomes one point in Figure D:

  • the samples’ per-word NLL under the model that generated them, which measures how far into its own tail the sampler goes;
  • their per-word NLL under an oracle, a Kneser–Ney model fit to five times more text from the generator that wrote the training corpus (the device Caccia and colleagues 2020 use on synthetic data).

Lower oracle NLL means more like the generator’s text, though it also rewards blandness: the trigram’s exact modes score 1.0731.073. As τ\tau rises from 0.40.4 to 1.51.5, both NLLs and the share of distinct bigrams rise on both engines, and copying falls: over five random streams the mean copy rate falls at every step, though a single stream can tick up. On the lab’s stream the trigram copies a training sentence verbatim in 0.1480.148 of its finished samples at τ=0.5\tau = 0.5 and 0.0240.024 at τ=1.5\tau = 1.5; the decoder in 0.2260.226 and 0.0590.059. “Finished” matters at the hot end: at τ=1.5\tau = 1.5 only 0.760.76–0.780.78 of the trigram’s draws finish within its 4040-token cap, and about 0.940.94 of the decoder’s, and the NLLs and copy rates count those alone. As any truncation rule loosens, its KL to the model falls.

The rules do not differ much. Every truncation setting lies within 0.10.1 nats of the temperature curve at its own model NLL, on both engines. How much a rule cuts matters more than which rule cuts, which is Zhang and colleagues’ (2021) finding on large models seen in a small one. None of the settings reaches the held-out text, at 2.5762.576 under the trigram but only 1.9681.968 under the oracle. At that model NLL the temperature curve reads about 2.72.7, so there the text lies about three-quarters of a nat below it. Cold settings do go below 1.9681.968 on the oracle axis, but the curve reaches that cost at a model NLL of about 1.771.77. On each of the 2525 settings, oracle NLL minus model NLL is larger than the text’s −0.607-0.607, and the smallest margin on a stream is 0.250.25–0.290.29 nats across five streams. That is a fact about the settings run, not about decoding in general: past the grid the margin reaches zero near τ=1.75\tau = 1.75, and at τ=2\tau = 2, where only about a third of draws finish, it is negative on every stream.

Not all of that distance is the model’s error. 6.46.4 percent of the text’s tokens are outside the oracle’s vocabulary, against about 22 percent of the samples’. The oracle scores them all as one unknown word, at 3.043.04 nats each, and the trigram charges them 10.3110.31. On the other tokens the text costs 2.052.05 under the trigram and 1.901.90 under the oracle, and it lies about 0.440.44 nats below the temperature curve redrawn on those tokens, a mean over five streams against 0.750.75 on all tokens. That part is the model’s error, and none of these settings removes it.



Where this goes next

The calibration topic, next in this track, asks the question the finance case study raises: does a model’s probability mean anything? There temperature reappears with a different job, fitted to held-out data so that predicted probabilities match frequencies (Guo and colleagues 2017). The BLEU and ROUGE topic supplies the reference-based scores this page avoided.

Several decoding methods are outside our scope. Minimum Bayes risk decoding picks the sample with the highest expected similarity to the others. Contrastive search, classifier-free guidance, and speculative decoding change the objective or the speed. Mirostat (Basu and colleagues 2021) adjusts truncation online to hold a target perplexity.


Honest caveats


Implementation

The companion notebook (notebookPath) imports sampling_temperature_nucleus.py, which owns every number on this page. That module imports the beam-search topic’s module for the lab tree, the trigram, the trained decoder, and the prompts; the Zipf topic’s module for the log–log slope; and the n-gram and perplexity topics’ Kneser–Ney code for the oracle and the order-5 fact model. It implements temperature, the five truncation rules, exact enumeration on finite trees, and a sampler that draws 1,5041{,}504 strings per setting from either engine, on five random streams and, for the decoder, four training seeds. The lab shows stream 00 on seed 00. A harness of 3636 assertion-based tests runs in about two and a half minutes on a laptop CPU. The tests cover:

  • Theorem 1 by goodness of fit on 3131 trees, with the pooled leaves counted, and Proposition 1’s three claims on 200,000200{,}000 draws.
  • Theorem 2 against a numerical optimizer, its entropy derivative against a finite difference, and its limits on every trigram prompt; Proposition 2 exactly on every trigram prompt, and the moving intercept.
  • Theorem 3’s identity on 3030 random trees, its equality case on permutation trees, its limits and ties on the lab tree, and the divergence threshold.
  • Theorem 4 by brute force and exact enumeration under every rule, its tail identity on the trigram’s samples, and part (d) with its counterexample.
  • Propositions 3 and 4, including that no rule recovers the seen set; Proposition 5 on both engines, and the three pools on the text’s weights.
  • The frontier’s orderings, how often the head is typical, typical sampling’s cost on both engines, the copy rate and finished share over five streams, the text’s distance from the curve and its rare-word split, and every sampled string’s score against the engine.
  • The three fabrication regimes, the typical-sampling exception, the once-seen peak, cooling on never-seen contexts, what “seen” counts, and the decoder on the same probes.

The laboratory reads its data from a JSON file that one of those tests requires to equal the module’s viz_payload() exactly, so the figure cannot drift from the code.

References & Further Reading