Algorithm Search⌘K

Algorithmresearch

Typical sampling

Also called locally typical sampling.

Keep the tokens whose surprisal is closest to the entropy of the next-token distribution, up to mass tau, and sample among them.

Time
O(V log V) worst
Space
O(V) extra
Where
V = the vocabulary size |V|
Properties
randomizednot exactonlineiterative
Origin
Clara Meister, Tiago Pimentel, Gian Wiher, Ryan Cotterell, 2023

Typical sampling, or locally typical sampling, generates text from an autoregressive language model one token at a time. At each step it computes the entropy HH of the next-token distribution, which is the expected surprisal of the next token. It then ranks the tokens by how far their surprisal −log⁡p-\log p is from HH, keeps the closest tokens until their total probability reaches a threshold τ\tau, renormalizes, and draws the next token. It works like nucleus sampling, but with a different order: nucleus sampling keeps the most probable tokens, while typical sampling keeps the tokens whose information content is close to the expected value. So it can drop the most probable token. Meister et al. 2023 motivated the rule by the idea that people choose words whose information content is close to what the listener expects. It is a heuristic for autoregressive decoding, and its quality gains are measurements on a few models and tasks.

In plain words

Every word that can come next has a surprise value: rare words are very surprising, common words are not. The model also has an average surprise for this step. Typical sampling keeps the words whose surprise is close to that average, not simply the most likely words. It adds them, closest first, until they hold a set share of the chance, and then draws one of them at random. When one word is far more likely than the rest, that word can be too unsurprising to keep. The idea is that good human text is neither too dull nor too strange.

The problem

The model gives a distribution p=p(⋅∣y<t)p = p(\cdot \mid y_{<t}) over the vocabulary VV. Let V+V^+ be the tokens with pi>0p_i > 0. The entropy of the step is

H=−∑i∈V+pilog⁡pi,H = -\sum_{i \in V^+} p_i \log p_i,

and the distance of a token i∈V+i \in V^+ is di=∣−log⁡pi−H∣d_i = |-\log p_i - H|. Sort V+V^+ by did_i, with the smaller index first on ties, and let KK be the shortest prefix whose mass is at least τ\tau. One step draws yty_t from q(i)=pi[i∈K]/∑j∈Kpjq(i) = p_i [i \in K] / \sum_{j \in K} p_j. All logs here are natural logs; the paper uses bits, and the set KK does not depend on the base, because changing the base scales every distance by the same factor.

The algorithm

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

  1. TYPICAL-SAMPLE(p, τ, u) ▷ p = next-token distribution, u uniform in [0, 1)
  2. 1H ← − Σ p[i] log p[i] over the tokens with p[i] > 0
  3. 2for each token i with p[i] > 0 do d[i] ← |−log p[i] − H|
  4. 3order ← these tokens sorted by d, smallest first ▷ ties: the smaller index first
  5. 4c ← 0, K ← empty list
  6. 5for each i in order do c ← c + p[i], append i to K
  7. 6if c ≥ τ then stop the loop
  8. 7Z ← c, r ← 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 ▷ only after rounding

Lines L4 to L11 are those of nucleus sampling; only the order of line L3 is new.

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). The entropy is H=1.5255H = 1.5255 nats (2.2008 bits).

token pp surprisal −log⁡p-\log p distance dd
the 0.40 0.9163 0.6092
a 0.25 1.3863 0.1392
cat 0.15 1.8971 0.3716
dog 0.10 2.3026 0.7771
sat 0.06 2.8134 1.2879
ran 0.04 3.2189 1.6934

The order by distance is a, cat, the, dog, sat, ran, with running masses 0.25, 0.40, 0.80, 0.90, 0.96 and 1.

τ\tau kept mass renormalized
0.2 a 0.25 a 1
0.5 a, cat, the 0.80 a 0.3125, cat 0.1875, the 0.5
0.9 a, cat, the, dog 0.90 a 0.2778, cat 0.1667, the 0.4444, dog 0.1111
0.95 the first five 0.96 a 0.2604, cat 0.15625, the 0.4167, dog 0.1042, sat 0.0625

With τ=0.2\tau = 0.2 the step returns "a" for sure, although "the" is more probable: the surprisal of "the" is too far below the entropy. With τ=0.5\tau = 0.5 the kept set is the same as the nucleus for p=0.8p = 0.8, but it is reached in a different order. For large τ\tau, typical sampling and nucleus sampling keep almost the same tokens, because the order matters only at the boundary.

Correctness

The proof is in proofs/correctness.md. It shows that the kept set is the shortest prefix of the distance order with mass at least τ\tau, that every kept token is at least as close to the entropy as every dropped token, that the set does not depend on the log base, and that the step draws each kept token with probability pi/Zp_i / Z. It also shows that the greedy prefix is not always a solution of the optimization problem in the paper (minimize the total distance subject to mass at least τ\tau): for p=(0.4,0.3,0.2,0.1)p = (0.4, 0.3, 0.2, 0.1) and τ=0.35\tau = 0.35, the greedy set holds the tokens of probability 0.3 and 0.2, with total distance 0.4055, while the token of probability 0.4 alone has mass 0.4 and distance 0.3636. The tests check these facts against all subsets on small distributions.

Proof: The typical set is the shortest prefix of the tokens ordered by distance to the entropyfull

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<τ≤10 < \tau \le 1, and a number uu drawn uniformly from [0,1)[0, 1). Let V+={i:pi>0}V^+ = \{i : p_i > 0\}. The entropy is H=−∑i∈V+pilog⁡piH = -\sum_{i \in V^+} p_i \log p_i, and the distance of a token i∈V+i \in V^+ is di=∣−log⁡pi−H∣d_i = |-\log p_i - H|, the gap between its surprisal and the entropy. We assume exact arithmetic for the masses; the remark at the end treats rounding.

Let i1,…,ini_1, \ldots, i_n with n=∣V+∣n = |V^+| be the order of line L3: the tokens of V+V^+ sorted by the key (di,i)(d_i, i). Let M(m)M(m) be the mass of the first mm of them. MM does not decrease and M(n)=1≥τM(n) = 1 \ge \tau.

Lemma 1 (the kept set). Lines L4 to L6 return K={i1,…,im∗}K = \{i_1, \ldots, i_{m^*}\}, where m∗m^* is the smallest mm with M(m)≥τM(m) \ge \tau. Every token of KK has positive probability, and every token of KK has a distance at most the distance of every token of V+∖KV^+ \setminus K.

Proof. The running sum after the token iti_t is M(t)M(t), and line L6 stops at the first tt with M(t)≥τM(t) \ge \tau, which exists since M(n)=1M(n) = 1. The tokens of probability 0 are left out at line L2. The order of line L3 sorts by distance first, so every token in the first m∗m^* positions has a distance at most that of every later token. □\square

Lemma 2 (the log base does not matter). If every log is taken to a base b>1b > 1 in place of ee, the order of line L3 is the same, and so is KK.

Proof. In base bb, every surprisal and the entropy are divided by ln⁡b>0\ln b > 0, so every distance is divided by the same positive number. The keys (di,i)(d_i, i) keep their order. □\square

The paper of Meister et al. works with bits; the code works with nats, and by Lemma 2 both give the same set. With floats, two different probabilities can have exactly equal distances in exact arithmetic, for example 1/41/4 and 1/21/2 in (1/4,1/4,1/2)(1/4, 1/4, 1/2), where H=1.5H = 1.5 bits and both distances are 0.50.5 bits. Then the order between them depends on rounding.

Theorem 3 (the draw). Let Z=M(m∗)Z = M(m^*). TYPICAL-SAMPLE returns each i∈Ki \in K with probability pi/Zp_i / Z, and returns no other token.

Proof. As for top-k sampling: r=uZr = uZ is uniform on [0,Z)[0, Z), the walk of lines L8 to L10 returns iti_t for the unique tt with M(t−1)≤r<M(t)M(t - 1) \le r < M(t), and that interval has length pitp_{i_t}. Since r<Zr < Z, line L11 is not reached. □\square

Corollary 4 (special cases). (a) For τ=1\tau = 1, K=V+K = V^+ and the step samples from pp. (b) For a uniform distribution on nn tokens, all distances are 0, and KK is the ⌈τn⌉\lceil \tau n \rceil tokens of smallest index. (c) The most probable token need not be in KK. For a small τ\tau, KK is the single token closest to the entropy.

Proof. (a) Every token of V+V^+ has positive probability, so M(m)<1M(m) < 1 for m<nm < n, and m∗=nm^* = n. (b) With pi=1/np_i = 1/n, −log⁡pi=log⁡n=H-\log p_i = \log n = H, so every di=0d_i = 0, the order is by index, and M(m)=m/n≥τM(m) = m / n \ge \tau first holds at m=⌈τn⌉m = \lceil \tau n \rceil. (c) In the example of the page, with pp = (0.40, 0.25, 0.15, 0.10, 0.06, 0.04), the token of probability 0.25 has the smallest distance, and τ=0.2\tau = 0.2 keeps it alone. □\square

Proposition 5 (the greedy prefix and the optimization problem differ). Meister et al. state the kept set as the solution of: minimize ∑i∈Sdi\sum_{i \in S} d_i over the sets SS with ∑i∈Spi≥τ\sum_{i \in S} p_i \ge \tau. The prefix KK of Lemma 1 does not always solve this problem.

Proof. Take p=(0.4,0.3,0.2,0.1)p = (0.4, 0.3, 0.2, 0.1) and τ=0.35\tau = 0.35. Then H=1.2799H = 1.2799 nats, and the distances are 0.36360.3636, 0.07590.0759, 0.32960.3296 and 1.02271.0227. The order is (0.3, 0.2, 0.4, 0.1), the masses of its prefixes are 0.30.3 and 0.50.5, so KK holds the tokens of probability 0.3 and 0.2, with total distance 0.40550.4055. The set that holds only the token of probability 0.4 has mass 0.4≥0.350.4 \ge 0.35 and total distance 0.3636<0.40550.3636 < 0.4055. So KK is not optimal, and the optimal set leaves out the token closest to the entropy. □\square

The algorithm that the paper describes and that implementations use is the greedy prefix of Lemma 1, which keeps the tokens closest to the entropy. The arXiv version 6 of the paper notes this mismatch between the formulation and the algorithm in an erratum. The tests check the counterexample above, and a second one with p=(1/2,1/4,1/8,1/8)p = (1/2, 1/4, 1/8, 1/8) and τ=0.3\tau = 0.3, by enumerating all subsets.

Remark (rounding). The entropy and the distances are floats, so the order can differ from the exact order when two distances are equal or nearly equal, as in Lemma 2. The masses are summed in the type of the input; with floats the running sum can stay below τ\tau to the end, and then the code keeps all of V+V^+, which is the result for τ=1\tau = 1.

Complexity

One step computes the entropy in O(∣V∣)O(|V|), the distances in O(∣V∣)O(|V|), and sorts in O(∣V∣log⁡∣V∣)O(|V| \log |V|). The prefix sums and the draw are O(∣V∣)O(|V|). As with nucleus sampling, the size of the kept set is not known in advance, so a selection by mass around a pivot gives expected O(∣V∣)O(|V|) plus the sort of the kept tokens. The extra space is O(∣V∣)O(|V|). Meister et al. note that the cost is the same as that of nucleus and top-k sampling, and the call of the network costs far more.

Properties

  • Randomized. Fix the seed to reproduce an output.
  • Closest to the entropy. Every kept token has a surprisal at least as close to HH as every dropped token.
  • Can drop the most probable token. When the largest probability is far above the others, its surprisal is far below HH. So there is no greedy limit: a small τ\tau keeps the single token closest to HH, not the most probable one.
  • Uniform steps. On a uniform distribution every distance is 0 and every token is equally typical; the tie rule decides the set, and the renormalized distribution is uniform on it.
  • Limit. τ=1\tau = 1 keeps every token of positive probability and gives ancestral sampling.
  • Base free. The set is the same in nats and in bits.

Variants and improvements

  • With temperature or top-k. As with nucleus sampling, a temperature can be applied to the logits first, and the kept set can be capped at kk tokens.
  • Nucleus sampling. The same prefix rule with the tokens ordered by probability (nucleus sampling).
  • The optimization form. Solving the stated problem exactly (a knapsack-like choice of tokens of minimum total distance and mass at least τ\tau) gives a different set from the greedy rule in some cases. No standard implementation does this; the greedy rule is the method in use.
  • Contrastive search. A deterministic method that fights repetition with a similarity penalty in place of an entropy rule (contrastive search).

When to use it

Use typical sampling for open-ended generation when nucleus sampling still gives dull or repetitive text, since it can skip the most predictable token. Meister et al. found τ=0.2\tau = 0.2 best for story generation with GPT-2 on WritingPrompts and τ=0.95\tau = 0.95 for abstractive summarization with BART on CNN/DailyMail, tuned with automatic measures and checked with human ratings. Tune τ\tau for your own model and task. For tasks with one correct answer, use greedy decoding or beam search.

Pitfalls

  • Small τ\tau is not greedy. People coming from nucleus sampling expect a small threshold to give safe text; here it can give the less probable token.
  • Ties of distance. A token above the entropy and a token below it can be equally far from it, for example 1/41/4 and 1/21/2 in (1/4,1/4,1/2)(1/4, 1/4, 1/2), where H=1.5H = 1.5 bits and both distances are 0.5 bits. The order between them then depends on rounding.
  • The formula and the algorithm differ. Code the greedy prefix, not the optimization problem as written in the paper, unless you want a different method.
  • Tokens of probability 0. Their surprisal is infinite. Leave them out before the sort, or the distance computation fails.
  • Rounding at the threshold. As with nucleus sampling, a float sum can stop just below τ\tau; with τ=1\tau = 1 that can keep every positive token, which is the intended result.

Implementations

The code takes the next-token probabilities (or logits) as given and implements the entropy, the order, the kept set 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
typical_sampling.py 86 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/typical-sampling/. The authors are listed in prov/T8X2CS.jsonl.

"""Locally typical 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; the entropy and the surprisals are floats in nats, while the
masses keep the type of the input, so a Fraction threshold is compared
exactly. 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.
"""

import math
from typing import List, Sequence

from nlslog import softmax


def entropy(probs: Sequence) -> float:
    """Return the Shannon entropy H = -sum p log p in nats, with 0 log 0 = 0."""
    return -math.fsum(float(x) * math.log(x) for x in probs if x > 0)


def typical_order(probs: Sequence) -> List[int]:
    """Return the tokens of positive probability sorted by |-log p - H|.

    The distance of a token is how far its surprisal -log p is from the
    entropy H of the step. Ties go to the smaller index. Tokens of
    probability 0 have infinite surprisal and are left out.
    """
    h = entropy(probs)  # @line L1
    dist = {i: abs(-math.log(probs[i]) - h) for i in range(len(probs)) if probs[i] > 0}  # @line L2
    return sorted(dist, key=lambda i: (dist[i], i))  # @line L3


def typical_set(probs: Sequence, tau) -> List[int]:
    """Return the shortest prefix of typical_order whose mass is at least tau.

    If rounding keeps the running sum below tau up to the end, every token
    of positive probability is kept.
    """
    if not 0 < tau <= 1:
        raise ValueError("tau must be in (0, 1]")
    order = typical_order(probs)
    if not order:
        raise ValueError("no token has positive probability")
    c = probs[order[0]] * 0  # @line L4
    for t, i in enumerate(order):  # @line L5
        c = c + probs[i]
        if c >= tau:  # @line L6
            return order[: t + 1]
    return order


def typical_distribution(probs: Sequence, tau) -> list:
    """Return the renormalized distribution on the typical set, 0 elsewhere."""
    kept = typical_set(probs, tau)
    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 typical_sample(probs: Sequence, tau, rng) -> int:
    """Draw one token index from the typical distribution of probs.

    Inverse transform sampling over the typical set in its order, with
    r = u Z for the mass Z of the set.
    """
    kept = typical_set(probs, tau)  # @line L1
    z = sum(probs[i] for i in kept)  # @line L7
    r = rng.random() * z
    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 kept[-1]  # @line L11


def typical_sample_logits(logits: Sequence[float], tau, rng, temperature: float = 1.0) -> int:
    """Typical sampling from logits: softmax with the temperature, then typical_sample."""
    return typical_sample(softmax(logits, temperature), tau, rng)
test_typical_sampling.py 152 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/typical-sampling/. The authors are listed in prov/T8X2CS.jsonl.

import itertools
import math
import random
from fractions import Fraction as F

from typical_sampling import (
    entropy,
    typical_distribution,
    typical_order,
    typical_sample,
    typical_sample_logits,
    typical_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:
    h = entropy(P)
    assert abs(h - 1.525476) < 1e-6
    assert abs(h / math.log(2) - 2.200797) < 1e-6
    d = [abs(-math.log(x) - h) for x in P]
    for got, want in zip(d, (0.6092, 0.1392, 0.3716, 0.7771, 1.2879, 1.6934)):
        assert abs(got - want) < 1e-4
    assert typical_order(P) == [1, 2, 0, 3, 4, 5]
    assert typical_set(P, F(1, 5)) == [1]
    assert typical_set(P, F(1, 2)) == [1, 2, 0]
    assert typical_distribution(P, F(1, 2)) == [F(1, 2), F(5, 16), F(3, 16), 0, 0, 0]
    assert typical_set(P, F(9, 10)) == [1, 2, 0, 3]
    assert typical_set(P, F(95, 100)) == [1, 2, 0, 3, 4]
    assert typical_set(P, F(1)) == [1, 2, 0, 3, 4, 5]


def test_kept_tokens_are_the_closest_and_the_prefix_is_shortest() -> None:
    rng = random.Random(1)
    for _ in range(300):
        n = rng.randint(1, 8)
        probs = random_fractions(rng, n)
        h = entropy(probs)
        for tau in (F(1, 10), F(1, 4), F(1, 2), F(9, 10), F(1)):
            kept = typical_set(probs, tau)
            assert sum(probs[i] for i in kept) >= tau
            assert sum(probs[i] for i in kept[:-1]) < tau
            assert all(probs[i] > 0 for i in kept)
            dropped = [i for i in range(n) if probs[i] > 0 and i not in kept]
            if dropped:
                worst_kept = max(abs(-math.log(probs[i]) - h) for i in kept)
                best_dropped = min(abs(-math.log(probs[i]) - h) for i in dropped)
                assert worst_kept <= best_dropped


def test_the_set_does_not_depend_on_the_log_base() -> None:
    rng = random.Random(2)
    for _ in range(200):
        probs = random_fractions(rng, rng.randint(1, 8))
        h2 = -sum(float(x) * math.log2(x) for x in probs if x > 0)
        d2 = {i: abs(-math.log2(probs[i]) - h2) for i in range(len(probs)) if probs[i] > 0}
        # the order of the code (in nats) is also sorted by the distances in
        # bits; exact ties between different probabilities, such as
        # (1/4, 1/4, 1/2), are broken by rounding, so allow 1e-9
        order = typical_order(probs)
        assert sorted(order) == sorted(d2)
        for a, b in zip(order, order[1:]):
            assert d2[a] <= d2[b] + 1e-9


def test_uniform_keeps_a_prefix_by_index() -> None:
    for n in range(1, 12):
        probs = [F(1, n)] * n
        for tau in (F(1, 10), F(1, 3), F(1, 2), F(9, 10), F(1)):
            m = math.ceil(tau * n)
            assert typical_set(probs, tau) == list(range(m))


def test_can_drop_the_most_probable_token() -> None:
    assert 0 not in typical_set(P, F(1, 5))
    assert typical_set(P, F(1, 5)) == [1]


def test_greedy_set_differs_from_the_optimization_of_the_paper() -> None:
    # minimize the sum of |H + log p| over sets of mass >= tau (Equation 12 of
    # Meister et al.), against the greedy prefix that the method uses
    for probs, tau, greedy, optimum in (
        ([F(4, 10), F(3, 10), F(2, 10), F(1, 10)], F(35, 100), [1, 2], (0,)),
        ([F(1, 2), F(1, 4), F(1, 8), F(1, 8)], F(3, 10), [1, 0], (0,)),
    ):
        h = entropy(probs)
        n = len(probs)
        best = min(
            (c for m in range(1, n + 1) for c in itertools.combinations(range(n), m) if sum(probs[i] for i in c) >= tau),
            key=lambda c: sum(abs(h + math.log(probs[i])) for i in c),
        )
        assert typical_set(probs, tau) == greedy
        assert best == optimum
        assert typical_order(probs)[0] not in best


def test_inverse_transform_is_exact_on_a_grid() -> None:
    n = 1600
    q = typical_distribution(P, F(1, 2))
    src = GridU(n)
    counts = [0] * len(P)
    for _ in range(n):
        counts[typical_sample(P, F(1, 2), 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[typical_sample(probs, 0.5, 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 typical_sample_logits([0.0, 0.0, -50.0], 1.0, rng) in (0, 1)


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

History

Meister, Pimentel, Wiher and Cotterell posted "Locally typical sampling" on arXiv in February 2022 and published it in the Transactions of the ACL in 2023. They argued, from psycholinguistic work on uniform information density, that human text keeps the information of each word close to its expected value, and that the most probable strings of a model, which have low information, are therefore atypical (see inadequacy of the mode). A later arXiv version adds an erratum that the optimization formulation can exclude the tokens closest to the entropy and does not match the greedy algorithm, which is the method that the experiments use.

References

  1. Clara Meister, Tiago Pimentel, Gian Wiher and Ryan Cotterell, Locally typical sampling, Transactions of the Association for Computational Linguistics 11, 2023, pages 102 to 121, Section 5 (local typicality and the algorithm: sort by the distance between surprisal and entropy, keep tokens until the mass reaches tau), Section 6.1 (tau = 0.2 for story generation and tau = 0.95 for summarization)
  2. Clara Meister, Tiago Pimentel, Gian Wiher and Ryan Cotterell, Locally typical sampling, arXiv 2202.00666, version 6, the erratum in footnote 18, which notes that the optimization problem of the paper and the greedy algorithm can give different sets
  3. Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes and Yejin Choi, The curious case of neural text degeneration, ICLR 2020, Section 3.1, nucleus sampling, the method that typical sampling changes by ordering the tokens by distance to the entropy

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
  • a scene preset for the example