Algorithm Search⌘K

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.

Time
O(V log V) worst
Space
O(V) extra
Where
V = the vocabulary size |V|; m = the number of tokens in the nucleus
Properties
randomizednot exactonlineiterative
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 pp, 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 P=P(⋅∣y<t)P = P(\cdot \mid y_{<t}) over the vocabulary VV for the prefix y<ty_{<t}. Sort the tokens by probability from high to low, with the smaller index first on ties, and let M(m)M(m) be the mass of the first mm tokens. The nucleus V(p)V^{(p)} is the first m∗m^* tokens, where m∗m^* is the smallest mm with M(m)≥pM(m) \ge p. One step draws yty_t from

qp(i)=Pi [i∈V(p)]∑j∈V(p)Pj.q_p(i) = \frac{P_i \, [i \in V^{(p)}]}{\sum_{j \in V^{(p)}} P_j}.

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 P(y)P(y); the method is defined by the rule.

The algorithm

The step takes PP, the threshold 0<p≤10 < p \le 1, and a number uu drawn uniformly from [0,1)[0, 1).

  1. NUCLEUS-SAMPLE(P, p, u) ▷ P = next-token distribution, u uniform in [0, 1)
  2. 1order ← the tokens sorted by P, from high to low ▷ ties: the smaller index first
  3. 2c ← 0, K ← empty list
  4. 3for each i in order do
  5. 4c ← c + P[i], append i to K
  6. 5if c ≥ p then stop the loop
  7. 6Z ← c ▷ the mass of the nucleus K
  8. 7r ← u · Z
  9. 8c ← 0; for each i in K, in order do
  10. 9c ← c + P[i]
  11. 10if r < c then return i
  12. 11return 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 ZZ moved to the random number so that nothing is divided.

Example

Take six next tokens with PP = (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.

pp 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 PP itself

With p=0.9p = 0.9 the mass 0.90 reaches the threshold exactly at "dog", so "dog" is kept and "sat" is not.

Now take p=0.9p = 0.9 on two other steps. On a peaked step, PP = (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 k=3k = 3 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 pp, 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 Pi/ZP_i / Z. The limits follow: for pp at most the largest probability the step is greedy, and for p=1p = 1 it samples from PP. The tests check the smallest size against all subsets on random distributions with Fraction probabilities, and check the draw exactly with uu 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 PP over the vocabulary V={0,…,∣V∣−1}V = \{0, \ldots, |V| - 1\}, a threshold 0<p≤10 < p \le 1, and a number uu drawn uniformly from [0,1)[0, 1). We assume exact arithmetic, as with the Fractions of the tests; the last remark treats rounding.

Let i1,i2,…,i∣V∣i_1, i_2, \ldots, i_{|V|} be the order of line L1: the tokens sorted by the key (−Pi,i)(-P_i, i). This order is unique. For m=0,…,∣V∣m = 0, \ldots, |V| let Sm={i1,…,im}S_m = \{i_1, \ldots, i_m\} and M(m)=P(Sm)M(m) = P(S_m), the mass of the first mm tokens. MM does not decrease in mm, and M(∣V∣)=1≥pM(|V|) = 1 \ge p.

Lemma 1 (prefixes have maximum mass). For every mm and every set S⊆VS \subseteq V with ∣S∣=m|S| = m, P(S)≤M(m)P(S) \le M(m).

Proof. This is the exchange argument of top-k sampling: every token of SmS_m is at least as probable as every token outside it, so replacing a token of S∖SmS \setminus S_m by a token of Sm∖SS_m \setminus S never lowers the mass, and after at most mm such steps the set is SmS_m. □\square

Theorem 2 (the nucleus is a smallest set). Let m∗m^* be the smallest mm with M(m)≥pM(m) \ge p. Lines L2 to L5 return Sm∗S_{m^*}. No set of fewer than m∗m^* tokens has mass at least pp. Among the sets of m∗m^* tokens, Sm∗S_{m^*} has the largest mass.

Proof. After the pass of line L4 for the token iti_t, the running sum is c=M(t)c = M(t), by induction on tt from c=0c = 0 (line L2). Line L5 returns StS_t at the first tt with M(t)≥pM(t) \ge p, which is m∗m^*. Such a tt exists since M(∣V∣)=1≥pM(|V|) = 1 \ge p. If a set SS with ∣S∣=m<m∗|S| = m < m^* had P(S)≥pP(S) \ge p, then M(m)≥P(S)≥pM(m) \ge P(S) \ge p by Lemma 1, against the choice of m∗m^*. The last claim is Lemma 1 with m=m∗m = m^*. □\square

Corollary 3 (no zero tokens). The nucleus has no token of probability 0.

Proof. The zero tokens come last in the order. If im∗i_{m^*} had probability 0, then M(m∗−1)=M(m∗)≥pM(m^* - 1) = M(m^*) \ge p, against the choice of m∗m^*. □\square

Theorem 4 (the draw). Let Z=M(m∗)Z = M(m^*). NUCLEUS-SAMPLE returns each token ii of the nucleus with probability Pi/ZP_i / Z, and never returns a token outside the nucleus.

Proof. Line L7 sets r=uZr = uZ, uniform on [0,Z)[0, Z). Lines L8 to L10 walk the nucleus in the order of line L1 with the running sum ct=M(t)c_t = M(t) and return iti_t for the unique tt with M(t−1)≤r<M(t)M(t - 1) \le r < M(t). That interval has length PitP_{i_t}, so iti_t is returned with probability Pit/ZP_{i_t} / Z. Since r<Z=M(m∗)r < Z = M(m^*), the walk always returns inside the loop, and line L11 is not reached. □\square

Corollary 5 (limits). For p≤max⁡iPip \le \max_i P_i, the nucleus is the first most probable token and the step is greedy decoding. For p=1p = 1, the nucleus is the set of all tokens of positive probability, and the step samples from PP.

Proof. For the first claim, M(1)=max⁡iPi≥pM(1) = \max_i P_i \ge p, so m∗=1m^* = 1. For the second, M(m)=1M(m) = 1 exactly when SmS_m holds every token of positive probability, and by Corollary 3 the nucleus holds no other. □\square

Remark (rounding). With floats, the running sum can stay below pp where the exact sum reaches it. For P=(0.7,0.2,0.1)P = (0.7, 0.2, 0.1) and p=0.9p = 0.9, the float sum 0.7+0.20.7 + 0.2 is 0.89999999999999990.8999999999999999, so the code keeps 3 tokens where exact arithmetic keeps 2. In the extreme case the sum stays below pp up to the end, and the code then keeps every token of positive probability, which is the result for p=1p = 1. In the draw, ZZ and the running sum can differ in the last bits and uZuZ 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 O(∣V∣log⁡∣V∣)O(|V| \log |V|) with a full sort, plus O(m)O(m) for the prefix sums and the draw, where mm is the size of the nucleus. The size mm 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 O(∣V∣)O(|V|) time, plus O(mlog⁡m)O(m \log m) to sort it. The extra space is O(∣V∣)O(|V|). 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 ∣V∣|V|, and it changes from step to step with the shape of PP.
  • Smallest set. No set of fewer tokens reaches mass pp, 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 T=1T = 1 gives (0.665, 0.245, 0.090) and p=0.8p = 0.8 keeps two tokens, while T=0.5T = 0.5 gives (0.867, 0.117, 0.016) and keeps one.
  • Limits. A very small pp gives greedy decoding, and p=1p = 1 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 kk 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 τ\tau (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 pp 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, 0.7+0.2=0.8999999999999999<0.90.7 + 0.2 = 0.8999999999999999 < 0.9, so on P=(0.7,0.2,0.1)P = (0.7, 0.2, 0.1) with p=0.9p = 0.9 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.

nlslog.pyI0RawGitHub
# 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 b=16b = 16 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 p=0.95p = 0.95 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

  1. 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)
  2. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example