Algorithmcore
Nucleus sampling
Also called top-p sampling.
Sample from the smallest set of most probable next tokens whose total probability reaches p, so the candidate set adapts to the shape.
- Solves
- Autoregressive decoding
- Time
- O(V log V) worst
- Space
- O(V) extra
- Where
- V = the vocabulary size |V|; m = the number of tokens in the nucleus
- Model
- Real RAM
- Properties
- randomizednot exactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes, Yejin Choi, 2020
Nucleus sampling, also called top-p sampling, generates text from an autoregressive language model one token at a time. At each step it sorts the next tokens by probability and keeps the shortest list from the top whose total probability is at least a threshold , such as 0.9 or 0.95. This list is the nucleus. It divides the kept probabilities by their sum and draws the next token from them. When the model is sure of the next token the nucleus has one or two tokens, and when the model is unsure it has many. That is the difference from top-k sampling, which keeps the same number of tokens at every step. Nucleus sampling is a heuristic method for autoregressive decoding. Holtzman et al. 2020 found that its output matched human text better than greedy decoding, beam search, pure sampling and top-k sampling on their measures, but that is a measurement on one model and one data set, not a property of the algorithm.
In plain words
The model gives a chance to every word that can come next. Sort the words from the most likely to the least likely. Walk down the list and add up the chances. Stop as soon as the total reaches a set share, for example 90%. Keep only the words you passed and draw one of them at random, in proportion to their chances. If one word is very likely, you keep only that word. If many words are about equally likely, you keep many. So the list grows and shrinks with the doubt of the model.
The problem
The model gives a distribution over the vocabulary for the prefix . Sort the tokens by probability from high to low, with the smaller index first on ties, and let be the mass of the first tokens. The nucleus is the first tokens, where is the smallest with . One step draws from
This is Equations 2 and 3 of Holtzman et al. 2020. The full output repeats the step until the end token </s> or a length limit. The output distribution is not the model distribution ; the method is defined by the rule.
The algorithm
The step takes , the threshold , and a number drawn uniformly from .
NUCLEUS-SAMPLE(P, p, u) ▷ P = next-token distribution, u uniform in [0, 1)- 1
order ← the tokens sorted by P, from high to low ▷ ties: the smaller index first - 2
c ← 0, K ← empty list - 3
for each i in order do - 4
c ← c + P[i], append i to K - 5
if c ≥ p then stop the loop - 6
Z ← c ▷ the mass of the nucleus K - 7
r ← u · Z - 8
c ← 0; for each i in K, in order do - 9
c ← c + P[i] - 10
if r < c then return i - 11
return the last i in K with P[i] > 0 ▷ only after rounding
Lines L7 to L10 are inverse transform sampling on the nucleus, with the bound moved to the random number so that nothing is divided.
Example
Take six next tokens with = (the 0.40, a 0.25, cat 0.15, dog 0.10, sat 0.06, ran 0.04), already sorted. The running masses are 0.40, 0.65, 0.80, 0.90, 0.96 and 1.
| nucleus | mass | renormalized | |
|---|---|---|---|
| 0.5 | the, a | 0.65 | the 0.6154, a 0.3846 |
| 0.9 | the, a, cat, dog | 0.90 | 0.4444, 0.2778, 0.1667, 0.1111 |
| 0.95 | the, a, cat, dog, sat | 0.96 | 0.4167, 0.2604, 0.15625, 0.1042, 0.0625 |
| 1 | all six | 1 | itself |
With the mass 0.90 reaches the threshold exactly at "dog", so "dog" is kept and "sat" is not.
Now take on two other steps. On a peaked step, = (0.90, 0.05, 0.03, 0.02), the first token already has mass 0.90, so the nucleus is that token alone and the step is greedy. On a flat step with ten tokens of 0.1 each, the nucleus has nine tokens. Top-k sampling with would keep three tokens in both cases.
Correctness
The proof is in proofs/correctness.md. It shows that the nucleus is a smallest set of tokens with mass at least , that among the sets of that size it has the largest mass, that it holds no token of probability 0, and that the step returns each token of the nucleus with probability exactly . The limits follow: for at most the largest probability the step is greedy, and for it samples from . The tests check the smallest size against all subsets on random distributions with Fraction probabilities, and check the draw exactly with on a fine grid.
Proof: The nucleus is a smallest set of mass at least p, and the draw follows the renormalized distributionfull
We use the notation of the page. The input is a distribution over the vocabulary , a threshold , and a number drawn uniformly from . We assume exact arithmetic, as with the Fractions of the tests; the last remark treats rounding.
Let be the order of line L1: the tokens sorted by the key . This order is unique. For let and , the mass of the first tokens. does not decrease in , and .
Lemma 1 (prefixes have maximum mass). For every and every set with , .
Proof. This is the exchange argument of top-k sampling: every token of is at least as probable as every token outside it, so replacing a token of by a token of never lowers the mass, and after at most such steps the set is .
Theorem 2 (the nucleus is a smallest set). Let be the smallest with . Lines L2 to L5 return . No set of fewer than tokens has mass at least . Among the sets of tokens, has the largest mass.
Proof. After the pass of line L4 for the token , the running sum is , by induction on from (line L2). Line L5 returns at the first with , which is . Such a exists since . If a set with had , then by Lemma 1, against the choice of . The last claim is Lemma 1 with .
Corollary 3 (no zero tokens). The nucleus has no token of probability 0.
Proof. The zero tokens come last in the order. If had probability 0, then , against the choice of .
Theorem 4 (the draw). Let . NUCLEUS-SAMPLE returns each token of the nucleus with probability , and never returns a token outside the nucleus.
Proof. Line L7 sets , uniform on . Lines L8 to L10 walk the nucleus in the order of line L1 with the running sum and return for the unique with . That interval has length , so is returned with probability . Since , the walk always returns inside the loop, and line L11 is not reached.
Corollary 5 (limits). For , the nucleus is the first most probable token and the step is greedy decoding. For , the nucleus is the set of all tokens of positive probability, and the step samples from .
Proof. For the first claim, , so . For the second, exactly when holds every token of positive probability, and by Corollary 3 the nucleus holds no other.
Remark (rounding). With floats, the running sum can stay below where the exact sum reaches it. For and , the float sum is , so the code keeps 3 tokens where exact arithmetic keeps 2. In the extreme case the sum stays below up to the end, and the code then keeps every token of positive probability, which is the result for . In the draw, and the running sum can differ in the last bits and can round up, and line L11 then returns the last kept token of positive probability. These events change the result only at the boundary of the threshold, by an amount of the order of the rounding error.
Complexity
One step costs with a full sort, plus for the prefix sums and the draw, where is the size of the nucleus. The size is not known in advance, so a plain top-k selection does not apply directly. A selection that splits the tokens around a pivot and recurses on the side that holds the boundary, as in quickselect but with the mass in place of the count, finds the nucleus in expected time, plus to sort it. The extra space is . On a GPU, frameworks usually sort the whole row; for a large model the call of the network costs far more than the sort.
Properties
- Randomized. Fix the seed of the random source to reproduce an output.
- Adaptive size. The nucleus can have any size from 1 to , and it changes from step to step with the shape of .
- Smallest set. No set of fewer tokens reaches mass , and the nucleus has the largest mass among the sets of its size.
- Depends on the temperature. Unlike top-k, the nucleus depends on the values of the probabilities, not only on their order. On the logits (2, 1, 0), the temperature gives (0.665, 0.245, 0.090) and keeps two tokens, while gives (0.867, 0.117, 0.016) and keeps one.
- Limits. A very small gives greedy decoding, and gives ancestral sampling.
Variants and improvements
- With temperature. Apply the temperature to the logits, then take the nucleus (temperature sampling). The order of the two operations matters.
- With top-k. Many libraries apply top-k first and then top-p, so that the nucleus never has more than tokens.
- Typical sampling. Order the tokens by how close their surprisal is to the entropy of the step, in place of their probability, and keep a prefix of mass (typical sampling).
- A minimum probability. Keep the tokens with probability at least a fixed share of the largest probability. Like the nucleus, this adapts to the shape of the distribution.
- Contrastive search. A deterministic alternative that scores the top candidates with a penalty for similarity to the context (contrastive search).
When to use it
Use nucleus sampling for open-ended generation, such as stories, dialogue and chat, where varied text is wanted. Values of from 0.9 to 0.95 are common, often with a temperature below 1. It is the default sampler of many systems. For tasks with a single correct answer, such as translation, short factual answers or code that must compile, greedy decoding or beam search is usually better, and for reasoning tasks several samples can be combined by self-consistency.
Pitfalls
- Rounding at the threshold. With floats, , so on with the code keeps three tokens, while exact arithmetic keeps two. The difference is real but small; do not write tests that depend on an exact boundary in floats.
- Ties at the boundary. Equal probabilities at the last position make the nucleus depend on the tie rule. Fix it if outputs must be reproducible.
- The order of the filters. Temperature then top-p, top-p then temperature, and top-k then top-p all give different distributions, and libraries differ. State what you use.
- A long flat tail. On a very flat step the nucleus can hold thousands of tokens, and some of them are poor. A temperature below 1 or a top-k cap limits this.
- Quality is measured, not proved. The claim that nucleus sampling gives better text than top-k is a result of human and automatic evaluations on particular models.
Implementations
The code takes the next-token probabilities (or logits) as given and implements the nucleus and the draw; it does not run or train a network.
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
nucleus_sampling.py 75 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nucleus-sampling/. The authors are listed in prov/G371BC.jsonl.
"""Nucleus (top-p) sampling of the next token.
A next-token distribution is a list of probabilities, one per token of the
vocabulary, in the order of the vocabulary. The values can be floats or
Fractions; with Fractions the set and the distribution are exact, and the
threshold p should then be a Fraction too. 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 probabilities of the model as
given; it does not run or train a network.
"""
from typing import List, Sequence
from nlslog import softmax
def _check(p) -> None:
if not 0 < p <= 1:
raise ValueError("the threshold p must be in (0, 1]")
def nucleus_set(probs: Sequence, p) -> List[int]:
"""Return the nucleus: the shortest prefix of the sorted tokens with mass >= p.
The tokens are sorted by probability from high to low, with the smaller
index first on ties. If rounding keeps the running sum below p up to the
end, every token of positive probability is kept.
"""
_check(p)
order = sorted(range(len(probs)), key=lambda i: (-probs[i], i)) # @line L1
c = probs[order[0]] * 0 # @line L2
for t, i in enumerate(order): # @line L3
c = c + probs[i] # @line L4
if c >= p: # @line L5
return order[: t + 1]
return [i for i in order if probs[i] > 0]
def nucleus_distribution(probs: Sequence, p) -> list:
"""Return the renormalized distribution on the nucleus, 0 elsewhere."""
kept = nucleus_set(probs, p)
z = sum(probs[i] for i in kept)
q = [probs[i] * 0 for i in range(len(probs))]
for i in kept:
q[i] = probs[i] / z
return q
def nucleus_sample(probs: Sequence, p, rng) -> int:
"""Draw one token index from the nucleus distribution of probs.
The draw is inverse transform sampling over the nucleus in sorted order,
with r = u Z for the nucleus mass Z, so nothing is divided.
"""
kept = nucleus_set(probs, p) # @line L1
z = sum(probs[i] for i in kept) # @line L6
r = rng.random() * z # @line L7
c = probs[kept[0]] * 0
for i in kept: # @line L8
c = c + probs[i] # @line L9
if r < c: # @line L10
return i
return [i for i in kept if probs[i] > 0][-1] # @line L11
def nucleus_sample_logits(logits: Sequence[float], p, rng, temperature: float = 1.0) -> int:
"""Nucleus sampling from logits: softmax with the temperature, then nucleus_sample.
Unlike top-k, the nucleus depends on the temperature: a lower T makes the
distribution peaked and the nucleus smaller.
"""
return nucleus_sample(softmax(logits, temperature), p, rng)
test_nucleus_sampling.py 137 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nucleus-sampling/. The authors are listed in prov/G371BC.jsonl.
import itertools
import random
from fractions import Fraction as F
from nlslog import argmax
from nucleus_sampling import nucleus_distribution, nucleus_sample, nucleus_sample_logits, nucleus_set
# the, a, cat, dog, sat, ran
P = [F(2, 5), F(1, 4), F(3, 20), F(1, 10), F(3, 50), F(1, 25)]
class GridU:
"""A fake random source that returns the points j / n, j = 0 ... n - 1, in turn."""
def __init__(self, n):
self.n = n
self.j = 0
def random(self):
u = F(self.j, self.n)
self.j += 1
return u
def random_fractions(rng, n):
w = [rng.randint(0, 9) for _ in range(n)]
if sum(w) == 0:
w[0] = 1
return [F(x, sum(w)) for x in w]
def test_example_values() -> None:
assert nucleus_set(P, F(1, 2)) == [0, 1]
assert nucleus_set(P, F(13, 20)) == [0, 1]
assert nucleus_set(P, F(9, 10)) == [0, 1, 2, 3]
assert nucleus_distribution(P, F(9, 10)) == [F(4, 9), F(5, 18), F(1, 6), F(1, 9), 0, 0]
assert nucleus_set(P, F(95, 100)) == [0, 1, 2, 3, 4]
assert sum(P[i] for i in nucleus_set(P, F(95, 100))) == F(24, 25)
assert nucleus_set(P, F(1)) == [0, 1, 2, 3, 4, 5]
def test_smallest_set_brute_force() -> None:
rng = random.Random(1)
for _ in range(250):
n = rng.randint(1, 7)
probs = random_fractions(rng, n)
for p in (F(1, 10), F(1, 3), F(1, 2), F(7, 10), F(9, 10), F(1)):
kept = nucleus_set(probs, p)
mass = sum(probs[i] for i in kept)
assert mass >= p
sizes = [
len(c)
for m in range(1, n + 1)
for c in itertools.combinations(range(n), m)
if sum(probs[i] for i in c) >= p
]
assert len(kept) == min(sizes)
# among the smallest sets, the nucleus has the largest mass
best = max(sum(probs[i] for i in c) for c in itertools.combinations(range(n), len(kept)))
assert mass == best
# no proper prefix reaches p
assert sum(probs[i] for i in kept[:-1]) < p
def test_adapts_to_the_shape() -> None:
peaked = [F(90, 100), F(5, 100), F(3, 100), F(2, 100)]
flat = [F(1, 10)] * 10
assert len(nucleus_set(peaked, F(9, 10))) == 1
assert len(nucleus_set(flat, F(9, 10))) == 9
def test_float_rounding_pitfall() -> None:
assert 0.7 + 0.2 < 0.9
assert nucleus_set([0.7, 0.2, 0.1], 0.9) == [0, 1, 2]
assert nucleus_set([F(7, 10), F(2, 10), F(1, 10)], F(9, 10)) == [0, 1]
def test_zero_mass_tokens_stay_out() -> None:
assert nucleus_set([F(1, 2), F(0), F(1, 2)], F(1)) == [0, 2]
assert nucleus_set([0.5, 0.0, 0.5], 1.0) == [0, 2]
# a float sum that never reaches 1
probs = [0.1] * 10 + [0.0]
c = 0.0
for x in probs:
c = c + x
assert c < 1.0
assert nucleus_set(probs, 1.0) == list(range(10))
def test_inverse_transform_is_exact_on_a_grid() -> None:
n = 18 * 400
q = nucleus_distribution(P, F(9, 10))
src = GridU(n)
counts = [0] * len(P)
for _ in range(n):
counts[nucleus_sample(P, F(9, 10), src)] += 1
assert [F(c, n) for c in counts] == q
def test_sampling_frequencies() -> None:
rng = random.Random(3)
probs = [float(x) for x in P]
draws = 20000
counts = [0] * len(P)
for _ in range(draws):
counts[nucleus_sample(probs, 0.85, rng)] += 1
expected = [4 / 9, 5 / 18, 1 / 6, 1 / 9, 0.0, 0.0]
for c, e in zip(counts, expected):
assert abs(c / draws - e) < 0.01
assert counts[4:] == [0, 0]
def test_small_p_is_greedy_and_temperature_changes_the_set() -> None:
rng = random.Random(4)
for _ in range(200):
probs = [rng.random() + 0.01 for _ in range(6)]
s = sum(probs)
probs = [x / s for x in probs]
assert nucleus_set(probs, 1e-9) == [argmax(probs)]
logits = [2.0, 1.0, 0.0]
# T = 1 gives (0.665, 0.245, 0.090), T = 0.5 gives (0.867, 0.117, 0.016)
assert nucleus_sample_logits(logits, 0.8, rng, temperature=0.5) == 0
seen = {nucleus_sample_logits(logits, 0.8, rng, temperature=1.0) for _ in range(500)}
assert seen == {0, 1}
def test_bad_threshold() -> None:
for p in (0, -0.1, 1.5):
try:
nucleus_set(P, p)
except ValueError:
pass
else:
raise AssertionError("no ValueError")
History
Holtzman, Buys, Du, Forbes and Choi posted "The curious case of neural text degeneration" on arXiv in 2019 and published it at ICLR 2020. They generated 5,000 passages of at most 200 tokens with GPT-2 Large, conditioned on prefixes of held-out web text, and compared the decoding methods with human text. Greedy decoding had 73.66% repeated text and beam search with had 28.94%, against 0.28% for human text. Pure sampling had a perplexity of 22.73, far above the 12.38 of human text, because it drew too many tokens from the unreliable tail. Nucleus sampling with had a perplexity of 13.13, repetition of 0.36% and the highest HUSE score in their Table 1, 0.97, a measure that combines human judgments of quality with the probability of the text under the model. The paper also named the problem of dull, repetitive and incoherent output "neural text degeneration" (see inadequacy of the mode).
References
- Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes and Yejin Choi, The curious case of neural text degeneration, ICLR 2020, Section 3.1 (the top-p vocabulary V(p) of Equation 2 and the rescaled distribution of Equation 3), Section 3.2 (top-k), Section 3.3 (temperature), and Table 1 (perplexity, Self-BLEU4, Zipf coefficient, repetition and HUSE of the decoding methods on GPT-2 Large)
- Angela Fan, Mike Lewis and Yann Dauphin, Hierarchical neural story generation, ACL 2018, pages 889 to 898, Section 5.4, top-k random sampling, the fixed-size method that nucleus sampling replaces
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 | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag G371BC Edit this page History Report an error Markdown