Algorithm Search⌘K

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.

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
Properties
deterministicnot exactofflineiterative
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 cc constraint tokens may finish. The cost is c+1c + 1 beams in place of one, so the number of model calls grows linearly with cc. 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 log⁡p(w∣y)\log p(w \mid y) for every prefix yy and every token ww of the vocabulary VV, which contains </s>. All logs are natural logs. The constraints are mm phrases P1,…,PmP_1, \ldots, P_m, each a non-empty sequence of tokens without </s>, with c=∣P1∣+⋯+∣Pm∣c = |P_1| + \cdots + |P_m| tokens in all. An output yy of at most nn tokens, </s> included, holds the constraints if each phrase appears in yy as a contiguous block and the mm blocks take disjoint positions. The task is

y∗=arg⁡max⁡{log⁡p(y):y holds P1,…,Pm}.y^* = \arg\max \{ \log p(y) : y \text{ holds } P_1, \ldots, P_m \}.

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 Grid[c′]\text{Grid}[c'] at step tt holds the hypotheses of t−1t - 1 tokens of which c′c' are constraint tokens.

  1. GRID-BEAM-SEARCH(model, P_1 .. P_m, n, k)
  2. 1Grid[0] ← { empty prefix, score 0, nothing covered }; Grid[c'] ← ∅ for c' > 0; best ← none
  3. 2for t ← 1 to n do
  4. 3for c' ← 0 to c, for each hypothesis h in Grid[c'] do
  5. 4ℓ ← model(h.prefix) ▷ one call per hypothesis
  6. 5if h is closed and c' = c then best ← the better of best and h + "</s>"
  7. if t = n then continue ▷ no room for a token before "</s>"
  8. if h is closed then
  9. 6generate: for each w ≠ "</s>", put h + w with score + ℓ[w] into Next[c']
  10. 7start: for each phrase i not covered, put h + P_i[1] into Next[c' + 1]
  11. else
  12. 8continue: put h + the next token of its phrase into Next[c' + 1]
  13. 9for each c': empty Next[c'] if c' < c - (n - 1 - t), else keep its k best; Grid ← Next
  14. 10return best ▷ none if no output held every phrase

Line L9 drops cells that cannot reach cc 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 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. Without constraints the best output is b</s> (0.36). Require the phrase "a", so c=1c = 1, with n=3n = 3 and k=1k = 1.

  • Step 1. The empty prefix (call 1) generates a (−0.693-0.693) and b (−0.916-0.916) into cell 0, and starts the phrase with a (−0.693-0.693) 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 (−1.609-1.609) into cell 1. The constraint a (call 3) is closed in cell cc, so it finishes a</s> (log⁡0.15=−1.897\log 0.15 = -1.897); it also generates aa (−1.609-1.609) and ab (−1.897-1.897) into cell 1. Cell 0 can no longer reach cc 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> (log⁡0.2=−1.609\log 0.2 = -1.609), 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", n=5n = 5 and k=1k = 1, grid beam search returns b c </s> with log probability −5.020-5.020, but the best output that holds the phrase is a c b c </s>, with −2.745-2.745. A grid with an unbounded beam finds it. On 40 random models with k=1k = 1 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 cc finish and a hypothesis reaches cell cc only by placing every token of every phrase at disjoint positions. Line L9 drops only hypotheses that can no longer finish. With kk 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 nk(c+1)n k (c + 1).

With a finite kk 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 P1,…,PmP_1, \ldots, P_m are non-empty, contain no </s>, and have cc tokens in all. An output y=y1…yℓy = y_1 \ldots y_\ell ends with its only </s>, so its body is y1…yℓ−1y_1 \ldots y_{\ell - 1}. A placement of the phrases in yy is a choice of start positions s1,…,sms_1, \ldots, s_m such that ysi…ysi+∣Pi∣−1=Piy_{s_i} \ldots y_{s_i + |P_i| - 1} = P_i for each ii, and the mm blocks are disjoint subsets of the body. The output holds the phrases if it has a placement.

A hypothesis hh has a prefix h.yh.y, a score h.sh.s, a set h.Dh.D of covered phrases, and, if it is open, a phrase index h.ih.i and a position h.jh.j with 1≤h.j<∣Ph.i∣1 \le h.j < |P_{h.i}|. Write cnt(h)=∑i∈h.D∣Pi∣+h.j\mathrm{cnt}(h) = \sum_{i \in h.D} |P_i| + h.j for an open hh, and ∑i∈h.D∣Pi∣\sum_{i \in h.D} |P_i| for a closed one.

Lemma 1 (invariant of a hypothesis). Every hypothesis hh that the search builds satisfies: (a) h.s=log⁡p(h.y)h.s = \log p(h.y), the sum of the token log probabilities; (b) hh lies in the cell cnt(h)\mathrm{cnt}(h); (c) h.yh.y has disjoint blocks that hold each covered phrase in full and, if hh is open, the first h.jh.j tokens of Ph.iP_{h.i} at the end of h.yh.y, 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 ww to a closed hh, adds log⁡p(w∣h.y)\log p(w \mid h.y) and keeps the cell and the blocks. Line L7 appends the first token of an uncovered phrase PiP_i to a closed hh; 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 c′+1c' + 1. If ∣Pi∣=1|P_i| = 1 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 h.Dh.D and hh becomes closed. Line L9 only removes hypotheses. □\square

Theorem 2 (soundness). If the search returns (y,s)(y, s), then yy holds the phrases and s=log⁡p(y)s = \log p(y).

Proof. Line L5 finishes only a closed hypothesis hh in cell cc. By Lemma 1(b) and since hh is closed, ∑i∈h.D∣Pi∣=c\sum_{i \in h.D} |P_i| = c, so h.Dh.D holds all mm phrases, and by Lemma 1(c) their blocks are disjoint and lie in h.yh.y, the body of y=h.yy = h.y </s>. The score is h.s+log⁡p(</s>∣h.y)=log⁡p(y)h.s + \log p(\text{</s>} \mid h.y) = \log p(y) by Lemma 1(a). □\square

Lemma 3 (safe pruning of cells). A hypothesis of tt tokens with count c′<c−(n−1−t)c' < c - (n - 1 - t) has no extension to an output of at most nn tokens that the search can finish.

Proof. Each token adds at most 1 to the count, and a finished output of at most nn tokens has at most n−1−tn - 1 - t more tokens before its </s>. To finish, the count must reach cc (Theorem 2), so c′+(n−1−t)≥cc' + (n - 1 - t) \ge c is needed. □\square

Theorem 4 (exact with an unbounded beam). If kk is at least the number of hypotheses that are ever put into one cell at one step, the search returns an output y∗y^* that holds the phrases with the largest log⁡p(y∗)\log p(y^*) among all outputs of at most nn tokens, or none if there is no such output of positive probability.

Proof. With such a kk, line L9 removes only the cells of Lemma 3. Take an output yy of positive probability and at most nn tokens with a placement s1,…,sms_1, \ldots, s_m. Build its hypotheses token by token: at position uu of the body, if u=siu = s_i for some ii, use line L7 with phrase ii; if uu 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 cc, and line L5 at the next step finishes yy with its true score. None of these hypotheses is removed by Lemma 3, since each has a completion. So yy is a candidate for best, and line L5 keeps the largest score seen. By Theorem 2 every candidate holds the phrases. □\square

Theorem 5 (the call bound). The search makes at most nk(c+1)n k (c + 1) 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 c+1c + 1 cells holds at most kk hypotheses, and line L1 starts with one. There are nn steps. □\square

What is not claimed. With a finite kk, line L9 can remove the prefix of y∗y^*, and the search returns a worse output or none. The page gives a model (seed 0 in the test) where k=1k = 1 returns b c </s> with log probability −5.020-5.020, while y∗y^* = a c b c </s> has −2.745-2.745. The test also checks that an unbounded beam returns y∗y^* on that model, as Theorem 4 says.

Complexity

The grid has c+1c + 1 cells of at most kk hypotheses, so each step makes at most k(c+1)k (c + 1) model calls, and nn steps make at most nk(c+1)n k (c + 1), the O(ktc)O(k t c) of Hokamp and Liu (Section 3.3) with t=nt = n. A closed hypothesis produces at most ∣V∣+m|V| + m candidates and an open one produces one. Selecting the kk best of a cell takes linear time with top-k selection, so the time is O(nk(c+1)(M+∣V∣+m))O(n k (c + 1) (M + |V| + m)) for a call cost MM in the word RAM; the code sorts each cell, for clarity. The grid at one step holds O(k(c+1))O(k (c + 1)) hypotheses, each with a prefix of O(n)O(n) tokens.

The calls in one step are independent, so a GPU runs them in one batch of k(c+1)k (c + 1) 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 c+1c + 1, 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 nn 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 kk for all counts and divide its slots among the counts at each step. The cost no longer grows with cc.
  • 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 c+1c + 1 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 kk, the cell cc may hold nothing at the end, and the search returns no output even if one exists. Increase kk or nn, 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.

grid_beam_search.pyI0RawGitHub
# 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

  1. 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)
  2. 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.

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