Algorithm Search⌘K

Algorithmresearch

Stochastic beam search

Also called Gumbel-top-k beam search.

Beam search on Gumbel-perturbed log-probabilities that draws k sequences without replacement exactly from a sequence model.

Time
O(n k (M + V)) worst
Space
O(n k + k V) extra
Where
M = the cost of one call of the model; V = the vocabulary size |V|; k = the beam width and the number of samples; n = the most output tokens
Properties
randomizedexactofflineiterative
Origin
Wouter Kool, Herke van Hoof, Max Welling, 2019

Stochastic beam search draws kk different outputs from an autoregressive model, as if you drew one output, removed it, renormalized, and drew again, kk times. It does this exactly, with one beam search of width kk and no rejection. The idea is the Gumbel-max trick applied to every complete output at once: add an independent Gumbel noise to the log probability of each output, and the kk outputs with the largest perturbed values are a sample without replacement. There are too many outputs to perturb one by one, so the method samples the perturbed values top down, from the root of the tree of prefixes, and a beam search on those values finds the kk largest. Kool, van Hoof and Welling introduced it in 2019.

In plain words

Think of all possible texts as the leaves of a tree, where each branch adds one word. Give each text a random ticket: its log probability plus some noise of a special kind. The texts with the kk best tickets are a fair draw of kk different texts. You cannot write a ticket for every text, but you do not need to. The best ticket below a branch has a known random law, so you can draw it for the branch first and then split it among the children so that they agree with it. Then keep the kk branches with the best tickets at each level, as a beam search does. The best ticket of a kept text can never lose to a dropped branch.

The problem

The model gives log⁡p(w∣y)\log p(w \mid y) for every prefix yy and token ww of the vocabulary VV, which contains </s>; all logs are natural logs. Every output ends with </s> within nn tokens. A sample of kk outputs without replacement is a sequence y(1),…,y(k)y^{(1)}, \ldots, y^{(k)} of distinct outputs with probability

P(y(1),…,y(k))=∏i=1kp(y(i))1−∑j<ip(y(j)).P\big(y^{(1)}, \ldots, y^{(k)}\big) = \prod_{i=1}^{k} \frac{p(y^{(i)})}{1 - \sum_{j < i} p(y^{(j)})}.

The task is to draw from this law with a cost close to that of a beam search of width kk. If the model has fewer than kk outputs, the sample is all of them.

A random variable GG has the Gumbel law with location ϕ\phi, written G∼Gumbel(ϕ)G \sim \text{Gumbel}(\phi), if P(G≤x)=exp⁡(−exp⁡(ϕ−x))P(G \le x) = \exp(-\exp(\phi - x)). Draw it as ϕ−log⁡(−log⁡U)\phi - \log(-\log U) with UU uniform on (0,1)(0, 1). Three facts are used, and the proof file proves them. If Gi∼Gumbel(ϕi)G_i \sim \text{Gumbel}(\phi_i) are independent, then max⁡iGi∼Gumbel(log⁡∑ieϕi)\max_i G_i \sim \text{Gumbel}(\log \sum_i e^{\phi_i}) (max-stability). The argmax is ii with probability eϕi/∑jeϕje^{\phi_i} / \sum_j e^{\phi_j} (the Gumbel-max trick). And the indices of the kk largest GiG_i, in order, are a sample of kk without replacement from that distribution (the Gumbel-top-k trick).

The algorithm

For a prefix yy, let ϕy=log⁡p(y)\phi_y = \log p(y), the sum of the token log probabilities; for a finished output it is the log probability of the output. The perturbed value of a prefix is GyG_y, the largest perturbed value of the outputs below it. The root has ϕ=0\phi = 0 and, by convention, G=0G = 0; a constant shift of all values does not change their order.

  1. STOCHASTIC-BEAM-SEARCH(model, n, k, rng)
  2. 1beam ← { (empty prefix, φ = 0, G = 0) }
  3. 2for t ← 1 to n do ▷ stop early when every node of the beam is finished
  4. 3C ← empty list
  5. 4for each node (y, φ_y, G_y) in the beam do ▷ a finished node goes to C unchanged
  6. 5children y w with φ_{yw} = φ_y + log p(w | y), for each w with p(w | y) > 0
  7. 6draw g_w ~ Gumbel(φ_{yw}) independently; Z ← max over w of g_w
  8. 7G_{yw} ← -log( exp(-G_y) - exp(-Z) + exp(-g_w) ) ▷ stable form below
  9. 8sort C by G, largest first ▷ ties: the first generated
  10. 9beam ← the first k nodes of C
  11. 10return the finished nodes of the beam, in order of G

Line L7 is the truncation: it maps the independent Gumbels gwg_w to values whose maximum is exactly GyG_y, keeping their order. Computed as written, exp⁡(−G)\exp(-G) overflows or loses all its digits. The code uses the stable form of Kool et al. (Appendix B): with v=Gy−gw+log⁡(1−exp⁡(gw−Z))v = G_y - g_w + \log(1 - \exp(g_w - Z)),

Gyw=Gy−log⁡(1+ev)=Gy−max⁡(0,v)−log⁡(1+e−∣v∣),G_{yw} = G_y - \log(1 + e^{v}) = G_y - \max(0, v) - \log(1 + e^{-|v|}),

where log⁡(1−ea)\log(1 - e^{a}) for a≤0a \le 0 is computed with expm1 for a>−ln⁡2a > -\ln 2 and with log1p otherwise, the usual way to keep the digits (see the log-sum-exp trick).

Example

Take the model M1 of greedy decoding: at the empty prefix p(a)=0.5p(a) = 0.5, p(b)=0.4p(b) = 0.4, p(</s>)=0.1p(\text{</s>}) = 0.1; after a, 0.4,0.3,0.30.4, 0.3, 0.3; after b, 0.05,0.05,0.90.05, 0.05, 0.9; after two tokens, </s> has probability 1. Its seven outputs and their probabilities are </s> 0.1, a</s> 0.15, aa</s> 0.2, ab</s> 0.15, b</s> 0.36, ba</s> 0.02 and bb</s> 0.02. Run k=2k = 2 with random.Random(3).

step parent (GG) child ϕ\phi Gumbel gg GG after line L7
1 root (0) a −0.693-0.693 −1.055-1.055 −0.855-0.855
1 root (0) b −0.916-0.916 −0.419-0.419 0.0000.000
1 root (0) </s> −2.303-2.303 −2.297-2.297 −2.243-2.243
2 b (0) ba −3.912-3.912 −3.227-3.227 −2.926-2.926
2 b (0) bb −3.912-3.912 −3.155-3.155 −2.826-2.826
2 b (0) b</s> −1.022-1.022 −2.024-2.024 0.0000.000
2 a (−0.855-0.855) aa −1.609-1.609 −3.075-3.075 −3.128-3.128
2 a (−0.855-0.855) ab −1.897-1.897 −0.168-0.168 −0.855-0.855
2 a (−0.855-0.855) a</s> −1.897-1.897 −2.197-2.197 −2.319-2.319

At step 1 the largest Gumbel, b's, is shifted to the root's value 0, and the others move with it; the beam keeps b (0) and a (−0.855-0.855). At step 2 each parent's largest child takes the parent's value: b</s> gets 0 and ab gets −0.855-0.855. The beam keeps b</s> (finished) and ab. At step 3 ab gets its only child ab</s>, with G=−0.855G = -0.855. The sample is b</s>, then ab</s>.

For this model, the exact probability that the ordered sample is (b</s>, aa</s>) is 0.36⋅0.2/0.64=0.11250.36 \cdot 0.2 / 0.64 = 0.1125, and the probability of the set {b</s>, aa</s>} is 0.1125+0.2⋅0.36/0.8=0.20250.1125 + 0.2 \cdot 0.36 / 0.8 = 0.2025. The tests draw 20000 samples of size 1 and 2 and compare the frequencies with these exact values, with a tolerance of 0.01, and 10000 samples of size 3 on a random model with a tolerance of 0.015.

Correctness

The proof is in proofs/correctness.md. It has four steps. First, the Gumbel-top-k trick on a flat list, proved with exponential races. Second, the truncation lemma: if gwg_w are independent Gumbels with maximum ZZ, then the values of line L7 have the law of independent Gumbel(ϕyw)\text{Gumbel}(\phi_{yw}) variables conditioned on their maximum being GyG_y. Third, by induction down the tree, the values that the algorithm draws for any set of nodes have the same joint law as the maxima of independent Gumbel perturbations of all outputs. Fourth, the beam never drops an ancestor of one of the kk largest outputs: if it did, kk other nodes at that depth would each have an output below them with a larger value. So the returned outputs are the kk largest perturbed outputs, and by the first step they are an exact sample without replacement.

This is a theorem about the algorithm with exact real arithmetic and exact Gumbel draws. The code uses floating point; the tests check the sampling frequencies, and check that the shift keeps the order and puts the maximum exactly on the parent's value.

Proof: Stochastic beam search returns an exact sample without replacementfull

We use the notation of the page. Every output ends with </s> within nn tokens, so the tree of prefixes of positive probability is finite; its leaves are the outputs. For a node yy, ϕy=log⁡p(y)\phi_y = \log p(y) is the log of the total probability of the outputs below it (for a prefix, the product of its token probabilities is the total probability of its completions, since the model ends within nn tokens). We work with exact real numbers and exact Gumbel draws. All logs are natural logs.

Gumbel(ϕ)\text{Gumbel}(\phi) has the distribution function Fϕ(x)=exp⁡(−eϕ−x)F_\phi(x) = \exp(-e^{\phi - x}). The map E=e−GE = e^{-G} turns G∼Gumbel(ϕ)G \sim \text{Gumbel}(\phi) into an exponential variable with rate λ=eϕ\lambda = e^{\phi}, since P(E>u)=P(G<−log⁡u)=e−λuP(E > u) = P(G < -\log u) = e^{-\lambda u}. It reverses the order: the largest GG is the smallest EE.

Lemma 1 (exponential races). Let E1,…,EmE_1, \ldots, E_m be independent exponential variables with rates λ1,…,λm\lambda_1, \ldots, \lambda_m, and Λ=∑iλi\Lambda = \sum_i \lambda_i. Then M=min⁡iEiM = \min_i E_i is exponential with rate Λ\Lambda; the index II of the minimum is ii with probability λi/Λ\lambda_i / \Lambda; II and MM are independent; and given I=iI = i and MM, the variables Ej−ME_j - M for j≠ij \ne i are independent exponential with rates λj\lambda_j.

Proof. For u≥0u \ge 0 and xj≥0x_j \ge 0, the joint density of Ei=uE_i = u with Ej>u+xjE_j > u + x_j for all j≠ij \ne i is λie−λiu∏j≠ie−λj(u+xj)=λiΛ⋅Λe−Λu⋅∏j≠ie−λjxj\lambda_i e^{-\lambda_i u} \prod_{j \ne i} e^{-\lambda_j (u + x_j)} = \frac{\lambda_i}{\Lambda} \cdot \Lambda e^{-\Lambda u} \cdot \prod_{j \ne i} e^{-\lambda_j x_j}. The product form gives all four claims. □\square

In Gumbel terms: max⁡iGi∼Gumbel(log⁡∑ieϕi)\max_i G_i \sim \text{Gumbel}(\log \sum_i e^{\phi_i}), the argmax is ii with probability pi=eϕi/∑jeϕjp_i = e^{\phi_i} / \sum_j e^{\phi_j}, and it is independent of the maximum.

Theorem 2 (Gumbel-top-k). Let Gi∼Gumbel(ϕi)G_i \sim \text{Gumbel}(\phi_i) be independent for i=1,…,mi = 1, \ldots, m. The indices I1,…,IkI_1, \ldots, I_k of the kk largest GiG_i, in decreasing order, have the law of a sample without replacement from pp: P(I1=i1,…,Ik=ik)=∏r=1kpir/(1−∑s<rpis)P(I_1 = i_1, \ldots, I_k = i_k) = \prod_{r=1}^{k} p_{i_r} / (1 - \sum_{s < r} p_{i_s}).

Proof. Pass to Ei=e−GiE_i = e^{-G_i}. By Lemma 1, I1=i1I_1 = i_1 with probability pi1p_{i_1}, and given that and MM, the others are MM plus independent exponentials with their own rates. The smallest of the others is therefore the first in a race among {Ej−M:j≠i1}\{E_j - M : j \ne i_1\}, which by Lemma 1 again is jj with probability λj/∑l≠i1λl=pj/(1−pi1)\lambda_j / \sum_{l \ne i_1} \lambda_l = p_j / (1 - p_{i_1}), and the remaining differences are again independent exponentials. Induction on kk gives the product. □\square

Lemma 3 (truncation). Let g1,…,gmg_1, \ldots, g_m be independent with gi∼Gumbel(ϕi)g_i \sim \text{Gumbel}(\phi_i), and Z=max⁡igiZ = \max_i g_i. For a fixed real TT let g~i=−log⁡(e−T−e−Z+e−gi)\tilde g_i = -\log(e^{-T} - e^{-Z} + e^{-g_i}). Then (g~1,…,g~m)(\tilde g_1, \ldots, \tilde g_m) has the law of (g1,…,gm)(g_1, \ldots, g_m) conditioned on max⁡igi=T\max_i g_i = T. Moreover max⁡ig~i=T\max_i \tilde g_i = T, attained at the same index as ZZ, and the map keeps the order of the gig_i.

Proof. In the exponential form Ei=e−giE_i = e^{-g_i}, M=e−ZM = e^{-Z}, E~i=e−g~i=e−T+(Ei−M)\tilde E_i = e^{-\tilde g_i} = e^{-T} + (E_i - M). The map adds the same constant to every EiE_i, so it keeps the order, and the argmin II gets E~I=e−T\tilde E_I = e^{-T}, that is g~I=T\tilde g_I = T. By Lemma 1, II has law pp, and given II, the values Ej−ME_j - M are independent exponentials with rates λj\lambda_j, independent of MM. So (E~j)(\tilde E_j) is: E~I=e−T\tilde E_I = e^{-T}, and the others e−Te^{-T} plus independent exponentials. By Lemma 1 applied to the conditional law of (Ej)(E_j) given M=e−TM = e^{-T}, this is exactly that conditional law. □\square

The stable formula of the page is the same number: with v=T−g+log⁡(1−eg−Z)v = T - g + \log(1 - e^{g - Z}), e−T−e−Z+e−g=e−T(1+ev)e^{-T} - e^{-Z} + e^{-g} = e^{-T}(1 + e^{v}), so g~=T−log⁡(1+ev)\tilde g = T - \log(1 + e^v), and log⁡(1+ev)=max⁡(0,v)+log⁡(1+e−∣v∣)\log(1 + e^v) = \max(0, v) + \log(1 + e^{-|v|}).

Lemma 4 (top-down sampling). Attach to every output yy an independent Gy∼Gumbel(ϕy)G_y \sim \text{Gumbel}(\phi_y), and to every internal node uu the value Gu=max⁡G_u = \max of GyG_y over the outputs below uu. Draw instead G^root\hat G_{\text{root}} from Gumbel(ϕroot)=Gumbel(0)\text{Gumbel}(\phi_{\text{root}}) = \text{Gumbel}(0), and for each node uu, given G^u\hat G_u, draw the values of its children by line L6 and line L7 with T=G^uT = \hat G_u. Then the family (G^u)(\hat G_u) over all nodes has the same law as (Gu)(G_u).

Proof. The children of uu partition the outputs below uu, so by Lemma 1, Guw∼Gumbel(ϕuw)G_{u w} \sim \text{Gumbel}(\phi_{uw}) independently over the children, and Gu=max⁡wGuwG_u = \max_w G_{uw}. The subtrees are disjoint, so given the values of the children, the families below different children are independent, and the family below uwuw depends on the rest only through GuwG_{uw}. So the law of (Gu)(G_u) is fixed by the law of the root value, Gumbel(log⁡∑yp(y))=Gumbel(0)\text{Gumbel}(\log \sum_y p(y)) = \text{Gumbel}(0), and the conditional law of the children values given the parent value, which is the law of independent Gumbel(ϕuw)\text{Gumbel}(\phi_{uw}) conditioned on their maximum. Lemma 3 says that line L7 draws exactly from that conditional law. Induction on the depth gives the claim. □\square

The code sets the root value to 0 in place of a Gumbel(0)\text{Gumbel}(0) draw. The proof of Lemma 4 then gives the law of (Gu)(G_u) conditioned on Groot=0G_{\text{root}} = 0. The algorithm uses only the order of the values, and the order of the outputs' values is independent of their maximum: by Lemma 1 applied again and again, the first index, then the first of the remaining differences, and so on, are independent of MM. So the conditioning does not change the law of the order, and the root value can be any constant.

Lemma 5 (the beam keeps the top k). In the algorithm, treat a finished node as its own only descendant at every later depth. Let y1,…,yky_1, \ldots, y_k be the outputs with the kk largest values (all values are distinct with probability 1). Then after each step tt, the beam holds, for each yry_r, its ancestor at depth tt (or yry_r itself if it is shorter).

Proof. Suppose the ancestor uu of yry_r at depth tt is a candidate at step tt but is not kept. Then kk other candidates v1,…,vkv_1, \ldots, v_k have larger values. Each vsv_s is the maximum over the outputs below it, so it has an output xsx_s below it with value G^vs>G^u≥G^yr\hat G_{v_s} > \hat G_u \ge \hat G_{y_r}. The candidates at one depth have disjoint subtrees, so the xsx_s are kk distinct outputs, none equal to yry_r, with larger values than yry_r. That contradicts that yry_r is among the kk largest. By induction on tt, each kept ancestor produces the next ancestor as a candidate at step t+1t + 1. □\square

Theorem 6 (correctness). STOCHASTIC-BEAM-SEARCH returns the outputs with the kk largest perturbed values, in decreasing order, and these form an exact sample of kk outputs without replacement from the model (all outputs, in a random order, if there are fewer than kk).

Proof. By Lemma 5, after the last step the beam holds y1,…,yky_1, \ldots, y_k, and since it holds at most kk nodes, it holds nothing else; line L10 returns them in the order of their values. By Lemma 4, the values have the law of independent Gumbel(log⁡p(y))\text{Gumbel}(\log p(y)) perturbations of the outputs, the setting of Theorem 2, with py=p(y)p_y = p(y), since the outputs' probabilities sum to 1. □\square

Complexity

Each step expands at most kk nodes. Each expansion makes one model call and draws and shifts at most ∣V∣|V| Gumbels. Selecting the kk largest of at most k∣V∣k |V| candidates takes O(k∣V∣)O(k |V|) time with top-k selection; the code sorts, for clarity. Over nn steps the time is O(nk(M+∣V∣))O(n k (M + |V|)), the same order as a beam search of width kk. The beam holds kk prefixes of at most nn tokens, and the candidates of one step take O(k∣V∣)O(k |V|) space.

Compare drawing kk distinct outputs by repeated ancestral sampling and throwing away repeats. When a few outputs hold most of the probability, almost every new draw is a repeat, and the number of draws needed has no bound in terms of kk. Stochastic beam search always makes nkn k calls at most.

Properties

  • Exact sampling without replacement (a theorem), in the order of the draws.
  • Width 1 is ancestral sampling. With k=1k = 1 each step keeps the child with the largest value, which by the Gumbel-max trick is a draw from p(w∣y)p(w \mid y).
  • No repeats, no rejection. The kk outputs are distinct by construction, and no draw is thrown away.
  • A threshold for estimators. The (k+1)(k+1)-th largest value κ\kappa, which the search sees but does not keep, makes q(y)=1−exp⁡(−exp⁡(ϕy−κ))q(y) = 1 - \exp(-\exp(\phi_y - \kappa)) the inclusion probability of an output; Kool et al. use it in an estimator of expectations that is unbiased for sampling without replacement.

Variants and improvements

  • Temperature. Divide the log probabilities by a temperature before perturbing to sample from a sharper or flatter model (temperature sampling); the sampler stays exact for the new model.
  • Flat lists. On a single categorical distribution the method reduces to the Gumbel-top-k trick, which is the same as weighted reservoir sampling with keys u1/wu^{1/w}, up to a monotone change of variable.
  • Estimators. Use the sample with the threshold κ\kappa for low variance estimates of an expected reward or loss, for example in minimum Bayes risk decoding, or with importance sampling weights.
  • Diverse search. Diverse beam search also returns different outputs, but by a penalty and without a probabilistic meaning.

When to use it

Use stochastic beam search when you need kk distinct outputs and their sampling probabilities matter: low variance estimates of an expectation over outputs, training with sampled sequences, or a candidate set for reranking that is still a fair sample. Use ordinary sampling when repeats are fine, and plain beam search when you want the most probable outputs.

Pitfalls

  • Overflow in the shift. The formula of line L7 overflows for large values; use the stable form.
  • log⁡(1−ea)\log(1 - e^a) near a=0a = 0. A naive log1p(-exp(a)) loses the digits for aa near 0, and log(-expm1(a)) loses them for very negative aa; switch at a=−ln⁡2a = -\ln 2.
  • Open nodes at the limit. An output that is still open after nn tokens is not a leaf of the model. If the model can run past nn, the sampler is exact only for the model conditioned on finishing in time. Make the model end within nn tokens.
  • Reusing the noise. Every expansion needs fresh independent Gumbels. Reusing a seed across calls correlates the samples.
  • Order matters. The values are a ranking: the ii-th output is the ii-th draw. Sorting the outputs by probability afterwards loses that, which matters for the estimators.

Implementations

The code takes the log probabilities of the model as given, as a function of the prefix, and implements the sampler around them; 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
stochastic_beam_search.py 86 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stochastic-beam-search/. The authors are listed in prov/G3YHYE.jsonl.

"""Stochastic beam search (Kool, van Hoof and Welling 2019).

A model is a function that takes the prefix y_1 ... y_t (a tuple of strings)
and returns a dict from each token to log p(w | prefix), in natural log. The
end token is the string "</s>". The code takes these log probabilities as
given; it does not run or train a network.

The search draws k distinct finished outputs. They are a sample without
replacement from the model: the first is a draw from p, the second a draw
from p restricted to the other outputs, and so on.
"""

import math
import random
from typing import Callable, Dict, List, Tuple

from nlslog import NEG_INF

EOS = "</s>"

Model = Callable[[Tuple[str, ...]], Dict[str, float]]
Node = Tuple[Tuple[str, ...], float, float]  # (tokens, log p, perturbed log p)


def gumbel(phi: float, rng: random.Random) -> float:
    """Return a sample of Gumbel(phi): phi - log(-log U) with U uniform on (0, 1)."""
    u = rng.random()
    while u == 0.0:
        u = rng.random()
    return phi - math.log(-math.log(u))


def log1mexp(a: float) -> float:
    """Return log(1 - exp(a)) for a <= 0, stably. log1mexp(0) is NEG_INF."""
    if a > 0:
        raise ValueError("log1mexp needs a <= 0")
    if a == 0:
        return NEG_INF
    if a > -math.log(2.0):
        return math.log(-math.expm1(a))
    return math.log1p(-math.exp(a))


def shift(target: float, z: float, g: float) -> float:
    """Return -log(exp(-target) - exp(-z) + exp(-g)), computed stably.

    The children of a node get Gumbels g with maximum z. The shifted values
    have maximum target, and the order among them does not change.
    """
    v = target - g + log1mexp(g - z)
    return target - max(0.0, v) - math.log1p(math.exp(-abs(v)))


def stochastic_beam_search(
    model: Model, max_len: int, k: int, rng: random.Random
) -> List[Tuple[List[str], float, float]]:
    """Return k distinct outputs as (tokens, log p, perturbed log p).

    The outputs come in decreasing order of the perturbed log probability,
    which is the order in which a sampling without replacement draws them.
    Fewer than k outputs are returned if the model has fewer outputs of at
    most max_len tokens. A node that is still open after max_len tokens is
    dropped, so the model should put "</s>" within max_len tokens.
    """
    if k < 1 or max_len < 1:
        raise ValueError("k and max_len must be at least 1")
    beam: List[Node] = [((), 0.0, 0.0)]  # @line L1
    for _ in range(max_len):  # @line L2
        if all(y and y[-1] == EOS for y, _, _ in beam):
            break
        cand: List[Node] = []  # @line L3
        for y, phi, g in beam:  # @line L4
            if y and y[-1] == EOS:
                cand.append((y, phi, g))
                continue
            children = [(y + (w,), phi + lp) for w, lp in model(y).items() if lp > NEG_INF]  # @line L5
            gs = [gumbel(cphi, rng) for _, cphi in children]  # @line L6
            z = max(gs)
            for (cy, cphi), cg in zip(children, gs):
                cand.append((cy, cphi, shift(g, z, cg)))  # @line L7
        order = sorted(range(len(cand)), key=lambda i: (-cand[i][2], i))  # @line L8
        beam = [cand[i] for i in order[:k]]  # @line L9
    return [(list(y), phi, g) for y, phi, g in beam if y and y[-1] == EOS]  # @line L10
test_stochastic_beam_search.py 172 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stochastic-beam-search/. The authors are listed in prov/G3YHYE.jsonl.

import itertools
import math
import random
from collections import Counter

from nlslog import NEG_INF, log_normalize, safe_log
from stochastic_beam_search import EOS, gumbel, log1mexp, shift, stochastic_beam_search

M1 = {
    (): {"a": 0.5, "b": 0.4, EOS: 0.1},
    ("a",): {"a": 0.4, "b": 0.3, EOS: 0.3},
    ("b",): {"a": 0.05, "b": 0.05, EOS: 0.9},
}
M1_CACHE = {}


def m1(prefix):
    key = tuple(prefix)
    if key not in M1_CACHE:
        probs = M1.get(key, {"a": 0.0, "b": 0.0, EOS: 1.0})
        M1_CACHE[key] = {w: safe_log(p) for w, p in probs.items()}
    return M1_CACHE[key]


def random_model(seed, vocab, n):
    cache = {}

    def model(prefix):
        if prefix not in cache:
            if len(prefix) >= n - 1:
                cache[prefix] = {w: (0.0 if w == EOS else NEG_INF) for w in vocab}
            else:
                rng = random.Random(f"{seed}|{' '.join(prefix)}")
                raw = [math.log(rng.random() ** 2 + 1e-3) for _ in vocab]
                cache[prefix] = dict(zip(vocab, log_normalize(raw)))
        return cache[prefix]

    return model


def exhaustive(model, n):
    out = []

    def rec(prefix, s):
        for w, lp in model(tuple(prefix)).items():
            if lp == NEG_INF:
                continue
            if w == EOS:
                out.append((tuple(prefix + [w]), s + lp))
            elif len(prefix) + 1 < n:
                rec(prefix + [w], s + lp)

    rec([], 0.0)
    return out


def ordered_probability(ps):
    """Probability that sampling without replacement draws ps[0], ps[1], ... first."""
    prob, left = 1.0, 1.0
    for p in ps:
        prob *= p / left
        left -= p
    return prob


def test_m1_has_seven_outputs() -> None:
    probs = {y: math.exp(s) for y, s in exhaustive(m1, 3)}
    assert len(probs) == 7
    assert math.isclose(math.fsum(probs.values()), 1.0)
    b, aa = ("b", EOS), ("a", "a", EOS)
    assert math.isclose(ordered_probability([probs[b], probs[aa]]), 0.1125)
    pair = ordered_probability([probs[b], probs[aa]]) + ordered_probability([probs[aa], probs[b]])
    assert math.isclose(pair, 0.2025)


def test_k1_is_a_sample_from_the_model() -> None:
    rng = random.Random(7)
    probs = {y: math.exp(s) for y, s in exhaustive(m1, 3)}
    draws = 20000
    counts = Counter(tuple(stochastic_beam_search(m1, 3, 1, rng)[0][0]) for _ in range(draws))
    for y, p in probs.items():
        assert abs(counts[y] / draws - p) < 0.01


def test_k2_ordered_pairs() -> None:
    rng = random.Random(11)
    probs = {y: math.exp(s) for y, s in exhaustive(m1, 3)}
    draws = 20000
    counts = Counter()
    for _ in range(draws):
        out = stochastic_beam_search(m1, 3, 2, rng)
        assert len(out) == 2 and out[0][0] != out[1][0]
        assert out[0][2] >= out[1][2]
        counts[(tuple(out[0][0]), tuple(out[1][0]))] += 1
    for y1, y2 in itertools.permutations(probs, 2):
        want = ordered_probability([probs[y1], probs[y2]])
        assert abs(counts[(y1, y2)] / draws - want) < 0.01


def test_k3_sets_on_a_random_model() -> None:
    model = random_model(5, ["a", "b", EOS], 3)
    probs = {y: math.exp(s) for y, s in exhaustive(model, 3)}
    assert len(probs) == 7
    rng = random.Random(3)
    draws = 10000
    counts = Counter(
        frozenset(tuple(y) for y, _, _ in stochastic_beam_search(model, 3, 3, rng)) for _ in range(draws)
    )
    for s in itertools.combinations(probs, 3):
        want = sum(ordered_probability([probs[y] for y in perm]) for perm in itertools.permutations(s))
        assert abs(counts[frozenset(s)] / draws - want) < 0.015


def test_large_k_returns_everything_once() -> None:
    for seed in range(20):
        model = random_model(seed, ["a", "b", "c", EOS], 4)
        everything = dict(exhaustive(model, 4))
        out = stochastic_beam_search(model, 4, len(everything) + 5, random.Random(seed))
        assert len(out) == len(everything)
        assert {tuple(y) for y, _, _ in out} == set(everything)
        for y, phi, _ in out:
            assert math.isclose(phi, everything[tuple(y)])


def test_shift_keeps_order_and_sets_the_maximum() -> None:
    rng = random.Random(2)
    for _ in range(500):
        target = rng.uniform(-5, 5)
        gs = [gumbel(rng.uniform(-6, 0), rng) for _ in range(rng.randrange(1, 6))]
        z = max(gs)
        shifted = [shift(target, z, g) for g in gs]
        assert max(shifted) == target
        for i in range(len(gs)):
            assert shifted[i] <= target
            for j in range(len(gs)):
                if gs[i] < gs[j]:
                    assert shifted[i] <= shifted[j]
        for g, s in zip(gs, shifted):
            direct = -math.log(math.exp(-target) - math.exp(-z) + math.exp(-g))
            assert math.isclose(s, direct, rel_tol=1e-9, abs_tol=1e-9)


def test_log1mexp() -> None:
    for a in (-1e-12, -1e-5, -0.3, -0.69):
        assert math.isclose(log1mexp(a), math.log(-math.expm1(a)), rel_tol=1e-12)
    for a in (-0.7, -2.0, -10.0):
        assert math.isclose(math.exp(log1mexp(a)) + math.exp(a), 1.0, rel_tol=1e-14)
    # For a very negative a, log(1 - e^a) is about -e^a; the naive form rounds to 0.
    assert math.isclose(log1mexp(-40.0), -math.exp(-40.0), rel_tol=1e-12)
    assert math.log(1.0 - math.exp(-40.0)) == 0.0
    assert log1mexp(0.0) == NEG_INF


def test_long_outputs_stay_in_log_space() -> None:
    steps = 1300
    vocab = ["a", "b", EOS]

    def model(prefix):
        if len(prefix) >= steps:
            return {"a": NEG_INF, "b": NEG_INF, EOS: 0.0}
        return {"a": math.log(0.5), "b": math.log(0.5), EOS: NEG_INF}

    out = stochastic_beam_search(model, steps + 1, 3, random.Random(4))
    assert len({tuple(y) for y, _, _ in out}) == 3
    for y, phi, _ in out:
        assert len(y) == steps + 1
        assert math.isclose(phi, steps * math.log(0.5))
        assert math.exp(phi) == 0.0
    assert vocab[-1] == EOS

History

The Gumbel-max trick goes back to the study of choice models and to extreme value theory; it was popular in machine learning by the 2010s. Kool, van Hoof and Welling 2019 observed that the top-down sampling of perturbed values, used before for single samples, can be pruned by a beam, and that the beam then returns an exact sample without replacement. They applied it to translation and to estimators of sentence-level quantities.

References

  1. Wouter Kool, Herke van Hoof and Max Welling, Stochastic beams and where to find them, the Gumbel-top-k trick for sampling sequences without replacement, ICML 2019, PMLR 97, pages 3499 to 3508, the Gumbel-top-k trick, the top-down sampling of perturbed log probabilities with truncated Gumbels, Algorithm 1 (stochastic beam search), and Appendix B (the numerically stable form of the truncation)

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