Algorithm Search⌘K

Algorithmcore

Stack decoding for phrase-based translation

Also called multi-stack beam decoding.

Beam search with one stack per number of covered source words, adding phrase translations to hypotheses with a future cost estimate.

Time
O(m k o log(k o)) worst
Space
O(m k o) extra
Where
k = the stack size; m = the source sentence length; o = the number of translation options of the sentence
Properties
deterministicnot exactofflineiterative
Origin
Philipp Koehn, 2004

Stack decoding for phrase-based translation is the beam search that the Pharaoh and Moses decoders use to find a high-scoring translation under a phrase-based model. It builds the translation from left to right, one phrase at a time, and each step may translate any untranslated part of the source, so the phrases can be reordered. Partial translations go into stacks by the number of source words they cover, and each stack is pruned by the score so far plus an estimate of the cost of the rest. The search is a heuristic: with pruning it can miss the best translation, and exact decoding with free reordering is NP-complete.

In plain words

The decoder writes the translation from left to right. At each step it picks a piece of the source sentence that it has not translated yet, anywhere in the sentence, and appends one translation of that piece. A partial translation remembers which source words it has used.

There are far too many partial translations to keep. So they are sorted into stacks: one stack for partial translations that used one source word, one for two words, and so on. Each stack keeps only its best few. To compare fairly a partial translation that did the easy words with one that did the hard words, the decoder adds a guess of what the remaining words will cost. Two partial translations that can continue in exactly the same ways are merged, and only the better one is kept.

The problem

Translation runs from the source f=f1…fmf = f_1 \ldots f_m to a target sentence ee. Spans are fencepost: (s,t)(s, t) covers fs+1…ftf_{s+1} \ldots f_t. A derivation is a sequence of steps (sk,tk,eˉk)(s_k, t_k, \bar e_k) whose source spans cover each source word once, where eˉk\bar e_k is a translation of fsk+1…ftkf_{s_k+1} \ldots f_{t_k} in the phrase table. Its target is e=eˉ1⋯eˉne = \bar e_1 \cdots \bar e_n. This page uses a log-linear score with four features, all logs natural:

score=∑k(tmk−δ ∣sk−tk−1∣+ω ∣eˉk∣)+μln⁡pLM(<s>  e  </s>),\mathrm{score} = \sum_k \bigl(\mathrm{tm}_k - \delta \, |s_k - t_{k-1}| + \omega \, |\bar e_k|\bigr) + \mu \ln p_{\mathrm{LM}}(\texttt{<s>} \; e \; \texttt{</s>}),

where tmk\mathrm{tm}_k is the log phrase score (already weighted), t0=0t_0 = 0, δ\delta weights the distortion (the jump from the end of the last phrase to the start of the next), ω\omega is a word penalty, and the language model is a bigram model weighted by μ\mu. An optional distortion limit dd forbids jumps with ∣sk−tk−1∣>d|s_k - t_{k-1}| > d. The goal is a derivation with the largest score. Real decoders use more features and a longer language model history; the search does not change.

The algorithm

A hypothesis stores its score, its coverage (the set of covered source words), its last target word, the end of its last source phrase, and a back pointer. Its state is the triple (coverage, last word, end). Two hypotheses with the same state have the same set of possible completions with the same added scores, so only the better one needs to be kept. This is recombination.

The future cost fc(s,t)\mathrm{fc}(s, t) is an estimate of the best score for translating fs+1…ftf_{s+1} \ldots f_t alone: the best monotone segmentation of the span into phrases, each scored by its translation score, word penalty and a language model estimate without context, and with no distortion. A dynamic program over spans, shorter spans first, computes it for all spans before the search. The future cost of a hypothesis is the sum of fc\mathrm{fc} over the maximal runs of uncovered words.

  1. DECODE(f, model, k, θ, d) ▷ k: stack size, θ: threshold, d: distortion limit
  2. 1compute fc(s, t) for all spans
  3. 2stacks S_0 .. S_m; S_0 ← { (score 0, coverage ∅, last <s>, end 0) }
  4. 3for c ← 0 to m − 1 do
  5. 4prune S_c by score + future cost: keep those within θ of the best, then the best k
  6. 5for each hypothesis h in S_c do
  7. 6for each translation option (s, t, ē, tm) do
  8. 7if (s, t) overlaps the coverage of h or |s − end(h)| > d then continue
  9. 8h' ← h + (s, t, ē): add tm, the LM scores of ē after last(h), −δ |s − end(h)| and ω |ē|
  10. 9key ← (coverage(h'), last(h'), end(h'))
  11. 10in S_{c + t − s}: keep h' if key is new or h' is better than the hypothesis with this key
  12. 11for each h in S_m do
  13. 12total(h) ← score(h) + μ ln p(</s> | last(h)); keep the best
  14. 13follow the back pointers from the best h to get the steps

Line L4 does both kinds of pruning of Pharaoh: threshold pruning drops hypotheses whose score plus future cost is more than θ\theta below the best in the stack, and histogram pruning keeps at most kk. Lines L9 and L10 do recombination. Line L12 adds the end of sentence term, which only complete hypotheses can have.

Example

Translate the German ff = morgen fliege ich into English. The phrase table has morgen to tomorrow with score −0.2-0.2, fliege to will fly (−0.7-0.7) or fly (−0.9-0.9), ich to I (−0.1-0.1), and the two-word phrase fliege ich to I will fly (−1.5-1.5). The bigram language model has, in natural log, ln⁡p(tomorrow∣<s>)=−1.0\ln p(\text{tomorrow} \mid \texttt{<s>}) = -1.0, ln⁡p(I∣tomorrow)=−1.2\ln p(\text{I} \mid \text{tomorrow}) = -1.2, ln⁡p(will∣I)=−0.6\ln p(\text{will} \mid \text{I}) = -0.6, ln⁡p(fly∣will)=−0.4\ln p(\text{fly} \mid \text{will}) = -0.4, ln⁡p(</s>∣fly)=−0.5\ln p(\texttt{</s>} \mid \text{fly}) = -0.5, a few other bigrams, and −6-6 for every unseen bigram. The weights are μ=1\mu = 1, δ=0.5\delta = 0.5 and ω=0\omega = 0, with no distortion limit.

Future cost. The table gives fc(0,1)=−1.2\mathrm{fc}(0,1) = -1.2 (tomorrow), fc(0,2)=−2.5\mathrm{fc}(0,2) = -2.5, fc(0,3)=−3.8\mathrm{fc}(0,3) = -3.8, fc(1,2)=−1.3\mathrm{fc}(1,2) = -1.3, fc(1,3)=−2.6\mathrm{fc}(1,3) = -2.6 and fc(2,3)=−1.3\mathrm{fc}(2,3) = -1.3.

Stack 1. Expanding the empty hypothesis gives tomorrow with score −1.2-1.2 and score plus future cost −1.2−2.6=−3.8-1.2 - 2.6 = -3.8; I (from ich, a jump of 2) with score −7.1-7.1; and two hypotheses from fliege. When "fly" is reached twice with the same state, recombination keeps the better one: the state (fliege covered, last word fly, end 2) gets −7.6-7.6 first and then −7.4-7.4, and only −7.4-7.4 stays.

Stack 3. The full hypotheses are compared with the end of sentence term. "Tomorrow I will fly", made of tomorrow and then the two-word phrase, gets

−0.2−1.5+(−1.0−1.2−0.6−0.4−0.5)=−5.4-0.2 - 1.5 + (-1.0 - 1.2 - 0.6 - 0.4 - 0.5) = -5.4.

The best translation that uses only one-word phrases is the same string with the steps tomorrow, I (a jump forward of 1), will fly (a jump back of 2), and gets −6.2-6.2, because it pays 0.5+1.00.5 + 1.0 for distortion and the phrase scores −0.2−0.1−0.7-0.2 - 0.1 - 0.7. The sentence has 14 derivations in all. The decoder with no pruning returns −5.4-5.4, the same as a search over all of them.

Without the phrase "fliege ich". The best derivation is then the reordering one, with score −6.2-6.2. With a distortion limit of 1, the jump back of 2 is forbidden, and the decoder returns "tomorrow will fly I".

A pruning error. Take the source "a b" with a to x (−0.1-0.1) or y (−1.0-1.0), b to z (00), a distortion limit of 0, and the bigrams ln⁡p(x∣<s>)=ln⁡p(y∣<s>)=−1\ln p(x \mid \texttt{<s>}) = \ln p(y \mid \texttt{<s>}) = -1, ln⁡p(z∣x)=−5\ln p(z \mid x) = -5, ln⁡p(z∣y)=−0.1\ln p(z \mid y) = -0.1 and ln⁡p(</s>∣z)=0\ln p(\texttt{</s>} \mid z) = 0. The best translation is "y z" with −2.1-2.1. With a stack size of 1, stack 1 keeps only x, because it looks better (−1.1-1.1 against −2.0-2.0, and both have the same future cost), and the decoder returns "x z" with −6.1-6.1. A threshold of 0.5 makes the same error.

Correctness

Without pruning, the decoder returns a derivation with the largest score; this is a theorem, proved in the proofs file. The proof rests on two facts. First, the score that a completion adds depends only on the state of the hypothesis, because the language model is a bigram model and the distortion depends only on the end of the last phrase; so recombination never loses the best derivation. Second, every step goes from a stack with fewer covered words to one with more, so the stacks can be processed in order. With pruning, the decoder is a heuristic: line L4 can drop the hypothesis that the best derivation passes through, as in the example. The test file compares the decoder with an exhaustive search over all segmentations, all orders and all options, for random models and sentences of up to 4 words.

Proof: Without pruning, multi-stack decoding with recombination returns a best derivationfull

The source is f=f1…fmf = f_1 \ldots f_m, and the decoder translates it into a target sentence ee. Spans are fencepost: (s,t)(s, t) covers fs+1…ftf_{s+1} \ldots f_t. A derivation is a sequence of phrase translations (s1,t1,eˉ1),…,(sn,tn,eˉn)(s_1, t_1, \bar e_1), \ldots, (s_n, t_n, \bar e_n) whose source spans are disjoint and cover 1,…,m1, \ldots, m, where each eˉk\bar e_k is a translation of fsk+1…ftkf_{s_k + 1} \ldots f_{t_k} in the phrase table and every jump ∣sk−tk−1∣|s_k - t_{k-1}| (with t0=0t_0 = 0) is within the distortion limit, if there is one. Its score is

∑k(tmk−δ ∣sk−tk−1∣+ω ∣eˉk∣)+μ∑x=1∣e∣+1ln⁡p(ex∣ex−1),\sum_k \Bigl(\mathrm{tm}_k - \delta \, |s_k - t_{k-1}| + \omega \, |\bar e_k|\Bigr) + \mu \sum_{x=1}^{|e|+1} \ln p(e_x \mid e_{x-1}),

where e=eˉ1⋯eˉne = \bar e_1 \cdots \bar e_n, $e_0 = $ <s>, $e_{|e|+1} = $ </s>, and δ,ω,μ\delta, \omega, \mu are the weights. Logs are natural. The claim is about DECODE with no histogram limit and no threshold, so line L4 keeps every hypothesis.

A partial derivation is a prefix (s1,t1,eˉ1),…,(sr,tr,eˉr)(s_1, t_1, \bar e_1), \ldots, (s_r, t_r, \bar e_r) of a sequence with disjoint spans and allowed jumps. Its state is the triple (coverage CC, last target word ww, end trt_r), with $w = $ <s> and end 00 for the empty prefix, and its partial score is the score above with the sums cut after step rr and without the final </s> term.

Lemma 1 (the rest of the score depends only on the state). Let dd be a partial derivation with state σ\sigma and let xx be a sequence of steps such that dxd x is a derivation. Then the score of dxd x is the partial score of dd plus a quantity g(σ,x)g(\sigma, x) that depends only on σ\sigma and xx. Whether dxd x is a derivation also depends only on σ\sigma and xx.

Proof. The terms of the steps of xx are tm\mathrm{tm}, ω∣eˉ∣\omega |\bar e|, the jump ∣s−tprev∣|s - t_{\mathrm{prev}}|, and the bigrams inside eˉ\bar e and between the last word before it and its first word. For the first step of xx, the previous end and the previous word are the end and the word of σ\sigma. For later steps they are inside xx. The final term ln⁡p(</s>∣⋅)\ln p(\texttt{</s>} \mid \cdot) uses the last word of dxd x, which is the last word of xx, or the word of σ\sigma if xx is empty. Disjointness of xx from dd depends only on the coverage CC, and the distortion test of the first step only on the end. □\square

Lemma 2 (invariant). For each c=0,…,mc = 0, \ldots, m, when the loop of line L3 reaches stack cc (and, for c=mc = m, at line L11), stack cc holds, for every state σ\sigma with ∣C∣=c|C| = c that some partial derivation reaches, one hypothesis with state σ\sigma whose score is the largest partial score over all partial derivations that reach σ\sigma. It holds nothing else.

Proof. By induction on cc. Stack 0 holds the start hypothesis, the only state with ∣C∣=0|C| = 0, with score 0.

Let c≥1c \ge 1 and let σ\sigma be a reachable state with ∣C∣=c|C| = c. Take a partial derivation dd with the best partial score S∗S^* for σ\sigma, and let its last step be (s,t,eˉ)(s, t, \bar e) with t−s=qt - s = q. Its prefix d′d' has a state σ′\sigma' with ∣C′∣=c−q<c|C'| = c - q < c. By Lemma 1 applied to partial scores (the same argument without the </s> term), the partial score of dd is the partial score of d′d' plus a term that depends only on σ′\sigma' and the last step. By induction, stack c−qc - q holds a hypothesis h′h' with state σ′\sigma' and score at least that of d′d'. When line L5 processes h′h', line L6 tries the step (s,t,eˉ)(s, t, \bar e). Line L7 accepts it, because it was allowed after d′d' and the test depends only on σ′\sigma'. Line L8 computes a score at least S∗S^* for a hypothesis with state σ\sigma, and puts it into stack cc under the key σ\sigma (line L9). Line L10 keeps the higher score for each key, so the hypothesis kept for σ\sigma has a score at least S∗S^*. Every hypothesis in the stack is built from a hypothesis that corresponds to a partial derivation, by one allowed step, so its score is the partial score of a real partial derivation reaching σ\sigma, hence at most S∗S^*. So it is exactly S∗S^*.

All the steps into stack cc come from stacks c′<cc' < c, and the loop of line L3 handles the stacks in increasing order. So all of them are done before stack cc is read. □\square

Theorem. If some derivation exists, DECODE with no pruning returns the largest derivation score, and the derivation it traces back at line L13 has this score. If none exists, it returns −∞-\infty.

Proof. A complete derivation is a partial derivation with ∣C∣=m|C| = m plus the </s> term, which depends only on the last word (Lemma 1). Line L12 adds this term to each hypothesis of stack mm and line L11 keeps the best. By Lemma 2, stack mm holds the best partial score of every reachable full state, so the maximum over it is the maximum over all derivations. The back pointers of a hypothesis lead through the hypotheses it was built from, so the traced steps form a derivation whose score is the stored score. If no derivation exists, stack mm is empty and line L11 finds nothing. □\square

With pruning. Line L4 may drop the hypothesis that the best derivation passes through, because it ranks by score plus a future cost estimate that leaves out distortion and the language model context. Then the theorem fails. The test file has a two-word case in which a stack size of 1 returns a derivation with score −6.1-6.1 while the best has −2.1-2.1. Recombination alone never loses the best derivation, by Lemma 1.

Cost. Without a distortion limit there are up to 2m2^m coverage sets, so the number of states, and the time, can be exponential in mm. With a stack size kk, each of the mm stacks expands at most kk hypotheses, each with at most ∣O∣|O| translation options, so the time is O(mk∣O∣)O(m k |O|) for the expansions, plus the cost of ranking each stack.

Complexity

Count in the word RAM model, with each language model lookup as one step. Let oo be the number of translation options of the sentence. With stack size kk, each of the mm stacks expands at most kk hypotheses, each with at most oo options, so there are O(mko)O(m k o) expansions, each costing O(1)O(1) for phrases of bounded length. Sorting a stack for pruning costs O(Nlog⁡N)O(N \log N) for the NN hypotheses it received, and N≤koN \le k o. The future cost table costs O(m3+o)O(m^3 + o) once. The space is dominated by the hypotheses created, O(mko)O(m k o). Decoders keep oo small by keeping only the best few translations of each source phrase.

Without pruning, the number of states can grow like 2m2^m times the number of target words, so the search is exponential. This is unavoidable in the worst case unless P = NP: finding the best translation with free reordering is NP-hard, and its decision version is NP-complete (Knight 1999, for a word-based model with a bigram language model, by a reduction from the Hamilton circuit problem, a special case of the traveling salesman problem). With a distortion limit dd, the coverage sets that can occur are limited, and the number of states is linear in mm for fixed dd and vocabulary, though exponential in dd.

Properties

  • Not exact. Pruning makes it a heuristic, as for every beam search; the narrow-beam example above is a search error.
  • Exact without pruning. With an unlimited stack size and threshold, it is a complete dynamic program over states, but exponential.
  • Recombination is safe. It never loses the best derivation, for an nn-gram language model with the state extended to the last n−1n - 1 words.
  • Left to right output. The target is built in order, so the nn-gram language model can be scored at once, while the source is covered in any order.
  • Fair comparison by coverage size. Hypotheses in one stack cover the same number of source words, so their scores are comparable, and the future cost corrects for which words were covered.

Variants and improvements

  • Coverage stacks. Some decoders put hypotheses with the same coverage set into one stack, or group them by coverage inside a stack, to keep diversity.
  • Cube pruning. Moses also offers cube pruning for phrase-based search: hypotheses and translation options are sorted, and only the most promising combinations are scored.
  • A-star search. With an admissible future cost (one that never underestimates the best completion), A* search finds the exact best; the future cost of Pharaoh is not admissible, because it ignores distortion and the language model context.
  • Exact decoding. Integer linear programming and Lagrangian relaxation give exact results on many sentences at a higher cost.
  • Lattice and n-best output. Keeping the recombined hypotheses as back links gives a word lattice of the search space, from which n-best lists for minimum error rate training are taken.
  • Stack decoding for speech. The older stack decoding of speech recognition keeps one priority queue; the multi-stack version here avoids comparing hypotheses of different coverage.

When to use it

Use it to decode a phrase-based model, with a stack size in the hundreds, a distortion limit of about 6 words (the Moses default) for languages with similar word order, and a threshold that drops hypotheses far below the best. Raise the stack size if the model score of the output improves with it: then the search makes errors. For models built on a synchronous grammar, such as Hiero, use chart decoding with cube pruning instead.

Pitfalls

  • Pruning without future cost. If line L4 ranks by the score alone, hypotheses that took the easy words first win, and the hard words are left for later with no good options.
  • Recombination on too small a state. With a trigram model, the state must hold the last two target words; with a distortion feature, it must hold the end of the last phrase. A smaller key merges hypotheses with different futures and can lose the best one.
  • Forgetting the end of sentence. Add ln⁡p(</s>∣⋅)\ln p(\texttt{</s>} \mid \cdot) to complete hypotheses before choosing the best, as in line L12.
  • Distortion in the future cost. Pharaoh's future cost leaves distortion out. If a variant adds an estimate of it, the estimate must be the same for hypotheses that are compared, or the ranking is unfair.
  • Gaps that cannot be filled. With a distortion limit, a hypothesis can leave a gap that it can never reach again. Such hypotheses waste stack space, so a decoder should test, before it adds a hypothesis, that the first gap can still be reached.

Implementations

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.

phrase_based_stack_decoding.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/phrase-based-stack-decoding/. The authors are listed in prov/7R5WTX.jsonl.

"""Multi-stack beam decoding for a phrase-based translation model (Koehn 2004).

The source f has m words. A span (s, t) is fencepost: it covers f[s + 1 .. t]
(f[s:t] in Python). The model scores a derivation, a sequence of phrase
translations (s_k, t_k, target_k) that covers every source word once, by

    sum_k tm(f[s_k:t_k] -> target_k)
    + lm_weight * log p_lm(<s> e </s>)            (a bigram model, natural log)
    - distortion_weight * sum_k |s_k - t_{k-1}|    (t_0 = 0)
    + word_penalty * |e|

where e is the concatenation of the targets. Stack c holds the hypotheses that
cover c source words. A hypothesis is recombined with another one that has the
same coverage, the same last target word and the same end of its last phrase.
Each stack is pruned to the best `stack_size` hypotheses and to those within
`threshold` of the best, ranked by score plus future cost. With no pruning the
decoder returns a best derivation of the model (see the correctness proof).
"""

import itertools
import math
from dataclasses import dataclass
from typing import Optional

Phrase = tuple[str, ...]
PhraseTable = dict[Phrase, list[tuple[Phrase, float]]]
NEG_INF = float("-inf")


class BigramLM:
    """A bigram language model in natural log. Unseen bigrams get `floor`."""

    def __init__(self, logprobs: dict[tuple[str, str], float], floor: float = -10.0) -> None:
        self.logprobs = dict(logprobs)
        self.floor = floor
        best: dict[str, float] = {}
        for (_, w), lp in self.logprobs.items():
            best[w] = max(best.get(w, floor), lp)
        self._best_first = best

    def logprob(self, prev: str, w: str) -> float:
        return self.logprobs.get((prev, w), self.floor)

    def estimate(self, phrase: Phrase) -> float:
        """LM estimate of a phrase out of context: the first word gets its best
        score over all histories, the others their bigram score inside the phrase."""
        if not phrase:
            return 0.0
        total = self._best_first.get(phrase[0], self.floor)
        for a, b in zip(phrase, phrase[1:]):
            total += self.logprob(a, b)
        return total


@dataclass
class Model:
    table: PhraseTable
    lm: BigramLM
    lm_weight: float = 1.0
    distortion_weight: float = 0.5
    word_penalty: float = 0.0
    max_phrase_len: int = 7
    distortion_limit: Optional[int] = None  # None means unrestricted reordering


@dataclass
class Hyp:
    score: float
    coverage: int  # bit s is set when f[s] (0-based) is covered
    last: str  # last target word, "<s>" at the start
    end: int  # end t of the last source phrase, 0 at the start
    back: Optional["Hyp"]
    step: Optional[tuple[int, int, Phrase]]


def translation_options(f: list[str], model: Model) -> list[tuple[int, int, Phrase, float]]:
    """Every (s, t, target, tm score) whose source phrase f[s:t] is in the table."""
    m = len(f)
    opts = []
    for s in range(m):
        for t in range(s + 1, min(m, s + model.max_phrase_len) + 1):
            for target, tm in model.table.get(tuple(f[s:t]), []):
                opts.append((s, t, target, tm))
    return opts


def future_cost_table(f: list[str], model: Model) -> list[list[float]]:
    """fc[s][t]: the best estimated score of translating f[s:t] alone, in any
    monotone segmentation, without distortion. -inf if no segmentation exists."""
    m = len(f)
    fc = [[NEG_INF] * (m + 1) for _ in range(m + 1)]
    for s, t, target, tm in translation_options(f, model):
        est = tm + model.lm_weight * model.lm.estimate(target) + model.word_penalty * len(target)
        fc[s][t] = max(fc[s][t], est)
    for length in range(2, m + 1):
        for s in range(0, m - length + 1):
            t = s + length
            for k in range(s + 1, t):
                fc[s][t] = max(fc[s][t], fc[s][k] + fc[k][t])
    return fc


def future_cost(coverage: int, m: int, fc: list[list[float]]) -> float:
    """Sum of fc over the maximal runs of uncovered source words."""
    total, s = 0.0, 0
    while s < m:
        if coverage >> s & 1:
            s += 1
            continue
        t = s
        while t < m and not coverage >> t & 1:
            t += 1
        total += fc[s][t]
        s = t
    return total


def _jump_ok(model: Model, s: int, end: int) -> bool:
    return model.distortion_limit is None or abs(s - end) <= model.distortion_limit


def decode(
    f: list[str],
    model: Model,
    stack_size: Optional[int] = None,
    threshold: float = math.inf,
    recombine: bool = True,
) -> tuple[float, Phrase, list[tuple[int, int, Phrase]]]:
    """Return (score, target words, derivation) of the best complete hypothesis
    found; (-inf, (), []) if no hypothesis covers the whole source."""
    m = len(f)
    full = (1 << m) - 1
    opts = translation_options(f, model)
    fc = future_cost_table(f, model)  # @line L1
    stacks: list[dict] = [dict() for _ in range(m + 1)]  # @line L2
    start = Hyp(0.0, 0, "<s>", 0, None, None)
    stacks[0][(0, "<s>", 0)] = start
    for c in range(m):  # @line L3
        hyps = _prune(list(stacks[c].values()), m, fc, stack_size, threshold)  # @line L4
        for h in hyps:  # @line L5
            for s, t, target, tm in opts:  # @line L6
                span_mask = ((1 << (t - s)) - 1) << s
                if h.coverage & span_mask or not _jump_ok(model, s, h.end):  # @line L7
                    continue
                lm = 0.0  # @line L8
                prev = h.last
                for w in target:
                    lm += model.lm.logprob(prev, w)
                    prev = w
                score = (
                    h.score
                    + tm
                    + model.lm_weight * lm
                    - model.distortion_weight * abs(s - h.end)
                    + model.word_penalty * len(target)
                )
                cov = h.coverage | span_mask
                new = Hyp(score, cov, prev, t, h, (s, t, target))
                key = (cov, prev, t) if recombine else (cov, prev, t, id(new))  # @line L9
                stack = stacks[c + t - s]
                old = stack.get(key)
                if old is None or new.score > old.score:  # @line L10
                    stack[key] = new
    best, best_total = None, NEG_INF  # @line L11
    for h in stacks[m].values():
        total = h.score + model.lm_weight * model.lm.logprob(h.last, "</s>")  # @line L12
        if total > best_total:
            best, best_total = h, total
    if best is None:
        return NEG_INF, (), []
    steps = []  # @line L13
    node: Optional[Hyp] = best
    while node is not None and node.step is not None:
        steps.append(node.step)
        node = node.back
    steps.reverse()
    words = tuple(w for _, _, target in steps for w in target)
    assert best.coverage == full
    return best_total, words, steps


def _prune(hyps: list[Hyp], m: int, fc, stack_size: Optional[int], threshold: float) -> list[Hyp]:
    """Histogram and threshold pruning by score plus future cost."""
    ranked = sorted(hyps, key=lambda h: h.score + future_cost(h.coverage, m, fc), reverse=True)
    if not ranked:
        return []
    top = ranked[0].score + future_cost(ranked[0].coverage, m, fc)
    kept = [h for h in ranked if h.score + future_cost(h.coverage, m, fc) >= top - threshold]
    return kept if stack_size is None else kept[:stack_size]


def score_derivation(f: list[str], model: Model, steps: list[tuple[int, int, Phrase]]) -> float:
    """The model score of a complete derivation, computed from scratch."""
    m = len(f)
    covered = [False] * m
    total, end, words = 0.0, 0, []
    for s, t, target in steps:
        if any(covered[s:t]) or not _jump_ok(model, s, end):
            return NEG_INF
        tms = [tm for tgt, tm in model.table.get(tuple(f[s:t]), []) if tgt == target]
        if not tms:
            return NEG_INF
        total += max(tms) - model.distortion_weight * abs(s - end)
        for k in range(s, t):
            covered[k] = True
        end = t
        words.extend(target)
    if not all(covered):
        return NEG_INF
    seq = ["<s>"] + words + ["</s>"]
    lm = sum(model.lm.logprob(a, b) for a, b in zip(seq, seq[1:]))
    return total + model.lm_weight * lm + model.word_penalty * len(words)


def exhaustive(f: list[str], model: Model) -> tuple[float, Phrase]:
    """Best score over every segmentation, every order of the phrases and every
    translation option. Exponential: only for sentences of a few words."""
    m = len(f)
    best, best_words = NEG_INF, ()
    for cuts in itertools.product([False, True], repeat=max(m - 1, 0)):
        bounds = [0] + [k + 1 for k, c in enumerate(cuts) if c] + [m]
        spans = list(zip(bounds, bounds[1:]))
        if any(t - s > model.max_phrase_len for s, t in spans):
            continue
        for order in itertools.permutations(spans):
            choices = [model.table.get(tuple(f[s:t]), []) for s, t in order]
            for pick in itertools.product(*choices):
                steps = [(s, t, tgt) for (s, t), (tgt, _) in zip(order, pick)]
                sc = score_derivation(f, model, steps)
                if sc > best:
                    best = sc
                    best_words = tuple(w for _, _, tgt in steps for w in tgt)
    return best, best_words
test_phrase_based_stack_decoding.py 150 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/phrase-based-stack-decoding/. The authors are listed in prov/7R5WTX.jsonl.

import itertools
import math
import random

from phrase_based_stack_decoding import (
    BigramLM,
    Model,
    decode,
    exhaustive,
    future_cost_table,
    score_derivation,
)


def example_model() -> Model:
    table = {
        ("morgen",): [(("tomorrow",), -0.2)],
        ("fliege",): [(("will", "fly"), -0.7), (("fly",), -0.9)],
        ("ich",): [(("I",), -0.1)],
        ("fliege", "ich"): [(("I", "will", "fly"), -1.5)],
    }
    lm = BigramLM(
        {
            ("<s>", "tomorrow"): -1.0,
            ("tomorrow", "I"): -1.2,
            ("I", "will"): -0.6,
            ("will", "fly"): -0.4,
            ("fly", "</s>"): -0.5,
            ("tomorrow", "will"): -2.5,
            ("fly", "I"): -3.0,
            ("I", "</s>"): -1.5,
            ("I", "fly"): -1.0,
            ("tomorrow", "fly"): -3.0,
        },
        floor=-6.0,
    )
    return Model(table, lm, lm_weight=1.0, distortion_weight=0.5)


def test_example() -> None:
    f = "morgen fliege ich".split()
    model = example_model()
    score, words, steps = decode(f, model)
    assert words == ("tomorrow", "I", "will", "fly")
    assert math.isclose(score, -5.4, abs_tol=1e-9)
    assert steps == [(0, 1, ("tomorrow",)), (1, 3, ("I", "will", "fly"))]
    assert math.isclose(exhaustive(f, model)[0], score, abs_tol=1e-9)
    fc = future_cost_table(f, model)
    assert [round(x, 9) for x in fc[0][1:]] == [-1.2, -2.5, -3.8]
    # without the two-word phrase the best derivation reorders
    model.table.pop(("fliege", "ich"))
    score, words, steps = decode(f, model)
    assert words == ("tomorrow", "I", "will", "fly")
    assert steps == [(0, 1, ("tomorrow",)), (2, 3, ("I",)), (1, 2, ("will", "fly"))]
    assert math.isclose(score, -6.2, abs_tol=1e-9)
    # a distortion limit of 1 forbids the jump back from 3 to 1
    model.distortion_limit = 1
    assert decode(f, model)[1] == ("tomorrow", "will", "fly", "I")


def test_narrow_beam_fails() -> None:
    table = {("a",): [(("x",), -0.1), (("y",), -1.0)], ("b",): [(("z",), 0.0)]}
    lm = BigramLM(
        {("<s>", "x"): -1.0, ("<s>", "y"): -1.0, ("x", "z"): -5.0, ("y", "z"): -0.1, ("z", "</s>"): 0.0},
        floor=-20.0,
    )
    model = Model(table, lm, distortion_weight=1.0, distortion_limit=0)
    best = exhaustive(["a", "b"], model)
    assert best[1] == ("y", "z") and math.isclose(best[0], -2.1, abs_tol=1e-9)
    assert math.isclose(decode(["a", "b"], model)[0], -2.1, abs_tol=1e-9)
    narrow = decode(["a", "b"], model, stack_size=1)
    assert narrow[1] == ("x", "z") and math.isclose(narrow[0], -6.1, abs_tol=1e-9)
    tight = decode(["a", "b"], model, threshold=0.5)
    assert tight[1] == ("x", "z")


def random_model(rng: random.Random, m: int) -> tuple[list[str], Model]:
    f = [f"s{k}" for k in range(m)]
    vocab = ["p", "q", "r", "t"]
    table = {}
    for s in range(m):
        for t in range(s + 1, min(m, s + 3) + 1):
            if t - s > 1 and rng.random() < 0.5:
                continue
            opts = []
            for _ in range(rng.randint(1, 2)):
                target = tuple(rng.choice(vocab) for _ in range(rng.randint(1, 2)))
                opts.append((target, -rng.uniform(0.0, 3.0)))
            table[tuple(f[s:t])] = opts
    lp = {}
    for a in ["<s>"] + vocab:
        for b in vocab + ["</s>"]:
            lp[(a, b)] = -rng.uniform(0.1, 4.0)
    model = Model(table, BigramLM(lp), lm_weight=rng.uniform(0.5, 1.5), distortion_weight=rng.uniform(0.0, 1.5), word_penalty=rng.uniform(-0.5, 0.5))
    return f, model


def test_wide_beam_equals_exhaustive() -> None:
    rng = random.Random(2004)
    for _ in range(120):
        m = rng.randint(1, 4)
        f, model = random_model(rng, m)
        model.distortion_limit = rng.choice([None, None, 0, 1, 2])
        exact, _ = exhaustive(f, model)
        score, words, steps = decode(f, model)
        if exact == -math.inf:
            assert score == -math.inf
            continue
        assert math.isclose(score, exact, abs_tol=1e-9)
        assert math.isclose(score_derivation(f, model, steps), score, abs_tol=1e-9)
        no_recomb = decode(f, model, recombine=False)[0]
        assert math.isclose(no_recomb, exact, abs_tol=1e-9)
        for k in (1, 2):
            assert decode(f, model, stack_size=k)[0] <= exact + 1e-9


def test_future_cost_is_best_monotone_segmentation() -> None:
    rng = random.Random(11)
    for _ in range(40):
        m = rng.randint(1, 5)
        f, model = random_model(rng, m)
        fc = future_cost_table(f, model)
        for s in range(m):
            for t in range(s + 1, m + 1):
                best = -math.inf
                for cuts in itertools.product([False, True], repeat=t - s - 1):
                    bounds = [s] + [s + k + 1 for k, c in enumerate(cuts) if c] + [t]
                    total = 0.0
                    for a, b in zip(bounds, bounds[1:]):
                        opts = model.table.get(tuple(f[a:b]), [])
                        if not opts:
                            total = -math.inf
                            break
                        total += max(tm + model.lm_weight * model.lm.estimate(tg) + model.word_penalty * len(tg) for tg, tm in opts)
                    best = max(best, total)
                assert math.isclose(fc[s][t], best, abs_tol=1e-9) or fc[s][t] == best == -math.inf


def test_narrow_beam_failure_is_common() -> None:
    rng = random.Random(5)
    fails = 0
    for _ in range(60):
        f, model = random_model(rng, 4)
        exact = exhaustive(f, model)[0]
        if decode(f, model, stack_size=1)[0] < exact - 1e-9:
            fails += 1
    assert fails > 0

History

Stack decoding came from speech recognition, and the early word-based translation decoders adapted it. Koehn (2004) described the multi-stack beam search of the Pharaoh decoder, with stacks by the number of translated source words, a future cost estimate from the best phrase segmentation of each span, recombination, and histogram and threshold pruning. Knight (1999) had shown that exact decoding is NP-complete when the words can be reordered freely. Moses (Koehn et al. 2007) became the open-source successor of Pharaoh and kept the same search, with cube pruning added later.

References

  1. Koehn 2004, the decoding algorithm with stacks by the number of foreign words translated, the future cost estimate, recombination and pruning
  2. Knight 1999, Section 4.1 (decoding IBM Model 1 with a bigram language model is NP-complete, by a reduction from the Hamilton circuit problem, and its relation to the traveling salesman problem)
  3. Koehn, Och and Marcu 2003, the phrase-based model and the beam search decoder used in its experiments
  4. Philipp Koehn, Statistical Machine Translation, Cambridge University Press, 2010, Chapter 6 (decoding: translation options, hypothesis expansion, recombination, stack decoding, future cost)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example