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.
- Solves
- Autoregressive decoding
- 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
- Model
- Word RAM
- Properties
- randomizedexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Wouter Kool, Herke van Hoof, Max Welling, 2019
Stochastic beam search draws different outputs from an autoregressive model, as if you drew one output, removed it, renormalized, and drew again, times. It does this exactly, with one beam search of width 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 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 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 best tickets are a fair draw of 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 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 for every prefix and token of the vocabulary , which contains </s>; all logs are natural logs. Every output ends with </s> within tokens. A sample of outputs without replacement is a sequence of distinct outputs with probability
The task is to draw from this law with a cost close to that of a beam search of width . If the model has fewer than outputs, the sample is all of them.
A random variable has the Gumbel law with location , written , if . Draw it as with uniform on . Three facts are used, and the proof file proves them. If are independent, then (max-stability). The argmax is with probability (the Gumbel-max trick). And the indices of the largest , in order, are a sample of without replacement from that distribution (the Gumbel-top-k trick).
The algorithm
For a prefix , let , 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 , the largest perturbed value of the outputs below it. The root has and, by convention, ; a constant shift of all values does not change their order.
STOCHASTIC-BEAM-SEARCH(model, n, k, rng)- 1
beam ← { (empty prefix, φ = 0, G = 0) } - 2
for t ← 1 to n do ▷ stop early when every node of the beam is finished - 3
C ← empty list - 4
for each node (y, φ_y, G_y) in the beam do ▷ a finished node goes to C unchanged - 5
children y w with φ_{yw} = φ_y + log p(w | y), for each w with p(w | y) > 0 - 6
draw g_w ~ Gumbel(φ_{yw}) independently; Z ← max over w of g_w - 7
G_{yw} ← -log( exp(-G_y) - exp(-Z) + exp(-g_w) ) ▷ stable form below - 8
sort C by G, largest first ▷ ties: the first generated - 9
beam ← the first k nodes of C - 10
return the finished nodes of the beam, in order of G
Line L7 is the truncation: it maps the independent Gumbels to values whose maximum is exactly , keeping their order. Computed as written, overflows or loses all its digits. The code uses the stable form of Kool et al. (Appendix B): with ,
where for is computed with expm1 for 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 , , ; after a, ; after b, ; 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 with random.Random(3).
| step | parent () | child | Gumbel | after line L7 | |
|---|---|---|---|---|---|
| 1 | root (0) | a | |||
| 1 | root (0) | b | |||
| 1 | root (0) | </s> |
|||
| 2 | b (0) | ba | |||
| 2 | b (0) | bb | |||
| 2 | b (0) | b</s> |
|||
| 2 | a () | aa | |||
| 2 | a () | ab | |||
| 2 | a () | a</s> |
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 (). At step 2 each parent's largest child takes the parent's value: b</s> gets 0 and ab gets . The beam keeps b</s> (finished) and ab. At step 3 ab gets its only child ab</s>, with . The sample is b</s>, then ab</s>.
For this model, the exact probability that the ordered sample is (b</s>, aa</s>) is , and the probability of the set {b</s>, aa</s>} is . 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 are independent Gumbels with maximum , then the values of line L7 have the law of independent variables conditioned on their maximum being . 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 largest outputs: if it did, other nodes at that depth would each have an output below them with a larger value. So the returned outputs are the 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 tokens, so the tree of prefixes of positive probability is finite; its leaves are the outputs. For a node , 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 tokens). We work with exact real numbers and exact Gumbel draws. All logs are natural logs.
has the distribution function . The map turns into an exponential variable with rate , since . It reverses the order: the largest is the smallest .
Lemma 1 (exponential races). Let be independent exponential variables with rates , and . Then is exponential with rate ; the index of the minimum is with probability ; and are independent; and given and , the variables for are independent exponential with rates .
Proof. For and , the joint density of with for all is . The product form gives all four claims.
In Gumbel terms: , the argmax is with probability , and it is independent of the maximum.
Theorem 2 (Gumbel-top-k). Let be independent for . The indices of the largest , in decreasing order, have the law of a sample without replacement from : .
Proof. Pass to . By Lemma 1, with probability , and given that and , the others are plus independent exponentials with their own rates. The smallest of the others is therefore the first in a race among , which by Lemma 1 again is with probability , and the remaining differences are again independent exponentials. Induction on gives the product.
Lemma 3 (truncation). Let be independent with , and . For a fixed real let . Then has the law of conditioned on . Moreover , attained at the same index as , and the map keeps the order of the .
Proof. In the exponential form , , . The map adds the same constant to every , so it keeps the order, and the argmin gets , that is . By Lemma 1, has law , and given , the values are independent exponentials with rates , independent of . So is: , and the others plus independent exponentials. By Lemma 1 applied to the conditional law of given , this is exactly that conditional law.
The stable formula of the page is the same number: with , , so , and .
Lemma 4 (top-down sampling). Attach to every output an independent , and to every internal node the value of over the outputs below . Draw instead from , and for each node , given , draw the values of its children by line L6 and line L7 with . Then the family over all nodes has the same law as .
Proof. The children of partition the outputs below , so by Lemma 1, independently over the children, and . The subtrees are disjoint, so given the values of the children, the families below different children are independent, and the family below depends on the rest only through . So the law of is fixed by the law of the root value, , and the conditional law of the children values given the parent value, which is the law of independent conditioned on their maximum. Lemma 3 says that line L7 draws exactly from that conditional law. Induction on the depth gives the claim.
The code sets the root value to 0 in place of a draw. The proof of Lemma 4 then gives the law of conditioned on . 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 . 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 be the outputs with the largest values (all values are distinct with probability 1). Then after each step , the beam holds, for each , its ancestor at depth (or itself if it is shorter).
Proof. Suppose the ancestor of at depth is a candidate at step but is not kept. Then other candidates have larger values. Each is the maximum over the outputs below it, so it has an output below it with value . The candidates at one depth have disjoint subtrees, so the are distinct outputs, none equal to , with larger values than . That contradicts that is among the largest. By induction on , each kept ancestor produces the next ancestor as a candidate at step .
Theorem 6 (correctness). STOCHASTIC-BEAM-SEARCH returns the outputs with the largest perturbed values, in decreasing order, and these form an exact sample of outputs without replacement from the model (all outputs, in a random order, if there are fewer than ).
Proof. By Lemma 5, after the last step the beam holds , and since it holds at most 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 perturbations of the outputs, the setting of Theorem 2, with , since the outputs' probabilities sum to 1.
Complexity
Each step expands at most nodes. Each expansion makes one model call and draws and shifts at most Gumbels. Selecting the largest of at most candidates takes time with top-k selection; the code sorts, for clarity. Over steps the time is , the same order as a beam search of width . The beam holds prefixes of at most tokens, and the candidates of one step take space.
Compare drawing 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 . Stochastic beam search always makes calls at most.
Properties
- Exact sampling without replacement (a theorem), in the order of the draws.
- Width 1 is ancestral sampling. With each step keeps the child with the largest value, which by the Gumbel-max trick is a draw from .
- No repeats, no rejection. The outputs are distinct by construction, and no draw is thrown away.
- A threshold for estimators. The -th largest value , which the search sees but does not keep, makes 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 , up to a monotone change of variable.
- Estimators. Use the sample with the threshold 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 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.
- near . A naive log1p(-exp(a)) loses the digits for near 0, and log(-expm1(a)) loses them for very negative ; switch at .
- Open nodes at the limit. An output that is still open after tokens is not a leaf of the model. If the model can run past , the sampler is exact only for the model conditioned on finishing in time. Make the model end within 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 -th output is the -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.
# 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag G3YHYE Edit this page History Report an error Markdown