Algorithm Search⌘K

Algorithmcore

Top-k sampling

Also called truncated sampling.

Keep only the k most probable next tokens, renormalize their probabilities and sample from them.

Time
O(V + k log k) worst
Space
O(V) extra
Where
V = the vocabulary size |V|; k = the number of kept tokens
Properties
randomizednot exactonlineiterative
Origin
Angela Fan, Mike Lewis, Yann Dauphin, 2018

Top-k sampling generates text from an autoregressive language model one token at a time. At each step it keeps the kk most probable next tokens, sets the probability of every other token to 0, divides the kept probabilities by their sum, and draws the next token from that distribution. With k=1k = 1 it is greedy decoding; with k=∣V∣k = |V| it is plain ancestral sampling from the model. It is a heuristic method for autoregressive decoding: it does not look for the most probable text, and it does not sample from the model either. It cuts off the long tail of unlikely tokens, where a single bad draw can derail the text, and keeps the variety of sampling among the likely tokens. The value of kk is a setting that people tune by hand.

In plain words

The model gives a chance to every word that can come next. Most of these words are bad choices, but together they can hold a real share of the chance, so a plain random draw picks one of them now and then. Top-k sampling keeps only the best k words, for example the best 40. It forgets the others and draws at random among the kept ones, in proportion to their chances. Then it adds the word and repeats. A small k gives safe, plain text. A large k gives more varied text with more risk.

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}. Number the tokens 0,…,∣V∣−10, \ldots, |V| - 1. The task of one step is to choose yty_t at random. Top-k sampling draws yty_t from the truncated distribution

qk(i)=pi [i∈K]∑j∈Kpj,q_k(i) = \frac{p_i \, [i \in K]}{\sum_{j \in K} p_j},

where KK is a set of min⁡(k,∣V∣)\min(k, |V|) tokens of largest probability. On ties at the boundary, the tokens with smaller indices are kept. The whole output is built by repeating the step until the end token </s> or a length limit, as in greedy decoding. The output distribution is not the model distribution p(y)p(y), and no single sequence is the target; the method is defined by the rule itself.

The algorithm

The step takes pp and a number uu drawn uniformly from [0,1)[0, 1). In practice pp comes from the logits zz by a softmax, often with a temperature TT (temperature sampling); since dividing by T>0T > 0 keeps the order of the logits, KK is the same for every TT.

  1. TOP-K-SAMPLE(p, k, 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. 2K ← the first min(k, |V|) tokens of order
  4. 3Z ← sum of p[i] over i in K
  5. 4r ← u · Z
  6. 5c ← 0
  7. 6for each i in K, in the order of L1 do
  8. 7c ← c + p[i]
  9. 8if r < c then return i
  10. 9return the last i in K with p[i] > 0 ▷ only if u · Z rounded up to Z

Lines L4 to L8 are inverse transform sampling on the kept tokens. The bound ZZ multiplies uu, so the renormalized distribution is never written down and nothing is divided. A token of probability 0 has an empty interval and is never returned.

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). They are already sorted.

kk kept ZZ renormalized
1 the 0.40 the 1
2 the, a 0.65 the 8/13 = 0.6154, a 5/13 = 0.3846
3 the, a, cat 0.80 the 1/2, a 5/16 = 0.3125, cat 3/16 = 0.1875
6 all 1 pp itself

With k=3k = 3 and u=0.6u = 0.6, line L4 gives r=0.48r = 0.48. The running sum is 0.40 after "the", which is not above 0.48, and 0.65 after "a", which is. So the step returns "a". In terms of uu, the token "the" wins for u<0.5u < 0.5, "a" for 0.5≤u<0.81250.5 \le u < 0.8125, and "cat" for u≥0.8125u \ge 0.8125.

The weak point shows with k=3k = 3 on two other steps. On a peaked step, pp = (0.90, 0.05, 0.03, 0.02), top-3 still keeps a token of probability 0.03 and gives it 0.03/0.98=0.03060.03 / 0.98 = 0.0306. On a flat step with ten tokens of 0.1 each, top-3 drops 70% of the mass and keeps three tokens that are no better than the other seven. A fixed kk is too large for the first step and too small for the second; nucleus sampling adapts the size of the set to the shape of pp.

Correctness

The proof is in proofs/correctness.md. It shows that the kept set has the largest total probability of all sets of min⁡(k,∣V∣)\min(k, |V|) tokens, by an exchange argument, and that the step returns each kept token ii with probability exactly pi/Zp_i / Z and never returns a dropped token or a token of probability 0. The special cases follow: k=1k = 1 returns the first most probable token, and k≥∣V∣k \ge |V| samples from pp. The tests check the maximum mass against all subsets on random distributions, and check the draw exactly with Fraction probabilities and uu on a fine grid.

Proof: Top-k sampling keeps a set of maximum mass and draws from the renormalized distributionfull

We use the notation of the page. The input is a distribution pp over the vocabulary V={0,1,…,∣V∣−1}V = \{0, 1, \ldots, |V| - 1\}, an integer k≥1k \ge 1, and a number uu drawn uniformly from [0,1)[0, 1). Let m=min⁡(k,∣V∣)m = \min(k, |V|). We assume exact arithmetic, as with the Fractions of the tests; the last remark treats rounding.

Lemma 1 (the kept set). Line L1 sorts the indices by the key (−pi,i)(-p_i, i), and line L2 keeps the first mm of them. The kept set KK has mm elements, every kept token has a probability at least as large as every dropped token, and among the tokens with the same probability as the least probable kept token, the kept ones have the smaller indices.

Proof. The key (−pi,i)(-p_i, i) is distinct for distinct ii, so the sorted order is unique, whatever sort algorithm runs. A token ii comes before a token jj exactly when pi>pjp_i > p_j, or pi=pjp_i = p_j and i<ji < j. The first mm positions therefore hold tokens whose probabilities are at least the probability of every later token, and on a tie at the boundary the smaller indices come first. □\square

Theorem 2 (maximum mass). Among all sets S⊆VS \subseteq V with ∣S∣=m|S| = m, the kept set has the largest mass ∑i∈Spi\sum_{i \in S} p_i.

Proof. Let SS be any set of size mm with S≠KS \ne K. Then there are i∈K∖Si \in K \setminus S and j∈S∖Kj \in S \setminus K, and pi≥pjp_i \ge p_j by Lemma 1. The set S′=S∖{j}∪{i}S' = S \setminus \{j\} \cup \{i\} has size mm, its mass is at least the mass of SS, and it has one more element in common with KK. Repeat until the set is KK. The mass never goes down, so the mass of KK is at least the mass of SS. □\square

So top-k keeps the mm tokens of largest mass. Theorem 2 only says that the set is best for its size; whether kk tokens is a good size is a separate question, which nucleus sampling answers with a mass threshold.

Theorem 3 (the draw). Let Z=∑i∈Kpi>0Z = \sum_{i \in K} p_i > 0. TOP-K-SAMPLE returns each i∈Ki \in K with probability pi/Zp_i / Z, and returns no token outside KK and no token with pi=0p_i = 0.

Proof. Write the kept tokens in sorted order as i1,…,imi_1, \ldots, i_m, and let c0=0c_0 = 0 and ct=pi1+⋯+pitc_t = p_{i_1} + \cdots + p_{i_t}, so cm=Zc_m = Z. Line L4 sets r=uZr = u Z, which is uniform on [0,Z)[0, Z). The loop of lines L6 to L8 returns iti_t for the first tt with r<ctr < c_t. Since the ctc_t do not decrease and r<Z=cmr < Z = c_m, such a tt exists, and it is the unique tt with ct−1≤r<ctc_{t-1} \le r < c_t. The interval [ct−1,ct)[c_{t-1}, c_t) has length pitp_{i_t}, so the probability of returning iti_t is pit/Zp_{i_t} / Z. If pit=0p_{i_t} = 0, the interval is empty and iti_t is never returned. Line L9 is not reached. □\square

This is inverse transform sampling on the renormalized distribution qi=pi/Zq_i = p_i / Z for i∈Ki \in K and qi=0q_i = 0 otherwise, but with the bound ZZ moved to the random number: comparing r=uZr = uZ with ctc_t is the same as comparing uu with ct/Zc_t / Z, and no division is needed. The tests check Theorem 3 exactly: with uu on the grid j/nj / n and Fraction probabilities, the share of grid points that return each token equals qiq_i.

Corollary 4 (special cases). With k=1k = 1 the kept set is the first index of a largest probability, and the draw returns it with probability 1, which is greedy decoding of one step. With k≥∣V∣k \ge |V|, the kept set is all of VV, Z=1Z = 1, and the draw is a sample from pp itself.

Proof. Both follow from Lemma 1 and Theorem 3. □\square

Remark (rounding). With floats, the sum ZZ of line L3 and the running sum cmc_m of line L7 can differ in the last bits, because two ways of adding the same numbers can round differently, and the product uZuZ of line L4 can round up to ZZ when uu is very close to 1. Then rr can be at least cmc_m, and no tt has r<ctr < c_t. Line L9 returns the last kept token of positive probability in that case. The event has probability of the order of the rounding error, and it does not change which tokens can be drawn.

Complexity

One step reads ∣V∣|V| probabilities. A full sort costs O(∣V∣log⁡∣V∣)O(|V| \log |V|). Only the kk largest are needed, in order: a selection in linear time followed by a sort of the kk kept values costs O(∣V∣+klog⁡k)O(|V| + k \log k), and a min-heap of size kk costs O(∣V∣log⁡k)O(|V| \log k). The draw itself is O(k)O(k). The extra space is O(∣V∣)O(|V|) for the scores, or O(k)O(k) beyond them with the heap. On a GPU, frameworks use a parallel top-k kernel. For a large model the call of the network costs far more than any of this.

Properties

  • Randomized. The same prefix can give different tokens. Fix the seed of the random source to reproduce an output.
  • Not the model distribution. For k<∣V∣k < |V| the output distribution differs from p(y)p(y). Tokens outside the top kk at some step can never appear there.
  • Maximum mass for its size. The kept set holds the most probability of any set of min⁡(k,∣V∣)\min(k, |V|) tokens.
  • Order only. The kept set depends only on the order of the probabilities, so it is the same for every temperature and for the logits or the probabilities.
  • Limits. k=1k = 1 is greedy decoding, and k=∣V∣k = |V| is ancestral sampling.
  • Online. Each token is final when it is drawn.

Variants and improvements

  • Top-k with temperature. Apply the temperature to the logits, then truncate. Holtzman et al. 2020 report top-k = 40 with T=0.7T = 0.7 as one of their baselines.
  • Nucleus sampling. Keep the smallest set whose mass reaches pp in place of a fixed count (nucleus sampling). Libraries often apply both: first top-k, then top-p.
  • Typical sampling. Keep the tokens whose surprisal is closest to the entropy of the step (typical sampling).
  • Contrastive search. Take the top kk candidates, but choose among them by a score with a penalty for similarity to the context, without randomness (contrastive search).
  • Gumbel top-k. Adding Gumbel noise to the log probabilities and taking the kk largest draws kk tokens without replacement (Gumbel-max trick, stochastic beam search). This draws several tokens at once; it is not the same as top-k sampling.

When to use it

Use top-k sampling for open-ended text, such as stories and dialogue, where varied output is wanted and the most probable text tends to be dull and repetitive. A value of kk between 10 and 100 is common. Prefer nucleus sampling when the shape of the distribution changes a lot from step to step, which is the usual case. Use greedy decoding or beam search when a single correct answer is wanted, as in translation or short factual answers.

Pitfalls

  • One kk for all steps. The same kk keeps bad tokens on peaked steps and drops good ones on flat steps (the example above).
  • Ties at the boundary. With equal probabilities at position kk, the kept set depends on the tie rule. Fix it if outputs must be reproducible.
  • Order of the filters. Top-k then top-p is not the same as top-p then top-k with renormalization in between, and libraries differ. State the order.
  • Temperature does not change the set. People sometimes expect a high temperature to let more tokens in; with top-k it only changes the weights inside the fixed set.
  • Repetition is not fixed. Truncation lowers the chance of bad tokens but does not stop loops; a repetition penalty is a separate tool.

Implementations

The code takes the next-token probabilities (or logits) as given and implements the truncation 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
top_k_sampling.py 73 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/top-k-sampling/. The authors are listed in prov/CNGCHZ.jsonl.

"""Top-k sampling of the next token.

A next-token distribution is a list p of probabilities, one per token of the
vocabulary, in the order of the vocabulary. The values can be floats or
Fractions; with Fractions the distribution functions are exact. 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 top_k_set(probs: Sequence, k: int) -> List[int]:
    """Return the indices of the min(k, |V|) most probable tokens.

    The list is sorted by probability from high to low. On ties the smaller
    index comes first, so the result does not depend on the sort algorithm.
    """
    if k < 1:
        raise ValueError("k must be at least 1")
    order = sorted(range(len(probs)), key=lambda i: (-probs[i], i))  # @line L1
    return order[: min(k, len(probs))]  # @line L2


def top_k_distribution(probs: Sequence, k: int) -> list:
    """Return the truncated and renormalized distribution q of top-k sampling.

    q[i] = p[i] / Z for the kept tokens, where Z is their total mass, and 0
    for the others. Raise ValueError if the kept mass is 0.
    """
    kept = top_k_set(probs, k)
    z = sum(probs[i] for i in kept)
    if not z > 0:
        raise ValueError("the kept tokens have no mass")
    q = [probs[i] * 0 for i in range(len(probs))]
    for i in kept:
        q[i] = probs[i] / z
    return q


def top_k_sample(probs: Sequence, k: int, rng) -> int:
    """Draw one token index from the top-k distribution of probs.

    The draw is inverse transform sampling over the kept tokens in sorted
    order: r = u Z, and the first index whose running sum exceeds r wins.
    Nothing is divided, and a token of probability 0 is never returned.
    """
    kept = top_k_set(probs, k)  # @line L1
    z = sum(probs[i] for i in kept)  # @line L3
    if not z > 0:
        raise ValueError("the kept tokens have no mass")
    r = rng.random() * z  # @line L4
    c = probs[kept[0]] * 0  # @line L5
    for i in kept:  # @line L6
        c = c + probs[i]  # @line L7
        if r < c:  # @line L8
            return i
    return [i for i in kept if probs[i] > 0][-1]  # @line L9


def top_k_sample_logits(logits: Sequence[float], k: int, rng, temperature: float = 1.0) -> int:
    """Top-k sampling from logits: softmax with the temperature, then top_k_sample.

    The kept set is the same for every temperature, because dividing by a
    positive T keeps the order of the logits.
    """
    return top_k_sample(softmax(logits, temperature), k, rng)
test_top_k_sampling.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/top-k-sampling/. The authors are listed in prov/CNGCHZ.jsonl.

import itertools
import random
from fractions import Fraction as F

from nlslog import argmax, softmax
from top_k_sampling import top_k_distribution, top_k_sample, top_k_sample_logits, top_k_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 top_k_set(P, 1) == [0]
    assert top_k_distribution(P, 2) == [F(8, 13), F(5, 13), 0, 0, 0, 0]
    assert top_k_distribution(P, 3) == [F(1, 2), F(5, 16), F(3, 16), 0, 0, 0]
    assert top_k_distribution(P, 6) == P
    assert top_k_distribution(P, 100) == P


def test_kept_set_has_maximum_mass_brute_force() -> None:
    rng = random.Random(1)
    for _ in range(300):
        n = rng.randint(1, 7)
        p = random_fractions(rng, n)
        for k in range(1, n + 2):
            kept = top_k_set(p, k)
            m = min(k, n)
            assert len(kept) == m and len(set(kept)) == m
            best = max(sum(p[i] for i in c) for c in itertools.combinations(range(n), m))
            assert sum(p[i] for i in kept) == best
            # every kept token is at least as probable as every dropped one
            dropped = [i for i in range(n) if i not in kept]
            if dropped:
                assert min(p[i] for i in kept) >= max(p[i] for i in dropped)


def test_tie_rule_smaller_index_first() -> None:
    p = [F(1, 10), F(3, 10), F(3, 10), F(3, 10)]
    assert top_k_set(p, 2) == [1, 2]
    assert top_k_set(p, 3) == [1, 2, 3]


def test_inverse_transform_is_exact_on_a_grid() -> None:
    n = 1600
    for k, q in ((2, top_k_distribution(P, 2)), (3, top_k_distribution(P, 3))):
        src = GridU(n * 13)
        counts = [0] * len(P)
        for _ in range(n * 13):
            counts[top_k_sample(P, k, src)] += 1
        assert [F(c, n * 13) for c in counts] == q


def test_k_equal_one_is_greedy() -> None:
    rng = random.Random(2)
    for _ in range(200):
        p = [rng.random() for _ in range(5)]
        assert top_k_sample(p, 1, rng) == argmax(p)


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[top_k_sample(probs, 3, rng)] += 1
    expected = [0.5, 0.3125, 0.1875, 0.0, 0.0, 0.0]
    for c, e in zip(counts, expected):
        assert abs(c / draws - e) < 0.01
    assert counts[3:] == [0, 0, 0]


def test_zero_mass_token_is_never_drawn() -> None:
    rng = random.Random(4)
    p = [0.5, 0.0, 0.5, 0.0]
    assert top_k_set(p, 3) == [0, 2, 1]
    seen = {top_k_sample(p, 3, rng) for _ in range(2000)}
    assert seen == {0, 2}


def test_kept_set_does_not_depend_on_temperature() -> None:
    rng = random.Random(5)
    for _ in range(100):
        z = [rng.uniform(-5, 5) for _ in range(8)]
        sets = [top_k_set(softmax(z, t), 3) for t in (0.5, 1.0, 2.0)]
        assert sets[0] == sets[1] == sets[2]
    assert top_k_sample_logits([2.0, 1.0, 0.0], 1, rng, temperature=3.0) == 0


def test_bad_arguments() -> None:
    for bad in (lambda: top_k_set(P, 0), lambda: top_k_distribution([0, 0], 1)):
        try:
            bad()
        except ValueError:
            pass
        else:
            raise AssertionError("no ValueError")

History

Fan, Lewis and Dauphin 2018 used top-k random sampling with k=10k = 10 to generate stories on their WritingPrompts dataset, because beam search tended to produce common phrases and repetitive text. Top-k sampling then became a standard way to generate text with large language models. Holtzman et al. 2020 measured its weak point, the fixed size of the set, and proposed nucleus sampling, which adapts the size to the distribution.

References

  1. Angela Fan, Mike Lewis and Yann Dauphin, Hierarchical neural story generation, ACL 2018, pages 889 to 898, Section 5.4 (Generation), top-k random sampling from the k = 10 most likely candidates, and the note that beam search gives common phrases and repetitive text
  2. Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes and Yejin Choi, The curious case of neural text degeneration, ICLR 2020, Section 3.2 (top-k sampling as the size-k set of largest mass) and Table 1 (top-k = 40 and top-k = 640 against nucleus sampling on GPT-2 Large)

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