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.
- Solves
- Machine translation
- 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
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 to a target sentence . Spans are fencepost: covers . A derivation is a sequence of steps whose source spans cover each source word once, where is a translation of in the phrase table. Its target is . This page uses a log-linear score with four features, all logs natural:
where is the log phrase score (already weighted), , weights the distortion (the jump from the end of the last phrase to the start of the next), is a word penalty, and the language model is a bigram model weighted by . An optional distortion limit forbids jumps with . 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 is an estimate of the best score for translating 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 over the maximal runs of uncovered words.
DECODE(f, model, k, θ, d) ▷ k: stack size, θ: threshold, d: distortion limit- 1
compute fc(s, t) for all spans - 2
stacks S_0 .. S_m; S_0 ← { (score 0, coverage ∅, last <s>, end 0) } - 3
for c ← 0 to m − 1 do - 4
prune S_c by score + future cost: keep those within θ of the best, then the best k - 5
for each hypothesis h in S_c do - 6
for each translation option (s, t, ē, tm) do - 7
if (s, t) overlaps the coverage of h or |s − end(h)| > d then continue - 8
h' ← h + (s, t, ē): add tm, the LM scores of ē after last(h), −δ |s − end(h)| and ω |ē| - 9
key ← (coverage(h'), last(h'), end(h')) - 10
in S_{c + t − s}: keep h' if key is new or h' is better than the hypothesis with this key - 11
for each h in S_m do - 12
total(h) ← score(h) + μ ln p(</s> | last(h)); keep the best - 13
follow 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 below the best in the stack, and histogram pruning keeps at most . Lines L9 and L10 do recombination. Line L12 adds the end of sentence term, which only complete hypotheses can have.
Example
Translate the German = morgen fliege ich into English. The phrase table has morgen to tomorrow with score , fliege to will fly () or fly (), ich to I (), and the two-word phrase fliege ich to I will fly (). The bigram language model has, in natural log, , , , , , a few other bigrams, and for every unseen bigram. The weights are , and , with no distortion limit.
Future cost. The table gives (tomorrow), , , , and .
Stack 1. Expanding the empty hypothesis gives tomorrow with score and score plus future cost ; I (from ich, a jump of 2) with score ; 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 first and then , and only 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
.
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 , because it pays for distortion and the phrase scores . The sentence has 14 derivations in all. The decoder with no pruning returns , the same as a search over all of them.
Without the phrase "fliege ich". The best derivation is then the reordering one, with score . 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 () or y (), b to z (), a distortion limit of 0, and the bigrams , , and . The best translation is "y z" with . With a stack size of 1, stack 1 keeps only x, because it looks better ( against , and both have the same future cost), and the decoder returns "x z" with . 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 , and the decoder translates it into a target sentence . Spans are fencepost: covers . A derivation is a sequence of phrase translations whose source spans are disjoint and cover , where each is a translation of in the phrase table and every jump (with ) is within the distortion limit, if there is one. Its score is
where , $e_0 = $ <s>, $e_{|e|+1} = $ </s>, and 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 of a sequence with disjoint spans and allowed jumps. Its state is the triple (coverage , last target word , end ), with $w = $ <s> and end for the empty prefix, and its partial score is the score above with the sums cut after step and without the final </s> term.
Lemma 1 (the rest of the score depends only on the state). Let be a partial derivation with state and let be a sequence of steps such that is a derivation. Then the score of is the partial score of plus a quantity that depends only on and . Whether is a derivation also depends only on and .
Proof. The terms of the steps of are , , the jump , and the bigrams inside and between the last word before it and its first word. For the first step of , the previous end and the previous word are the end and the word of . For later steps they are inside . The final term uses the last word of , which is the last word of , or the word of if is empty. Disjointness of from depends only on the coverage , and the distortion test of the first step only on the end.
Lemma 2 (invariant). For each , when the loop of line L3 reaches stack (and, for , at line L11), stack holds, for every state with that some partial derivation reaches, one hypothesis with state whose score is the largest partial score over all partial derivations that reach . It holds nothing else.
Proof. By induction on . Stack 0 holds the start hypothesis, the only state with , with score 0.
Let and let be a reachable state with . Take a partial derivation with the best partial score for , and let its last step be with . Its prefix has a state with . By Lemma 1 applied to partial scores (the same argument without the </s> term), the partial score of is the partial score of plus a term that depends only on and the last step. By induction, stack holds a hypothesis with state and score at least that of . When line L5 processes , line L6 tries the step . Line L7 accepts it, because it was allowed after and the test depends only on . Line L8 computes a score at least for a hypothesis with state , and puts it into stack under the key (line L9). Line L10 keeps the higher score for each key, so the hypothesis kept for has a score at least . 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 , hence at most . So it is exactly .
All the steps into stack come from stacks , and the loop of line L3 handles the stacks in increasing order. So all of them are done before stack is read.
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 .
Proof. A complete derivation is a partial derivation with plus the </s> term, which depends only on the last word (Lemma 1). Line L12 adds this term to each hypothesis of stack and line L11 keeps the best. By Lemma 2, stack 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 is empty and line L11 finds nothing.
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 while the best has . Recombination alone never loses the best derivation, by Lemma 1.
Cost. Without a distortion limit there are up to coverage sets, so the number of states, and the time, can be exponential in . With a stack size , each of the stacks expands at most hypotheses, each with at most translation options, so the time is 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 be the number of translation options of the sentence. With stack size , each of the stacks expands at most hypotheses, each with at most options, so there are expansions, each costing for phrases of bounded length. Sorting a stack for pruning costs for the hypotheses it received, and . The future cost table costs once. The space is dominated by the hypotheses created, . Decoders keep small by keeping only the best few translations of each source phrase.
Without pruning, the number of states can grow like 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 , the coverage sets that can occur are limited, and the number of states is linear in for fixed and vocabulary, though exponential in .
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 -gram language model with the state extended to the last words.
- Left to right output. The target is built in order, so the -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 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.
# 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
- Koehn 2004, the decoding algorithm with stacks by the number of foreign words translated, the future cost estimate, recombination and pruning
- 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)
- Koehn, Och and Marcu 2003, the phrase-based model and the beam search decoder used in its experiments
- 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.
| 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 7R5WTX Edit this page History Report an error Markdown