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 , “was” with , and “fell” with . The most probable sentence, the mode, is “revenue was flat” at ; greedy decoding finds “revenue rose sharply” at . 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 nats per word and the held-out sentences cost . This page adds a third number: the model’s own samples cost (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:
- 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.
- Temperature is a Gibbs distribution. Dividing logits by trades expected score against entropy. The entropy only rises with , and the log–log slope of the distribution divides by .
- Per-step temperature is not a tempered model. Its cold limit is greedy decoding, not the mode, and above the tempered model may not exist.
- Truncation has an exact price. A cut that keeps mass costs in total variation and in KL, and over a sentence the KL adds up exactly.
- 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 for the end mark </s>, and for the prefix before step .
Definition 1 (Ancestral sampling).
Given a prompt , draw , then for , until is drawn.
Theorem 1 (Sampling is exact).
(i) For every finite string ending in , ancestral sampling returns with probability exactly .
(ii) It halts with probability , so it halts almost surely if and only if the model is consistent.
Proof.
(i) Given the prefix , the draw has law . So the probability of drawing in order is the product of these conditional probabilities, , by the chain rule.
(ii) The events “the sampler returns ” are disjoint for different finite , and their union is the event that it halts. By (i), .
∎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 samples from the lab tree and from random trees, and tests each tree’s fit by . It also checks every leaf with an expected count of at least against ; on the random trees the other of leaves are pooled into one 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 and let be independent standard Gumbel variables, with CDF . Then , and is Gumbel with location , independent of the argmax.
Proof.
Write . The density of at is , and . So
which factors into times the Gumbel CDF with location at .
∎So a draw from is the argmax of 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 strings are an exact sample without replacement (their Theorem 1, Gumbel-top-). 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 and ,
Figure A of the laboratory below shows one such distribution as slides. Near the mass sits on the likeliest token; at large 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 and :
(a) is the unique maximizer over the simplex of , and the maximum is .
(b) , with equality only when is constant on the support. The expected score is nonincreasing in .
(c) As , tends to the uniform distribution on ; as , to the uniform distribution on the support.
Proof.
(a) Write , so that . For any , . Gibbs’ inequality makes the KL term non-negative, and zero only at .
(b) Put and . This is a log-partition function, so and . Since , we get , and turns this into . Also .
(c) Divide numerator and denominator of by and let or .
∎Part (a) is the maximum-entropy principle of Jaynes (1957) with as the energy: temperature prices entropy against expected score. Part (b) is formalStatistics’ log-partition theorem (its Theorem 7.1) applied to the family , an exponential family with sufficient statistic and natural parameter . 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 random score vectors, and (b) as monotone entropy on a -point grid of 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 against is the slope of divided by . A Zipf() distribution becomes a Zipf() distribution.
Proof.
Tempering preserves ranks, and . 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 shifts the whole line: on a Zipf() row over ranks, takes the log-probability at rank from to , and the two lines cross near rank . Sampled text mixes many contexts, so its own rank–frequency slope only roughly follows .
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 be the per-step tempered sampler, and , with , the tempered sequence distribution, when that sum is finite.
(a) . So if and only if takes the same value for every string in the support.
(b) With and the Rényi entropy of order ,
For , 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 , concentrates on greedy’s string and on the mode.
Proof.
(a) Substitute Definition 2 into the product; the numerators multiply to .
(b) By definition , so . Divide (a) by and take logarithms.
(c) Along greedy’s path, each tends to the point mass on that prefix’s unique argmax. The path has finitely many steps, so of greedy’s string tends to . Likewise 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 , and the forced row contributes . The forced row has to be excepted, because the last row of a same-length string puts all its mass on . The harness checks the equality on such trees, and checks the identity in (b) on 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 they are apart in total variation: the per-step sampler puts on greedy’s “rose sharply” while the tempered model puts 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 , can be infinite. Take the beam-search topic’s stationary model: words of probability each and of probability , after every prefix. Then
a geometric series with ratio . For and it diverges once . The per-step sampler exists at every temperature; “the model at temperature ” does not.
Truncation: top-k, nucleus, min-p, η, and typical
Definition 3 (Truncation).
A truncation rule keeps a set at each prefix and samples from , where is the kept mass. With the probabilities sorted as :
- top- keeps the largest;
- nucleus() keeps the shortest prefix of the sorted order whose mass reaches ;
- min-() keeps every with ;
- keeps every with , where is the row’s entropy;
- typical sorts tokens by and keeps them until their mass reaches the typical mass.
Ties go to the lower token id.
Fan, Lewis, and Dauphin (2018) popularized top-; Holtzman and colleagues (2020) introduced the nucleus; Nguyen and colleagues (2025) min-; Hewitt, Manning, and Liang (2022) ; 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 , and the most mass among sets of its size. Top- has the most mass among sets of tokens.
(b) At one step, and , while whenever .
(c) Over a sequence, for the truncated sampler ,
and the probability that pure sampling never leaves the kept sets is .
(d) If every kept mass is at most , pure sampling reaches step inside the kept sets with probability at most . That is, the first draws happen and are all kept.
Proof.
(a) Any entries sum to at most the largest, so a set of mass at least has at least as many tokens as the shortest sorted prefix reaching .
(b) On , , so , and . In the other direction is zero where is not.
(c) The KL identity is the chain rule for KL: step contributes , averaged over the prefixes visits. For TV, couple the two samplers step by step with a maximal coupling; they agree until the first decoupling, which happens at step with probability given agreement so far, and a union bound finishes. For the last identity, with .
(d) Let be the event in the statement. Given and its prefix , the -th draw is kept with probability , so . A string that halts before step is not in , and it has to be left out: if the root gives probability and only is kept, of draws never leave the kept sets.
∎The harness checks (a) against every subset of random eight-token distributions, and (c) by exact enumeration on 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 -nucleus at every step with probability , measured directly, or 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.
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.
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.
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.
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.
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 with , then .
Proof.
exactly when , and 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 and a context with ,
and the seen set is exactly . The backoff term varies from word to word, so no single threshold on recovers the seen set in general.
Proof.
This is the n-gram topic’s recursion. A seen word has , so its first term is positive; an unseen word has first term zero.
∎On the prompt rows whose context the trigram has seen, the seen set averages words. On 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, , and is a martingale.
Proof.
Given , the surprisal has conditional mean , so every increment of 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 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 for the exact mode, for pure samples, and for the held-out text, and they come from three different pools. The modes cover all prompts, the samples are draws on each, and the text is the of sentences the trigram can score, on prompts at to sentences each. Give the samples the text’s weights and, over five random streams, they cost – nats per word against the text’s , and – nats per string on average against its . That mean hides the shape. The median string costs – nats against the text’s , and strings of to tokens cost – per word against its . 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 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 of prompt rows, and on about 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 , , and nats per word at masses , , and . On the decoder, masses and tie on the page’s training seed, and on three other seeds 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 words and the toy causal transformer over , times on each of the same held-out MD&A prompts, under 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 . As rises from to , 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 of its finished samples at and at ; the decoder in and . “Finished” matters at the hot end: at only – of the trigram’s draws finish within its -token cap, and about 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 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 under the trigram but only under the oracle. At that model NLL the temperature curve reads about , so there the text lies about three-quarters of a nat below it. Cold settings do go below on the oracle axis, but the curve reaches that cost at a model NLL of about . On each of the settings, oracle NLL minus model NLL is larger than the text’s , and the smallest margin on a stream is – 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 , and at , where only about a third of draws finish, it is negative on every stream.
Not all of that distance is the model’s error. percent of the text’s tokens are outside the oracle’s vocabulary, against about percent of the samples’. The oracle scores them all as one unknown word, at nats each, and the trigram charges them . On the other tokens the text costs under the trigram and under the oracle, and it lies about nats below the temperature curve redrawn on those tokens, a mean over five streams against 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 strings per setting from either engine, on five random streams and, for the decoder, four training seeds. The lab shows stream on seed . A harness of 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 trees, with the pooled leaves counted, and Proposition 1’s three claims on 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 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
- paper The Curious Case of Neural Text Degeneration — Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes, and Yejin Choi (2020) ICLR 2020. Nucleus sampling: the top-p vocabulary (their Eq. 2) and its rescaled distribution (Eq. 3), and the unreliable tail of Theorem 4(c)
- paper Hierarchical Neural Story Generation — Angela Fan, Mike Lewis, and Yann Dauphin (2018) ACL 2018, 889–98. Sampling from the k = 10 most likely candidates (§5.4), the use that popularized top-k sampling
- paper Truncation Sampling as Language Model Desmoothing — John Hewitt, Christopher D. Manning, and Percy Liang (2022) Findings of EMNLP 2022, 3414–27. The smoothing model (their Eq. 3), the absolute and relative probability principles (§3.4), η-sampling and support recovery (§4.4, App. A.2)
- paper Locally Typical Sampling — Clara Meister, Tiago Pimentel, Gian Wiher, and Ryan Cotterell (2023) Transactions of the Association for Computational Linguistics 11: 102–21. The locally typical set (their Definition 3.5) and the sampler of Algorithm 5.3, in the greedy form of their erratum
- paper Turning Up the Heat: Min-p Sampling for Creative and Coherent LLM Outputs — Nguyen Nhat Minh, Andrew Baker, Clement Neo, Allen Roush, Andreas Kirsch, and Ravid Shwartz-Ziv (2025) ICLR 2025. The threshold p_base · p_max of their §3.1
- paper Mirostat: A Neural Text Decoding Algorithm that Directly Controls Perplexity — Sourya Basu, Govardana Sachitanandam Ramachandran, Nitish Shirish Keskar, and Lav R. Varshney (2021) ICLR 2021. A feedback controller that targets a perplexity, outside this page's scope
- paper The Relationship between Luce's Choice Axiom, Thurstone's Theory of Comparative Judgment, and the Double Exponential Distribution — John I. Yellott Jr. (1977) Journal of Mathematical Psychology 15 (2): 109–44. The argmax half of Proposition 1
- paper A* Sampling — Chris J. Maddison, Daniel Tarlow, and Tom Minka (2014) NeurIPS 27. The Gumbel-max trick and the independence of the maximum and the argmax (their Eqs. 1–2)
- paper Stochastic Beams and Where to Find Them: The Gumbel-Top-k Trick for Sampling Sequences Without Replacement — Wouter Kool, Herke van Hoof, and Max Welling (2019) ICML 2019, PMLR 97: 3499–508. Gumbel-top-k (their Theorem 1) and stochastic beam search
- paper Information Theory and Statistical Mechanics — E. T. Jaynes (1957) Physical Review 106 (4): 620–30. The maximum-entropy reading of Gibbs distributions behind Theorem 2
- paper Optimization by Simulated Annealing — S. Kirkpatrick, C. D. Gelatt Jr., and M. P. Vecchi (1983) Science 220 (4598): 671–80. Annealing: lowering the temperature of a Gibbs distribution toward its minimum
- paper A Learning Algorithm for Boltzmann Machines — David H. Ackley, Geoffrey E. Hinton, and Terrence J. Sejnowski (1985) Cognitive Science 9 (1): 147–69. Temperature in neural networks
- paper Language GANs Falling Short — Massimo Caccia, Lucas Caccia, William Fedus, Hugo Larochelle, Joelle Pineau, and Laurent Charlin (2020) ICLR 2020. Temperature sweeps as quality–diversity curves, oracle NLL on synthetic data, and the observation that per-token temperature differs from tempering the joint (§3)
- paper Long Horizon Temperature Scaling — Andy Shih, Dorsa Sadigh, and Stefano Ermon (2023) ICML 2023, PMLR 202: 31422–34. Myopic temperature scaling is not the tempered joint distribution (their §2.1), with its per-step normalizer written out (their Eqs. 2–3)
- paper Globally Normalized Transition-Based Neural Networks — Daniel Andor, Chris Alberti, David Weiss, Aliaksei Severyn, Alessandro Presta, Kuzman Ganchev, Slav Petrov, and Michael Collins (2016) ACL 2016, 2442–52. Locally normalized models are strictly less expressive than globally normalized ones (their Theorem 3.1), the label-bias relative of Theorem 3
- book Elements of Information Theory — Thomas M. Cover and Joy A. Thomas (2006) 2nd ed., Wiley. The asymptotic equipartition property (§3.1) and the Shannon–McMillan–Breiman theorem (§16.8) behind Proposition 5
- paper Trading Off Diversity and Quality in Natural Language Generation — Hugh Zhang, Daniel Duckworth, Daphne Ippolito, and Arvind Neelakantan (2021) Proceedings of the Workshop on Human Evaluation of NLP Systems, 25–33. Temperature, top-k, and nucleus compared along one quality–diversity curve
- paper On Calibration of Modern Neural Networks — Chuan Guo, Geoff Pleiss, Yu Sun, and Kilian Q. Weinberger (2017) ICML 2017, PMLR 70: 1321–30. Temperature scaling as calibration, the subject of the next topic