Algorithmadvanced
Grid beam search
Also called lexically constrained decoding.
Beam search with one beam per count of satisfied constraint tokens, so that the output must contain given words or phrases.
- Solves
- Autoregressive decoding
- Time
- O(n k (c + 1) (M + V + m)) worst
- Space
- O(n k (c + 1) + V) extra
- Where
- M = the cost of one call of the model; V = the vocabulary size |V|; c = the total number of constraint tokens; k = the beam width of one cell; m = the number of phrases; n = the most output tokens
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Chris Hokamp, Qun Liu, 2017
Grid beam search finds a probable output of an autoregressive model that contains a given set of words or phrases, for example the required terms of a glossary in machine translation. A plain beam search cannot do this by filtering at the end, because hypotheses that hold the phrases usually fall out of the beam early: forcing a word in costs probability now, and pays off only later. Hokamp and Liu 2017 keep a separate beam for each count of constraint tokens covered so far. A hypothesis competes only with hypotheses that have covered as much as it has, and only the cell that has covered all constraint tokens may finish. The cost is beams in place of one, so the number of model calls grows linearly with . It is a heuristic: with a finite beam it can miss the best output that holds the phrases, and the page shows such a case.
In plain words
You want the model to write a text that uses some given words. If you just add the words to a normal search, the texts that contain them lose to texts that skip them, because a forced word looks unlikely at the moment you add it. So grid beam search sorts the partial texts into bins by how many of the required words they already hold. Texts only compete inside their own bin. At each step a text can add a free word and stay in its bin, or add the next required word and move up one bin. Only texts in the top bin, which hold every required word, may stop.
The problem
The model gives for every prefix and every token of the vocabulary , which contains </s>. All logs are natural logs. The constraints are phrases , each a non-empty sequence of tokens without </s>, with tokens in all. An output of at most tokens, </s> included, holds the constraints if each phrase appears in as a contiguous block and the blocks take disjoint positions. The task is
This is a search problem over an exponential set, and grid beam search is a heuristic for it. A phrase may contain the same token as the free text; the search then has two ways to produce the same output, and both compete.
The algorithm
A hypothesis is a prefix with its score, the set of phrases it has covered, and, if it is inside a phrase, which phrase and how far. A hypothesis inside a phrase is open; the others are closed. The cell at step holds the hypotheses of tokens of which are constraint tokens.
GRID-BEAM-SEARCH(model, P_1 .. P_m, n, k)- 1
Grid[0] ← { empty prefix, score 0, nothing covered }; Grid[c'] ← ∅ for c' > 0; best ← none - 2
for t ← 1 to n do - 3
for c' ← 0 to c, for each hypothesis h in Grid[c'] do - 4
ℓ ← model(h.prefix) ▷ one call per hypothesis - 5
if h is closed and c' = c then best ← the better of best and h + "</s>" if t = n then continue ▷ no room for a token before "</s>"if h is closed then- 6
generate: for each w ≠ "</s>", put h + w with score + ℓ[w] into Next[c'] - 7
start: for each phrase i not covered, put h + P_i[1] into Next[c' + 1] else- 8
continue: put h + the next token of its phrase into Next[c' + 1] - 9
for each c': empty Next[c'] if c' < c - (n - 1 - t), else keep its k best; Grid ← Next - 10
return best ▷ none if no output held every phrase
Line L9 drops cells that cannot reach covered tokens with the tokens that remain before </s>. The code numbers the steps as the pseudocode does and counts the model calls.
Example
Take the model M1 of greedy decoding: at the empty prefix , , ; after a, ; after b, ; after two tokens, </s> has probability 1. Without constraints the best output is b</s> (0.36). Require the phrase "a", so , with and .
- Step 1. The empty prefix (call 1) generates a () and b () into cell 0, and starts the phrase with a () into cell 1. Each cell keeps one: a in cell 0, and the constraint a in cell 1.
- Step 2. The free a (call 2) generates aa and ab into cell 0 and starts the phrase: aa () into cell 1. The constraint a (call 3) is closed in cell , so it finishes a
</s>(); it also generates aa () and ab () into cell 1. Cell 0 can no longer reach in time, so line L9 empties it. Cell 1 holds aa twice, one copy from each route, and keeps the first. - Step 3. aa (call 4) finishes aa
</s>(), better than a</s>.
The result is aa</s> with probability 0.2, after 4 calls, which is the best output that contains a. With the phrase "b" the search returns b</s> (0.36).
A narrow grid can fail. On a random model with tokens a, b, c and </s> (seed 0 in the test), the phrase "b c", and , grid beam search returns b c </s> with log probability , but the best output that holds the phrase is a c b c </s>, with . A grid with an unbounded beam finds it. On 40 random models with the narrow grid misses the best output on some of them and not on all; the test checks both.
Correctness
The proof is in proofs/correctness.md. It proves four facts. Every output returned holds all the phrases (soundness), because only closed hypotheses in cell finish and a hypothesis reaches cell only by placing every token of every phrase at disjoint positions. Line L9 drops only hypotheses that can no longer finish. With at least the size of every cell, the search enumerates every pair of an output and a placement of the phrases in it, so it returns the best output that holds the phrases: it is then an exhaustive search. And the number of model calls is at most .
With a finite the search is a heuristic, as the seed 0 case shows. The test compares it with exhaustive search over all outputs that hold the phrases.
Proof: Grid beam search is sound, exact with an unbounded beam, and makes at most n k (c + 1) callsfull
We use the notation of the page. The phrases are non-empty, contain no </s>, and have tokens in all. An output ends with its only </s>, so its body is . A placement of the phrases in is a choice of start positions such that for each , and the blocks are disjoint subsets of the body. The output holds the phrases if it has a placement.
A hypothesis has a prefix , a score , a set of covered phrases, and, if it is open, a phrase index and a position with . Write for an open , and for a closed one.
Lemma 1 (invariant of a hypothesis). Every hypothesis that the search builds satisfies: (a) , the sum of the token log probabilities; (b) lies in the cell ; (c) has disjoint blocks that hold each covered phrase in full and, if is open, the first tokens of at the end of , and these blocks are disjoint.
Proof. By induction on the steps. The empty hypothesis of line L1 has score 0, nothing covered, and lies in cell 0. Line L6 appends a free token to a closed , adds and keeps the cell and the blocks. Line L7 appends the first token of an uncovered phrase to a closed ; the new block starts at the new position, after all old blocks, so it is disjoint from them, and the count grows by 1, which is the cell . If the phrase is covered at once. Line L8 appends the next token of the open phrase at the end, so its block stays contiguous, and the count grows by 1; when the last token is placed, the phrase moves to and becomes closed. Line L9 only removes hypotheses.
Theorem 2 (soundness). If the search returns , then holds the phrases and .
Proof. Line L5 finishes only a closed hypothesis in cell . By Lemma 1(b) and since is closed, , so holds all phrases, and by Lemma 1(c) their blocks are disjoint and lie in , the body of </s>. The score is by Lemma 1(a).
Lemma 3 (safe pruning of cells). A hypothesis of tokens with count has no extension to an output of at most tokens that the search can finish.
Proof. Each token adds at most 1 to the count, and a finished output of at most tokens has at most more tokens before its </s>. To finish, the count must reach (Theorem 2), so is needed.
Theorem 4 (exact with an unbounded beam). If is at least the number of hypotheses that are ever put into one cell at one step, the search returns an output that holds the phrases with the largest among all outputs of at most tokens, or none if there is no such output of positive probability.
Proof. With such a , line L9 removes only the cells of Lemma 3. Take an output of positive probability and at most tokens with a placement . Build its hypotheses token by token: at position of the body, if for some , use line L7 with phrase ; if lies inside a block that started earlier, use line L8; otherwise use line L6. Each choice is allowed, since a block starts only when the hypothesis is closed (the blocks are disjoint and contiguous, so the previous block has ended), the phrase is not covered yet, and every token has positive probability. After the body, the hypothesis is closed with count , and line L5 at the next step finishes with its true score. None of these hypotheses is removed by Lemma 3, since each has a completion. So is a candidate for best, and line L5 keeps the largest score seen. By Theorem 2 every candidate holds the phrases.
Theorem 5 (the call bound). The search makes at most model calls.
Proof. Line L4 makes one call per hypothesis in the grid at the start of a step. After line L9 each of the cells holds at most hypotheses, and line L1 starts with one. There are steps.
What is not claimed. With a finite , line L9 can remove the prefix of , and the search returns a worse output or none. The page gives a model (seed 0 in the test) where returns b c </s> with log probability , while = a c b c </s> has . The test also checks that an unbounded beam returns on that model, as Theorem 4 says.
Complexity
The grid has cells of at most hypotheses, so each step makes at most model calls, and steps make at most , the of Hokamp and Liu (Section 3.3) with . A closed hypothesis produces at most candidates and an open one produces one. Selecting the best of a cell takes linear time with top-k selection, so the time is for a call cost in the word RAM; the code sorts each cell, for clarity. The grid at one step holds hypotheses, each with a prefix of tokens.
The calls in one step are independent, so a GPU runs them in one batch of prefixes. With many constraints this batch is large, which is the reason for the fixed-size beam of Post and Vilar 2018.
Properties
- Sound (a theorem). Every output it returns holds every phrase.
- Exact with an unbounded beam (a theorem), and a heuristic with a finite beam (the seed 0 case).
- Linear in the constraints. The model calls grow as , not with the number of subsets of phrases.
- Order free. The phrases can appear in any order in the output; the search does not need an alignment to the input.
- No output. If no output of at most tokens holds the phrases, or the beam lost all of them, it returns nothing.
Variants and improvements
- Dynamic beam allocation. Post and Vilar 2018 keep one beam of size for all counts and divide its slots among the counts at each step. The cost no longer grows with .
- Disjunctive constraints. Allow a set of alternative phrases, for example the inflected forms of a term, and count the constraint as met when any one of them appears.
- Negative constraints. Forbid phrases by masking the token that would complete them. A matcher such as Aho-Corasick over the forbidden phrases tracks the partial matches of a prefix.
- Grammars. Grammar-constrained decoding masks the tokens that a grammar or an automaton does not allow at each step, which also handles structure such as JSON.
- Training with constraints. Some systems copy the constraints into the input and train the model to use them. That moves the work from the search to the model, without a guarantee that the phrases appear.
When to use it
Use grid beam search when certain words must appear and you can afford times the work of a beam search: terminology in translation, interactive translation where a user fixes a word, or keywords in a generated description. With many constraints, or on a tight latency budget, use dynamic beam allocation. If the constraint is a format and not a list of phrases, use grammar-constrained decoding.
Pitfalls
- A cell that empties. With a small , the cell may hold nothing at the end, and the search returns no output even if one exists. Increase or , or fall back to the unconstrained output.
- Phrases in odd places. The grid forces the phrases in but does not ask where they fit best; the model may put a phrase at the end, or repeat it, which hurts fluency. Measure the quality and not only the coverage.
- Tokenization. Constraints are lists of tokens. Tokenize each phrase the way the model tokenizes text in context, because a subword tokenizer can split the same word differently at the start of a sentence and inside it.
- Length bias. Outputs in the top cell are longer than free outputs, and raw log probabilities prefer short outputs; compare finished outputs with length normalization.
Implementations
The code takes the log probabilities of the model as given, as a function of the prefix, and implements the grid search 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
# Part of https://algorithm.tamnd.com/grid-beam-search/. The authors are listed in prov/ZN2NZT.jsonl.
"""Grid beam search: beam search with phrases that the output must hold (Hokamp and Liu 2017).
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.
A constraint is a phrase: a non-empty list of tokens that must appear, as a
contiguous block, in the output. The phrases must take disjoint positions.
"""
from dataclasses import dataclass
from typing import Callable, Dict, List, Optional, Sequence, Tuple
from nlslog import NEG_INF
EOS = "</s>"
Model = Callable[[Tuple[str, ...]], Dict[str, float]]
@dataclass(frozen=True)
class Hyp:
"""A partial output. phrase is the index of the open constraint, or -1."""
tokens: Tuple[str, ...]
score: float
covered: Tuple[bool, ...]
phrase: int = -1
pos: int = 0
def grid_beam_search(
model: Model,
phrases: Sequence[Sequence[str]],
max_len: int,
width: int,
stats: Optional[Dict[str, int]] = None,
) -> Optional[Tuple[List[str], float]]:
"""Return (tokens, log p) of the best finished output that holds every phrase.
Grid[t][c] holds at most width hypotheses with t tokens, c of which are
constraint tokens. The output has at most max_len tokens, "</s>"
included. Return None if no output that holds every phrase is found.
If stats is a dict, stats["calls"] counts the model calls.
"""
if width < 1 or max_len < 1:
raise ValueError("width and max_len must be at least 1")
phrases = [list(p) for p in phrases]
if any(len(p) == 0 for p in phrases):
raise ValueError("a constraint must not be empty")
if any(EOS in p for p in phrases):
raise ValueError("a constraint must not contain the end token")
total = sum(len(p) for p in phrases)
m = len(phrases)
grid: List[List[Hyp]] = [[] for _ in range(total + 1)]
grid[0] = [Hyp((), 0.0, (False,) * m)] # @line L1
best: Optional[Tuple[List[str], float]] = None
calls = 0
for t in range(1, max_len + 1): # @line L2
nxt: List[List[Hyp]] = [[] for _ in range(total + 1)]
for c in range(total + 1): # @line L3
for h in grid[c]:
logp = model(h.tokens) # @line L4
calls += 1
if h.phrase < 0 and c == total and logp.get(EOS, NEG_INF) > NEG_INF: # @line L5
s = h.score + logp[EOS]
if best is None or s > best[1]:
best = (list(h.tokens) + [EOS], s)
if t == max_len:
continue
if h.phrase < 0:
for w, lp in logp.items(): # @line L6
if w != EOS and lp > NEG_INF:
nxt[c].append(Hyp(h.tokens + (w,), h.score + lp, h.covered))
for i, p in enumerate(phrases): # @line L7
if not h.covered[i] and logp.get(p[0], NEG_INF) > NEG_INF:
nxt[c + 1].append(_advance(h, i, 0, p, logp[p[0]]))
else:
p = phrases[h.phrase] # @line L8
w = p[h.pos]
if logp.get(w, NEG_INF) > NEG_INF:
nxt[c + 1].append(_advance(h, h.phrase, h.pos, p, logp[w]))
low = total - (max_len - 1 - t)
for c in range(total + 1): # @line L9
if c < low:
nxt[c] = []
else:
order = sorted(range(len(nxt[c])), key=lambda j: (-nxt[c][j].score, j))
nxt[c] = [nxt[c][j] for j in order[:width]]
grid = nxt
if stats is not None:
stats["calls"] = calls
return best # @line L10
def _advance(h: Hyp, i: int, pos: int, phrase: List[str], lp: float) -> Hyp:
"""Append token pos of phrase i to h, and close the phrase if it is complete."""
tokens = h.tokens + (phrase[pos],)
if pos + 1 == len(phrase):
covered = h.covered[:i] + (True,) + h.covered[i + 1 :]
return Hyp(tokens, h.score + lp, covered)
return Hyp(tokens, h.score + lp, h.covered, i, pos + 1)
nlslog.py 152 lines
# 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
test_grid_beam_search.py 140 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/grid-beam-search/. The authors are listed in prov/ZN2NZT.jsonl.
import math
import random
from grid_beam_search import EOS, grid_beam_search
from nlslog import NEG_INF, log_normalize, safe_log
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},
}
def m1(prefix):
probs = M1.get(tuple(prefix), {"a": 0.0, "b": 0.0, EOS: 1.0})
return {w: safe_log(p) for w, p in probs.items()}
def random_model(seed, vocab, n):
def model(prefix):
if len(prefix) >= n - 1:
return {w: (0.0 if w == EOS else NEG_INF) for w in vocab}
rng = random.Random(f"{seed}|{' '.join(prefix)}")
raw = [math.log(rng.random() ** 2 + 1e-3) for _ in vocab]
return dict(zip(vocab, log_normalize(raw)))
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((prefix + [w], s + lp))
elif len(prefix) + 1 < n:
rec(prefix + [w], s + lp)
rec([], 0.0)
return out
def holds(tokens, phrases):
"""True if the phrases fit at disjoint contiguous places of tokens (without "</s>")."""
body = tokens[:-1]
def place(i, used):
if i == len(phrases):
return True
p = phrases[i]
for s in range(len(body) - len(p) + 1):
span = set(range(s, s + len(p)))
if body[s : s + len(p)] == p and not (span & used) and place(i + 1, used | span):
return True
return False
return place(0, frozenset())
def best_constrained(model, phrases, n):
good = [(y, s) for y, s in exhaustive(model, n) if holds(y, phrases)]
return max(good, key=lambda t: t[1]) if good else None
def test_example() -> None:
stats = {}
y, s = grid_beam_search(m1, [["a"]], 3, 1, stats)
assert y == ["a", "a", EOS]
assert math.isclose(math.exp(s), 0.2)
assert stats["calls"] == 4
assert best_constrained(m1, [["a"]], 3)[0] == ["a", "a", EOS]
# Without the constraint the best output is b</s>.
assert max(exhaustive(m1, 3), key=lambda t: t[1])[0] == ["b", EOS]
y, s = grid_beam_search(m1, [["b"]], 3, 1)
assert y == ["b", EOS] and math.isclose(math.exp(s), 0.36)
def test_holds() -> None:
assert holds(["x", "a", "b", EOS], [["a", "b"]])
assert not holds(["a", "x", "b", EOS], [["a", "b"]])
assert not holds(["a", EOS], [["a"], ["a"]])
assert holds(["a", "a", EOS], [["a"], ["a"]])
assert holds(["a", "b", "a", EOS], [["b", "a"], ["a"]])
def test_wide_grid_is_exact() -> None:
vocab = ["a", "b", "c", EOS]
cases = [[["a"]], [["b", "c"]], [["a"], ["c"]], [["c", "a"], ["b"]], [["a"], ["a"]], []]
for seed in range(25):
model = random_model(seed, vocab, 5)
for phrases in cases:
got = grid_beam_search(model, phrases, 5, 10**6)
want = best_constrained(model, phrases, 5)
assert math.isclose(got[1], want[1])
assert holds(got[0], phrases)
def test_narrow_grid_can_fail() -> None:
vocab = ["a", "b", "c", EOS]
phrases = [["b", "c"]]
model = random_model(0, vocab, 5)
got = grid_beam_search(model, phrases, 5, 1)
want = best_constrained(model, phrases, 5)
assert got[0] == ["b", "c", EOS]
assert want[0] == ["a", "c", "b", "c", EOS]
assert got[1] < want[1] - 2.0
assert math.isclose(grid_beam_search(model, phrases, 5, 10**6)[1], want[1])
fails = 0
for seed in range(40):
model = random_model(seed, vocab, 5)
got = grid_beam_search(model, phrases, 5, 1)
want = best_constrained(model, phrases, 5)
assert holds(got[0], phrases) and got[1] <= want[1] + 1e-12
fails += got[1] < want[1] - 1e-12
assert 0 < fails < 40
def test_model_calls_are_at_most_n_k_c() -> None:
vocab = ["a", "b", "c", EOS]
for seed in range(20):
model = random_model(seed, vocab, 6)
for phrases in ([["a"]], [["a", "b"], ["c"]]):
total = sum(len(p) for p in phrases)
for width in (1, 2, 4):
stats = {}
grid_beam_search(model, phrases, 6, width, stats)
assert stats["calls"] <= 6 * width * (total + 1)
def test_no_room_for_the_constraints() -> None:
vocab = ["a", "b", EOS]
model = random_model(1, vocab, 3)
assert grid_beam_search(model, [["a", "b", "a"]], 3, 4) is None
assert best_constrained(model, [["a", "b", "a"]], 3) is None
History
Hokamp and Liu presented grid beam search at ACL 2017, for interactive post-editing and domain adaptation of neural encoder-decoder translation. Its cost grows with the number of constraint tokens, and Post and Vilar 2018 removed that growth with dynamic beam allocation.
References
- Chris Hokamp and Qun Liu, Lexically constrained decoding for sequence generation using grid beam search, ACL 2017, pages 1535 to 1546, Algorithm 1 (the grid), and Section 3.3 (the cost in model calls, linear in the number of constraint tokens)
- Matt Post and David Vilar, Fast lexically constrained decoding with dynamic beam allocation for neural machine translation, NAACL 2018, pages 1314 to 1324, the dynamic beam allocation that keeps one beam of fixed size and splits it among the counts of met constraints
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 ZN2NZT Edit this page History Report an error Markdown