Statistical Machine Translation Foundations
Learn how noisy-channel IBM word alignment, EM training, phrase extraction, log-linear scoring, and beam decoding build a statistical machine translation system.
Language AI HandbookAll chapters Statistical Machine Translation Foundations
Machine translation maps a sentence in a source language to a sentence in a target language. This chapter follows two stages of statistical machine translation: IBM's word-based models and the later phrase-based systems. In a phrase-based system, a word aligner supplies links for extracting phrase pairs, a language model scores target text, and a decoder searches for a translation using these scores and a reordering feature.
Modern neural machine translation (NMT) retains several tools from statistical MT. Decoders still use beam search, and evaluators still report BLEU. Word alignments help project annotations into languages with less labeled data. The central decoding problem also remains: a system can give its highest score to a translation that readers judge less accurate.
The organizing idea is the noisy channel. In a 1990 paper, Brown and colleagues at IBM treated translation as a decoding problem. Brown, Stephen Della Pietra, Vincent Della Pietra, and Mercer laid out five word-alignment models and reported experiments on the Canadian Hansards in their 1993 paper. In the noisy-channel formulation, the model treats a candidate translation as the latent input to a channel and the observed sentence as its output. This is a modeling choice: Bayes' rule lets us rank candidates using the channel and a prior over target sentences.
Modeling and splits the training work. Parallel text supplies cross-language examples for the translation model. The separate target language model can also learn from monolingual text, even when no translation is available.
We derive IBM Model 1 and its EM updates, then look at how later models handle word order and fertility. Next we extract and score phrase pairs and combine the scores with a language model and a reordering feature. The worked example implements these pieces and searches over coverage vectors. The next chapter uses an encoder-decoder to learn representations and translation scores jointly.
The Translation Problem as Noisy-Channel Inference
Suppose we want the most probable translation of a source sentence . Bayes' rule gives
The denominator does not depend on the candidate , so it drops out of the argmax:
Taking logs preserves this ranking for positive scores and turns the product into a sum:
Thirty factors of give , which fits in a double-precision float. Thirty factors of give , which rounds to zero in that format. The log score remains finite. Working in log space lets the decoder compare such scores by adding the log probabilities.
A generative model in which the observed data (here, the source sentence) is assumed to have been produced by passing the desired quantity (the target sentence) through a noisy channel. Translation becomes inference about the unobserved input: score candidate targets by how likely they were to generate the source () and by how likely they are as sentences in their own right ().
Why Split the Problem at All
The split is not cosmetic. It changes what data you need and what each model has to learn.
A direct model trained on parallel data learns from target sentences paired with each source. A separate target language model can also learn from unpaired target text.
The -gram language model from Part II can learn that “the house is small” is more common than “small is house the” from English text alone. The channel model can learn from aligned translations of “the house is small.” The two components can therefore draw on different data.
There is a second, subtler benefit. decomposes over a latent alignment between source and target words, and that decomposition is what allows training from sentence-aligned but word-unaligned bitext. That is the subject of the next section.
If you acquire more legal French, you can fit a language model on it and use its scores with the existing translation model. The new scores can change which candidate wins, so check adequacy on in-domain translations before choosing or retuning the weight.
Bayes' Rule in Log Space, and What Gets Lost
Three practical notes about the log-space form.
First, each log probability is , so extending a hypothesis by another term can only leave its accumulated score unchanged or lower it. If two candidates have the same average negative log score per word, the shorter candidate receives the smaller total penalty, which biases the search toward shorter outputs. Phrase-based systems add a tuned word penalty, an additive term proportional to output length, to offset that bias.
Second, the channel scores the observed input given a candidate output . Its alignment can map each observed to the candidate token that generated it. The decoder fixes and searches for .
Third, a vocabulary of 50,000 gives possible target strings of exactly 30 tokens before constraints. Phrase-based decoding narrows the search to permitted segmentations and reorderings. The toy decoder below keeps a single bounded beam at each expansion step. It ranks partial hypotheses by their accumulated scores, so it can discard one that would complete with a higher score.
Word Alignment
A parallel corpus gives you sentence pairs with the word links unobserved. The IBM equations below use for the sentence the alignment model conditions on and for the sentence it generates. In the noisy-channel scoring direction above, is the candidate translation and is the observed input. In the English–Zeta fixture below, the forward aligner conditions on the English input and generates Zeta. The same alignment equations work in either direction.
An IBM alignment maps each generated position to a conditioning position. If , then token generates token . The indices are:
- assigns one conditioning position to each generated position.
- is the conditioning position assigned to generated position .
- ranges from to , with denoting NULL.
- is the conditioning token at position .
- is the generated token at position .
The conditioning sentence gets an extra position for generated tokens without an aligned conditioning word. This covers some articles, particles, morphological differences, and insertions caused by stylistic or tokenization differences.
Token correspondence across the two sentences can be many-to-many. A directional IBM model assigns each generated position to one conditioning position, which may be NULL. Combining two directional models can recover a richer set of links.
Each generated token has one parent in a directional IBM model. The worked pipeline combines predictions from two directions to allow several links at a token. The symmetrization step below shows how.
The IBM models use latent alignments to estimate lexical probabilities from sentence-level bitext. In a phrase-based pipeline, the resulting links determine which spans are eligible for phrase extraction. A misplaced link can block an otherwise eligible phrase pair.
IBM Model 1
Model 1 makes the most brutal simplification possible: it ignores word order entirely and assumes every alignment is equally likely.
The generative story is:
- Condition on a generated length . To assign probabilities across lengths, specify a separate distribution for .
- For each generated position , choose a conditioning position uniformly.
- Generate from with probability .
The variables are:
- is the generated sentence length.
- indexes generated tokens from to .
- is the conditioning position assigned to generated position .
- is the number of conditioning tokens excluding NULL.
- is the lexical probability of emitting given .
Because the alignment is uniform over the possible functions, summing over alignments gives
where:
- : the normalized probability of the generated length, held fixed while fitting lexical parameters
- : the number of possible alignments, since each generated position independently selects one of conditioning positions (including NULL)
- : the lexical probability that conditioning token emits generated token
- : the extra conditioning position that can emit insertions
At fixed generated length , the prior gives each of the alignments probability . Conditional on an alignment, the generated tokens contribute . Multiplying gives . Sum over alignments and multiply by the normalized length probability to obtain the marginal above. For their Model 1 fit, Brown et al. used the same positive factor for every generated length and conditioning sentence. A positive constant over unbounded lengths gives an unnormalized score. Over a set of allowed lengths, a constant of gives a uniform length distribution. Brown et al. (1993), §4.1
Each lexical factor depends only on the link at one generated position. The sum over the possible alignments therefore becomes a product of per-position sums. With , direct enumeration visits alignments, exponential in . Model 1 evaluates the per-position sums in . The HMM below has dependent links and uses a recurrence to sum its paths.
The exponential growth in the number of alignments is the reason the factoring property matters. The figure makes the scale of the enumeration problem visible.
PythonIn [3]Expand
import numpy as np
from book_plot_style import PALETTE
sentence_lengths = np.arange(1, 11)
source_lengths = [4, 9, 19]
alignment_counts = np.array(
[
[(length + 1) ** n for n in sentence_lengths]
for length in source_lengths
],
dtype=float,
)
series_labels = [f"source length {length}" for length in source_lengths]
series_colors = [PALETTE["primary"], PALETTE["amber"], PALETTE["muted"]]
series = list(zip(series_labels, alignment_counts, series_colors))VisualizationOut [4]Expand

The lexical table has one entry per pair of conditioning and generated word types. Two 50,000-word vocabularies give 2.5 billion entries before adding a NULL row. Each normalized row has one fewer independent parameter than entries. In unsmoothed Model 1, a word pair absent from all cross-sentence co-occurrences receives zero expected count. For rows with positive total count, those absent pairs get zero probability in the M-step.
When the model assigns positive probability to the observed sentence pair, the common length factor cancels from the alignment posterior and leaves the best alignment unchanged. With the factor held fixed, its logarithm adds a constant to the lexical objective and leaves the EM updates unchanged.
Learning Alignment with EM
We never observe , so we use expectation maximization. The derivation follows the standard latent-variable recipe, and it is worth walking through because the update has an unusually clean form.
If we knew the alignments, we could count links for each lexical pair and normalize each conditioning row. If we knew the lexical probabilities, Model 1 would let us find a most probable alignment by picking a highest-scoring conditioning position for each generated token. EM uses the current posterior to allocate fractional counts, then re-estimates the lexical probabilities.
The E-step evaluates . For Model 1 this posterior factors over generated positions. Positive probability for the observed pair under the current parameters ensures every denominator below is positive. For each position , the posterior probability that its parent is position is
where:
- : the latent conditioning position that generated position
- : a candidate conditioning position from through , including NULL
- : the current lexical probability of emitting from
- : the sum over all conditioning positions
Let be the corpus of sentence pairs, counted with multiplicity, and let denote the expected complete-data log-likelihood:
Since is a sum of terms plus fixed terms, the M-step can operate on expected counts. For one sentence pair, sum the posterior contributions for all matching tokens and positions:
The masses for one generated occurrence sum to one across conditioning positions. The count aggregates occurrences by word type. If a generated word occurs twice or a conditioning word occupies two positions, each occurrence contributes separately.
where:
- : expected number of links from type to type for this sentence pair
- : the current lexical probability of emitting type from type
- : each contribution uses the tokens at the selected positions
- : the sum at this generated position includes NULL at
The M-step sums these expected counts over the corpus and normalizes each row with positive total count:
The E-step costs per sentence pair because the posterior factors over generated positions. The IBM training sequence used simpler models to initialize richer ones.
Two properties matter for interpreting results:
- Exact EM never decreases the observed-data likelihood. A uniform positive initialization allows observed co-occurrences to accumulate positive counts.
- The posterior is normalized over conditioning positions for each generated occurrence. Two positions with identical conditioning tokens receive equal posterior mass for that occurrence.
EM maximizes a lower bound given by the expected complete-data log-likelihood plus the entropy of the current alignment posterior. The bound touches the observed log-likelihood at the current parameters. In Model 1 the observed log-likelihood is, up to fixed terms, a sum of logs of positive affine functions of the lexical probabilities. It is concave over the row simplices, so any local maximum on that feasible set is global, although multiple maximizers can exist. This property of Model 1 does not apply to every model trained with EM.
If the conditioning sentence contains two copies of “the,” their contributions to each generated article's posterior are equal. Other positions, including NULL, compete through their lexical probabilities. Model 1 cannot choose between those two copies from position alone.
Adding Word Order: IBM Model 2
Model 1 gives the same alignment prior to every conditioning position. Model 2 can learn, for example, that a generated token at position 3 tends to align near the start in a given length pair.
Model 2 replaces the uniform prior with , the probability of choosing conditioning position for generated position :
The sum still factors over generated positions. Expected counts for accumulate separately for each generated position and length pair, then normalize over conditioning positions. A table fitted for one length pair does not directly supply a row for another. Sharing parameters, as in the diagonal prior used by fast_align, can reduce this dependence on individual length pairs.
Train an English-conditioned model and a French-conditioned model separately to estimate two sets of positional probabilities. When their Viterbi predictions are converted to a common pair of axes, they can disagree.
An absolute-position table can learn that position 20 frequently aligns to position 22 and that position 3 frequently aligns to position 5. Its rows fit those tendencies separately. The HMM below shares a displacement score across positions and conditions on the previous link.
HMM Alignment
To condition each link on the preceding one, use a first-order Markov chain. Vogel, Ney, and Tillmann (1996) proposed this alignment model. The simplified joint below conditions on the generated length .
One way to parameterize the transition is to assign a nonnegative score to a displacement and normalize over the available destinations:
The jump score depends on displacement. The normalized transition probability can still vary with absolute position because some destinations are unavailable near the ends of the source sentence.
As in the hidden Markov models in Part VI: Sequence Labeling, forward-backward computes alignment posteriors and Viterbi recovers a highest-scoring alignment. In this simplified recurrence, the generated positions are time steps and the conditioning positions are states, counting NULL. There is also a start distribution for the first link. Scanning all ordered state pairs at each step costs , compared with complete alignment paths. Lexical probabilities supply the emission scores.
HMM alignment learns jumps from one alignment position to the next. fast_align uses a different prior, a log-linear reparameterization of IBM Model 2 that favors the diagonal while choosing each generated position's link independently. Dyer, Chahuneau, and Smith (2013), sections 2–3.
Fertility, Distortion, and IBM Models 3–5
In Models 1 and 2 and the HMM formulation above, each generated position chooses one conditioning position. Several generated positions can choose the same one. The number of generated positions that choose a conditioning token is its fertility.
A concrete example makes the gap obvious. Translating English "the" into a language without articles, or translating a compound German noun into an English multiword phrase, requires dropping or expanding a single source word into zero or several target words. Models 1 and 2 can technically represent these outcomes, since a source word may be selected zero or many times, but they have no parameter that says "this word usually expands into two target words." The count is emergent noise rather than modeled structure.
Model 3 represents fertility explicitly. The joint weight of a sentence and alignment is the following term of Brown et al.'s marginalization. The formula applies to alignments with . Brown et al. (1993), section 4.4, equations 31–32.
The terms distinguish ordinary fertility from the NULL insertion process.
- is the conditioning sentence and denotes NULL.
- is the generated sentence. The alignment index specifies which conditioning token generated .
- counts the generated words linked to . The non-NULL count is .
- is the fertility distribution for a non-NULL conditioning token.
- is the probability that an ordinary generated word triggers an additional NULL word. The complementary probability is .
- supplies the lexical probability for every generated word, including those linked to NULL.
- supplies the placement probability for a word linked to a non-NULL conditioning position.
For each ordinary token, the factor counts the interchangeable orderings of its generated words before placement.
- The leading binomial term gives the probability of drawing exactly NULL words from opportunities.
- The placement process fills the remaining slots with NULL words in uniformly random order.
- The NULL placement probability cancels the orderings of those words. This leaves no NULL factor in the ordinary fertility or distortion products.
For example, if two ordinary words are generated and , the probability of one NULL insertion is . The binomial term accounts for either ordinary word triggering the insertion.
Fertility counts the words emitted by a conditioning token. Fertility zero drops that token. Distortion assigns scores to placements. Model 3 can assign mass to colliding ordinary placements, so its distribution is deficient when restricted to valid output strings.
Fertility couples the alignment decisions, so Model 3 loses the factoring shortcut used by Models 1 and 2. Brown and colleagues approximate the E-step by summing over move and swap neighborhoods around several candidate alignments. They find these candidates with local search, including searches that hold one alignment link fixed. Model 4 adds relative placement, and Model 5 tracks vacant positions to avoid assigning probability mass to overlapping placements. Och and Ney's Model 6 combines the Model 4 and HMM alignment distributions log-linearly, bringing together their complementary notions of positional locality. Brown et al. (1993), §4.4, Equation 44, Och and Ney (2003), section 2.3.1.
The standalone GIZA++ defaults run five iterations each of Model 1, the HMM, Model 3, and Model 4. Model 2 is configurable and defaults to zero iterations in that release. The Moses training wrapper sets three iterations each for Models 3 and 4 by default and accepts overrides. In both cases, stages can initialize from simpler models to refine the alignments. GIZA++ defaults, Moses training wrapper.
Alignment Heuristics in Practice
A directional IBM model assigns one conditioning parent to each generated position. One conditioning word can still generate several words in that direction. Whether a single direction can encode a link set depends on which side needs multiple parents. Suppose we annotate the two-token idiom “clam up” and its gloss “fall silent” as a unit, linking each word to both words on the other side. In that annotation, either direction would need two parents for a generated position.
The standard remedy is to train two models, one in each direction, and combine their output:
- Intersection : keeps only links present in both directions. Relative to union, it cannot increase gold-link recall.
- Union : keeps links from either direction. The precision of the additional links depends on what each aligner got right.
- Grow-diag-final-and: start from the intersection and consider neighbors in the union. In the growing phase, add a link if at least one endpoint is unaligned. In the final passes, test both endpoints and accept a link when both are still unaligned.
The Moses training script defaults to grow-diag-final, with grow-diag-final-and as an option. The final stage of the former can add a link with one endpoint still free. The worked example uses one final pass with the stricter AND rule.
The “diag” step permits diagonal neighbors of links already in the working alignment. A final pass can find isolated links that the growth phase cannot reach. Its endpoint test uses the alignment as it stands when each link is considered.
Alignment Error Rate (AER) uses both sure and possible human-annotated links. Links in the sure set determine the recall term, and links in the possible set, which includes the sure set, count toward the precision term. Och and Ney (2003) evaluated alignment predictions against annotated Hansards sentences. Results depend on the language pair, domain, and annotation protocol.
Our collaborative experiment below makes the symmetrization tradeoff visible: on a synthetic corpus with exact gold alignments, intersection, union, and grow-diag-final-and land at different F1 values, and none of them is universally best.
From Alignments to Phrase Pairs
Word-level translation is obviously insufficient. Idioms, collocations, and morphology all demand larger units. The move that defined phrase-based SMT was to derive those units from the alignments rather than annotate them: any contiguous source span that is consistently aligned to a contiguous target span becomes a phrase pair, with no requirement that it be a linguistic constituent.
Koehn, Och, and Marcu (2003) compared phrase extraction methods and showed how alignment-based extraction learns multiword entries without syntactic annotations.
A dictionary from source phrases to a list of candidate target phrases, each with one or more scores (direct and inverse translation probability, lexical weights) and often a count. Entries are induced automatically from word-aligned bitext; "phrase" here means "contiguous token sequence," not "syntactic constituent."
Extracting Consistent Phrase Pairs
The extraction rule (Koehn, Och, and Marcu, 2003) is a consistency condition. For a source span and a target span :
- At least one alignment point connects the two spans.
- Every alignment point whose source index is in has its target index in .
- Every alignment point whose target index is in has its source index in .
Conditions 2 and 3 require that all links involving either span stay inside both spans. Extractors can start with the shortest compatible target span and extend it across neighboring unaligned tokens. A length- sentence has nonempty contiguous spans. A maximum phrase length reduces the number of candidates; the pinned Moses phrase-based trainer defaults to seven tokens.
The test operates on token spans. For example, if “look up the word” aligns to “busca la palabra,” a consistent pair can include just the first two target tokens and their linked source span, even though “busca la” is not a complete phrase in the syntactic sense. The extraction test depends on the supplied links.
Links may cross inside the proposed spans. A candidate is inconsistent when a link connects a position inside one span to a position outside the other span. A single misplaced boundary-crossing link can therefore prevent the extractor from retaining that phrase pair.
Scoring the Phrase Table
For phrase extraction and counting here, is the phrase we condition on and is its paired phrase. The English–Zeta decoder learns that direction from English to Zeta. A relative-frequency estimate is
A phrase seen once with only one observed partner gets a relative-frequency estimate of 1.0 in that direction. The inverse probability uses the same pair count and sums over conditioning phrases paired with in the denominator. Both estimates can equal 1.0 if neither phrase has another observed partner. Keeping both as weighted features exposes directional ambiguity, while the count shows how much data supports the estimate.
Moses commonly uses direct and inverse phrase probabilities and direct and inverse lexical weights. For generated word , let be the set of conditioning positions aligned to it within the phrase pair. Let be the word-level probability estimated from aligned counts. Use the special NULL word when is empty. Koehn, Och, and Marcu (2003), section 4.4.
For a phrase pair with the conditioning phrase “house” and the generated phrase “la casa,” suppose “casa” aligns to “house” and “la” is unaligned. If and , the lexical weight is . These are illustrative probabilities. The lexical weight adds word-level evidence as a separate feature.
The Language Model as a Fluency Judge
Target-side language model scores can distinguish translation candidates with identical phrase scores and also contribute when those scores differ.
The exact chain rule conditions each token on the entire preceding prefix. The -gram model from Part II approximates that history with a window of at most tokens:
Estimate these bounded-history conditionals from target-side text, use smoothing for unseen -grams, and evaluate the model with perplexity. Its memory footprint depends on the vocabulary, retained -grams, and storage format.
Two details are specific to the MT setting.
First, a decoder queries the model as it extends a partial hypothesis. For each added word it needs the log probability conditioned on the preceding words. A wider beam and more phrase choices create more such lookups.
Second, a target-only language model can assign a high score to a fluent string that mistranslates the input. For example, “Take this with food” and “Do not take this with food” can both sound natural. The channel or other source-conditioned scores supply evidence about which instruction the input expresses.
The Log-Linear Model
Och and Ney (2002) combined translation scores, language-model scores and other features in a log-linear model. Here we return to the decoding notation from the opening. The input is fixed, and ranges over possible translations.
where:
- is a candidate translation.
- is the fixed input sentence.
- : the -th feature function, scoring the pair
- : the tunable weight of feature
- : the number of features
- The denominator sums the exponential scores over candidate translations for the same input .
For a fixed input the denominator is shared by all candidates. Exponentiation preserves their ordering, so finding the most probable candidate amounts to maximizing its weighted feature sum.
Setting , and recovers the noisy-channel ranking. Summing the score exponentials over the full target support then gives by the law of total probability. A decoder needs only the weighted score to rank translations.
The Feature Set
A typical phrase-based system uses these features:
- Direct phrase translation score sums over phrase pairs.
- Inverse phrase translation score sums over phrase pairs.
- Direct lexical weighting sums over phrase pairs.
- Inverse lexical weighting sums over phrase pairs.
- Language model score: , possibly several LMs for different corpora.
- Distortion: a penalty on reordering, usually the sum of jump distances .
- Word penalty applies a tuned coefficient to the number of output words.
- Phrase count applies a tuned coefficient to the number of phrase pairs used.
Comparing two segmentations involves different numbers of phrase-score terms. A negative phrase-count coefficient favors fewer phrases when the other feature totals tie. A positive coefficient favors more phrases under the same condition.
Weight Tuning: MERT and Friends
Och and Ney estimated the weights of a conditional log-linear translation model by maximizing the likelihood of reference translations. Minimum error rate training (MERT) instead chooses weights to minimize an automatic translation error measure on held-out data, such as when BLEU is expressed on the unit scale. Och and Ney (2002), equation 11, Och (2003), sections 2–3.
The algorithm exploits a property of the log-linear form: if you fix everything except , each candidate translation's score is a linear function of . The best-scoring candidate therefore changes only at finitely many breakpoints, and the error as a function of is piecewise constant. In one dimension you can enumerate all breakpoints exactly; MERT does this, alternating between coordinate directions until convergence. Concretely, for a candidate pool of translations, the score of candidate is , so any two candidates cross at most once, giving at most breakpoints. Sort them, evaluate the metric on each interval, keep the best, and repeat for the next coordinate.
Coordinate descent on a piecewise-constant, non-convex objective has no global optimality guarantee. Results can depend on initialization, tuning examples, and the candidates retained. Pairwise ranking optimization is an alternative described by Hopkins and May (2011). When tuning to a corpus-level metric, measure performance on a separate test set.
Decoding
Unrestricted phrase-based decoding is NP-hard. Knight (1999) proved hardness for word-based models, and Chang and Collins (2017) discuss the phrase-based setting and a dynamic program with a fixed distortion limit. A decoder can constrain the search by limiting the jump to the next input span.
Beam Search over Coverage Vectors
The standard algorithm is a variant of stack decoding. A state consists of:
- A coverage vector: a bitmask over source positions, recording which source words have been translated.
- The last source position covered, needed to score distortion.
- The last few target words produced, needed to score the language model incrementally.
- Accumulated feature values and a backpointer to the predecessor state.
A bitmask of the consumed positions in the input. The decoder rejects any new phrase span that overlaps a set bit. Future distortion and fluency scores also depend on the source end position and the target language model state.
For each hypothesis, choose an uncovered input position and try each allowed contiguous span starting there. Append a candidate target phrase, update the coverage mask, and add its feature scores. For a bigram language model, the first word of the new phrase is scored from the previous target word. Later words in the phrase are scored from their predecessors within that phrase.
Stack decoding groups hypotheses by how many input words they cover. Separately, exact recombination for a first-best search can retain only the best-scoring prefix when the hypotheses agree in every field that determines their legal continuations and future scores. In the basic phrase model below, those fields are the coverage mask, the last input phrase end, and the target language model context. A bigram model needs the previous target word. Each stack can then be pruned using either of these strategies. Moses manual, sections 6.2.3–6.2.4.
- Histogram pruning: keep only the top hypotheses per stack.
- Threshold pruning: discard hypotheses whose score is worse than the best in the stack by more than a fixed margin.
A beam can rank partial hypotheses using their accumulated score plus an estimate for the uncovered spans. The standard phrase-based heuristic precomputes estimates by dynamic programming, approximates the missing target context, and omits distortion in the estimate. Those approximations give no guarantee of an upper bound on the best remaining log score. For exact A* search, an admissible heuristic would have to supply that upper bound, or equivalently a lower bound on the remaining negative-log cost. Koehn, Och, and Marcu (2003), section 2.2, Moses manual, sections 6.2.4–6.2.5.
The decoder ranks completed hypotheses after adding the language model's end-of-sentence log score. A bigram model conditions it on the final target word.
Reordering Limits and Pruning
A hard distortion limit bounds the jump to the next input span and can rule out some reorderings. A conventional coverage-bitmask decoder still tracks which input positions are open. A fixed jump limit alone can leave exponentially many reachable masks for that representation. Chang and Collins (2017), section 5.2.
Pre-reordering permutes the source sentence before translation. Syntactic translation models, such as Galley et al. (2004), use tree structure to inform translation rules. A hard distance limit and a syntax-based rule offer different ways to constrain reorderings.
Worked Example: Two EM Iterations by Hand
Before writing code, let us run IBM Model 1 by hand on a tiny corpus so the mechanics are unambiguous. Use English as the source and our miniature target language "Zeta" as the target .
Training corpus, two sentence pairs:
- ,
- ,
The target vocabulary has three words, so we initialize everywhere.
Iteration 1, E-step. For sentence 1, the source is extended to . For the target word "ze":
so each source position receives posterior mass . The same holds for "mika". Sentence 2 has the same structure at initialization, so the same computation applies to "ze" and "voso". The posterior table after the E-step is therefore uniform: every (source position, target word) pair inside a sentence gets .
Iteration 1, M-step. Sum the counts. For source word "the", it appears in both sentences and receives from "ze" and from the other target word in each, for a total of . Its count for "ze" is , so
Similarly , , and the same for "dog". The model has already learned something: the cross-lexical entries dropped from to , and the "the"↔"ze" link rose to .
Iteration 2, E-step. Now the posteriors are no longer uniform. For "ze" in sentence 1, the denominator is
so each source position still gets a posterior of . For "mika" the denominator is
so "cat" gets posterior mass and the other two get each. The alignment is sharpening exactly where it should.
Iteration 2, M-step. For "the", the two occurrences of "ze" each contribute . "Mika" and "voso" each contribute in their respective sentences. The row total is , so
"Cat" appears only in sentence 1, where "ze" contributes and "mika" contributes . Dividing by their total, , gives and .
The two updates shift lexical probability toward the recurring correspondence between "the" and "ze" and toward the content words' partners. The expected counts remain fractional. The plotted values show how the finite run behaves on this specific two-pair corpus.
The hand-worked example shows the direction of the updates. Repeating the same deterministic EM updates for ten iterations makes the pace of convergence visible.
PythonIn [5]Expand
from collections import defaultdict
import numpy as np
from book_plot_style import PALETTE
tiny_pairs = [
(("the", "cat"), ("ze", "mika")),
(("the", "dog"), ("ze", "voso")),
]
tiny_src = ["<NULL>", "the", "cat", "dog"]
tiny_tgt = ["ze", "mika", "voso"]
tiny_t = {e: {f: 1.0 / len(tiny_tgt) for f in tiny_tgt} for e in tiny_src}
tiny_iters = 10
tiny_tracked = [("the", "ze"), ("cat", "mika"), ("the", "mika")]
tiny_curves = {pair: [] for pair in tiny_tracked}
for _ in range(tiny_iters):
for pair in tiny_tracked:
e, f = pair
tiny_curves[pair].append(tiny_t[e][f])
counts = {e: defaultdict(float) for e in tiny_src}
totals = defaultdict(float)
for src, tgt in tiny_pairs:
src_ext = ["<NULL>"] + list(src)
for f in tgt:
denom = sum(tiny_t[e][f] for e in src_ext)
for e in src_ext:
mass = tiny_t[e][f] / denom
counts[e][f] += mass
totals[e] += mass
for e in tiny_src:
denom = totals[e] if totals[e] > 0 else 1.0
tiny_t[e] = {f: counts[e][f] / denom for f in tiny_tgt}
tiny_x = np.arange(1, tiny_iters + 1)
tiny_series = [
("t(ze | the)", tiny_curves[("the", "ze")], PALETTE["primary"]),
("t(mika | cat)", tiny_curves[("cat", "mika")], PALETTE["amber"]),
("t(mika | the)", tiny_curves[("the", "mika")], PALETTE["muted"]),
]VisualizationOut [6]Expand

Building a Miniature SMT System in Python
We now implement the full pipeline. To make alignment quality measurable, we generate a synthetic parallel corpus from a tiny grammar, which gives us exact gold alignments for free. The target language "Zeta" is engineered to differ from English in two ways that matter:
- It is verb-final: object before verb (
ze mika ze voso tira= "the cat the dog sees"). - It uses postpositions:
inofollows its noun rather than preceding it.
The toy lexicon assigns a single counterpart to each lexical item. The generator records which positions correspond, so we know the gold links even when a token occurs twice. Natural parallel text can add one-to-many correspondences, morphological splitting, and freer translations.
Step 1: Generate a Corpus with Gold Alignments
We define the lexicon and three sentence templates. Each template returns the English tokens, the Zeta tokens, and the gold alignment as a list of (english_index, zeta_index) pairs.
PythonIn [8]Expand
LEXICON = {
"the": "ze",
"a": "un",
"cat": "mika",
"dog": "voso",
"bird": "turi",
"fish": "paku",
"sees": "tira",
"chases": "kavu",
"big": "runa",
"small": "piti",
"is": "va",
"in": "ino",
".": ".",
}
def z(word):
return LEXICON[word]
def transitive(n1, verb, n2, det):
"""English SVO -> Zeta SOV, determiners preserved."""
en = [det, n1, verb, det, n2, "."]
ze = [z(det), z(n1), z(det), z(n2), z(verb), "."]
gold = [(0, 0), (1, 1), (3, 2), (4, 3), (2, 4), (5, 5)]
return en, ze, gold
def copular(n1, adj):
"""Adjective follows the noun; copula moves to the end."""
en = ["the", n1, "is", adj, "."]
ze = [z("the"), z(n1), z(adj), z("is"), "."]
gold = [(0, 0), (1, 1), (3, 2), (2, 3), (4, 4)]
return en, ze, gold
def locative(n1, n2):
"""Zeta uses a postposition, so 'in' moves after its noun."""
en = ["the", n1, "is", "in", "the", n2, "."]
ze = [z("the"), z(n1), z("the"), z(n2), z("in"), z("is"), "."]
gold = [(0, 0), (1, 1), (4, 2), (5, 3), (3, 4), (2, 5), (6, 6)]
return en, ze, goldNow we enumerate every combination, which gives 88 unique sentence pairs.
PythonIn [9]Expand
NOUNS = ["cat", "dog", "bird", "fish"]
VERBS = ["sees", "chases"]
ADJECTIVES = ["big", "small"]
corpus = []
for det in ["the", "a"]:
for n1 in NOUNS:
for verb in VERBS:
for n2 in NOUNS:
corpus.append(transitive(n1, verb, n2, det))
for n1 in NOUNS:
for adj in ADJECTIVES:
corpus.append(copular(n1, adj))
for n1 in NOUNS:
for n2 in NOUNS:
corpus.append(locative(n1, n2))
rng = random.Random(13)
rng.shuffle(corpus)
n_train = int(0.9 * len(corpus))
train, test = corpus[:n_train], corpus[n_train:]
# Guarantee every Zeta word appears in training so the phrase table can cover the test set.
seen_zeta = {w for _, ze, _ in train for w in ze}
for pair in list(test):
if not set(pair[1]) <= seen_zeta:
test.remove(pair)
train.append(pair)
seen_zeta |= set(pair[1])
train_pairs = [(en, ze) for en, ze, _ in train]
gold_train = [gold for _, _, gold in train]ConsoleOut [10]Expand
Total sentence pairs: 88 Training pairs: 79 Held-out pairs: 9 Example pair English: the cat is in the fish . Zeta: ze mika ze paku ino va . gold: [(0, 0), (1, 1), (4, 2), (5, 3), (3, 4), (2, 5), (6, 6)]
The corpus splits into 79 training pairs and 9 held-out pairs. The gold alignment for the first training pair is a set of index pairs such as (0, 0) and (1, 1), which we can compare directly against what the aligner predicts. The vocabulary-coverage check just above the split is a small but important piece of experimental hygiene: if a held-out sentence contains a Zeta word that never appeared in training, the phrase table cannot possibly translate it, and the resulting failure would say nothing about the decoder.
Step 2: Train IBM Model 1 with EM
We write the model as three small functions: one to build vocabularies, one to initialize uniformly, and one to run a single EM iteration. Keeping the E-step and M-step together emphasizes that the only thing that changes between iterations is the table.
PythonIn [11]Expand
NULL = "<NULL>"
def build_vocab(pairs):
src = {NULL}
tgt = set()
for s, t in pairs:
src.update(s)
tgt.update(t)
return sorted(src), sorted(tgt)
def uniform_table(src_vocab, tgt_vocab):
u = 1.0 / len(tgt_vocab)
return {e: {f: u for f in tgt_vocab} for e in src_vocab}
def em_step(t_table, bitext, src_vocab, tgt_vocab):
"""One E-step plus M-step of IBM Model 1. Returns a new t table."""
count = {e: defaultdict(float) for e in src_vocab}
total = defaultdict(float)
for src, tgt in bitext:
src_ext = [NULL] + list(src)
for f in tgt:
denom = sum(t_table[e][f] for e in src_ext)
for e in src_ext:
mass = t_table[e][f] / denom
count[e][f] += mass
total[e] += mass
new_table = {}
for e in src_vocab:
if total[e] > 0:
new_table[e] = {f: count[e][f] / total[e] for f in tgt_vocab}
else:
new_table[e] = t_table[e].copy()
return new_tableFor each generated token, the E-step normalizes over the extended conditioning sentence. The M-step divides expected counts by their conditioning row's total when it is positive. A row with zero total contributes nothing to the expected complete-data objective, so any normalized row for that type is a valid M-step choice. The toy keeps the preceding normalized row in that case. Its vocabulary comes from the training corpus, and initialization is positive.
Next, Viterbi decoding: for each target word, pick the source word with the highest . This is the maximum-posterior alignment under Model 1.
PythonIn [12]Expand
def viterbi_align(src, tgt, t_table):
"""For each target position, pick the best source position. i = -1 means NULL."""
src_ext = [NULL] + list(src)
links = []
for j, f in enumerate(tgt):
best_i = max(range(len(src_ext)), key=lambda i: t_table[src_ext[i]][f])
links.append((best_i - 1, j))
return links
def align_reverse(src, tgt, rev_table):
"""For each source position, pick the best target position under t(source|target)."""
tgt_ext = [NULL] + list(tgt)
links = []
for i, e in enumerate(src):
best_j = max(
range(len(tgt_ext)), key=lambda j: rev_table[tgt_ext[j]][e]
)
links.append((i, best_j - 1))
return links
def alignment_f1(predicted, gold, filter_null=True):
tp = fp = fn = 0
for pred, gold_links in zip(predicted, gold):
p = (
{(i, j) for i, j in pred if (i >= 0 and j >= 0)}
if filter_null
else set(pred)
)
g = set(gold_links)
tp += len(p & g)
fp += len(p - g)
fn += len(g - p)
precision = tp / (tp + fp) if tp + fp else 0.0
recall = tp / (tp + fn) if tp + fn else 0.0
f1 = (
2 * precision * recall / (precision + recall)
if precision + recall
else 0.0
)
return precision, recall, f1Now the training loop. We record alignment F1 against gold before each parameter update, so iteration reports the quality of the model produced by previous updates.
PythonIn [13]Expand
src_vocab, tgt_vocab = build_vocab(train_pairs)
t_table = uniform_table(src_vocab, tgt_vocab)
N_ITER = 10
alignment_history = []
for it in range(N_ITER):
preds = [viterbi_align(en, ze, t_table) for en, ze in train_pairs]
precision, recall, f1 = alignment_f1(preds, gold_train)
alignment_history.append((it, precision, recall, f1))
t_table = em_step(t_table, train_pairs, src_vocab, tgt_vocab)ConsoleOut [14]Expand
iter precision recall F1 0 0.000 0.000 0.000 1 0.650 0.631 0.641 2 0.776 0.648 0.706 3 0.776 0.648 0.706 4 0.776 0.648 0.706 5 0.776 0.648 0.706 6 0.776 0.648 0.706 7 0.776 0.648 0.706 8 0.776 0.648 0.706 9 0.776 0.648 0.706
All three scores begin at zero because the uniform table gives each target word a tie and the decoder chooses the first position, NULL. After two updates the F1 reaches about 0.706 and stays there in the recorded curve. Model 1 assigns identical lexical scores to repeated occurrences of "the", so it has no positional information to disambiguate those links.
VisualizationOut [15]Expand

Step 3: Train the Reverse Direction and Symmetrize
In this pipeline, we train a reverse model, , and combine both directions before extracting phrases. The extractor accepts any valid set of source–target links in its coordinate convention, including links from a single direction.
PythonIn [16]Expand
rev_table = {NULL: {f: 1.0 / len(src_vocab) for f in src_vocab}}
rev_table.update(uniform_table(tgt_vocab, src_vocab))
for _ in range(N_ITER):
rev_table = em_step(
rev_table,
[(ze, en) for en, ze in train_pairs],
[NULL] + tgt_vocab,
src_vocab,
)
pred_ef = [viterbi_align(en, ze, t_table) for en, ze in train_pairs]
pred_fe = [align_reverse(en, ze, rev_table) for en, ze in train_pairs]The grow-diag-final-and heuristic starts at the intersection. It considers all eight neighboring cells and adds a union link if either endpoint is unaligned. In the final pass it can add a remaining union link only if both endpoints are unaligned.
PythonIn [17]Expand
NEIGHBOURS = [
(-1, -1),
(-1, 0),
(-1, 1),
(0, -1),
(0, 1),
(1, -1),
(1, 0),
(1, 1),
]
def grow_diag_final_and(a_ef, a_fe):
inter = a_ef & a_fe
union = a_ef | a_fe
links = set(inter)
aligned_src = {i for i, _ in inter}
aligned_tgt = {j for _, j in inter}
def grow_once():
added = False
for i, j in sorted(union - links):
if i in aligned_src and j in aligned_tgt:
continue
if any((i + di, j + dj) in links for di, dj in NEIGHBOURS):
links.add((i, j))
aligned_src.add(i)
aligned_tgt.add(j)
added = True
return added
while grow_once():
pass
for i, j in sorted(union - links):
if i not in aligned_src and j not in aligned_tgt:
links.add((i, j))
aligned_src.add(i)
aligned_tgt.add(j)
return linksNow compare the five candidate alignments against gold on the training set.
PythonIn [18]Expand
variant_names = [
"English to Zeta",
"Zeta to English",
"Intersection",
"Union",
"Grow-diag-final-and",
]
variant_links = {name: [] for name in variant_names}
sym_alignments = []
for idx, (en, ze) in enumerate(train_pairs):
a_ef = {(i, j) for i, j in pred_ef[idx] if i >= 0}
a_fe = {(i, j) for i, j in pred_fe[idx] if j >= 0}
gdfa = grow_diag_final_and(a_ef, a_fe)
sym_alignments.append(gdfa)
for name, links in zip(
variant_names,
[a_ef, a_fe, a_ef & a_fe, a_ef | a_fe, gdfa],
):
variant_links[name].append(sorted(links))
variant_f1 = {}
for name in variant_names:
_, _, f1 = alignment_f1(variant_links[name], gold_train)
variant_f1[name] = f1ConsoleOut [19]Expand
English to Zeta F1 = 0.706 Zeta to English F1 = 0.706 Intersection F1 = 0.786 Union F1 = 0.641 Grow-diag-final-and F1 = 0.706
The intersection has the highest measured F1, about 0.786. Both one-way alignments and grow-diag-final-and score about 0.706. The union scores about 0.641. These results depend on which links the directional models contribute. For instance, both directional models tie on the period's lexical probability between NULL and the observed period. The first-maximum rule chooses NULL in each direction. After filtering out NULL, the period-to-period link is absent from the union, so neither the growth pass nor the final pass can recover it.
VisualizationOut [20]Expand

Step 4: Extract and Score Phrase Pairs
Phrase extraction applies the consistency rule from earlier. The toy parameter max_len caps both the source and the target span. The pinned Moses trainer uses seven tokens as the default maximum phrase length in ordinary phrase extraction.
PythonIn [21]Expand
def extract_phrase_pairs(src, tgt, align, max_len=3):
pairs = []
n = len(src)
for i1 in range(n):
for i2 in range(i1, min(i1 + max_len, n)):
js = [j for i, j in align if i1 <= i <= i2]
if not js:
continue
j1, j2 = min(js), max(js)
if j2 - j1 + 1 > max_len:
continue
crossing = any((i1 <= i <= i2) != (j1 <= j <= j2) for i, j in align)
if crossing:
continue
pairs.append((tuple(src[i1 : i2 + 1]), tuple(tgt[j1 : j2 + 1])))
return pairsA source span with no links is skipped. For each other source span, the target side is the smallest contiguous span containing all linked target positions. This toy omits unaligned target positions beyond that span. The crossing test rejects a link with one endpoint inside its span and the other outside its span.
Now collect all extracted pairs and build the phrase table with direct relative frequencies in log space.
PythonIn [22]Expand
extracted = []
for idx, (en, ze) in enumerate(train_pairs):
extracted.extend(extract_phrase_pairs(en, ze, sorted(sym_alignments[idx])))
phrase_counts = Counter(extracted)
source_totals = Counter()
for (src_phrase, tgt_phrase), count in phrase_counts.items():
source_totals[src_phrase] += count
phrase_table = defaultdict(list)
for (src_phrase, tgt_phrase), count in phrase_counts.items():
phrase_table[src_phrase].append(
(tgt_phrase, math.log(count / source_totals[src_phrase]))
)
for src_phrase in phrase_table:
phrase_table[src_phrase].sort(key=lambda entry: -entry[1])ConsoleOut [23]Expand
Distinct phrase pairs extracted: 103 Distinct source phrases: 72 the cat -> ze mika ze (-0.69), mika (-0.94), ze mika (-2.20) sees the dog -> voso tira (-0.29), tira (-1.39) is in the -> ino va (0.00) . -> (no standalone entry) a -> (no standalone entry)
The table includes "voso tira" as a candidate for "sees the dog". That entry puts the object before the verb in the target. The period and "a" have no standalone entries under this alignment. Larger spans can still cover unaligned source tokens. That distinction matters when we inspect the decoder's output.
The learned alignments can also change which candidates the extractor finds. For “the cat,” extraction with the gold links gives only “ze mika.” The learned links give “ze mika,” “mika,” and “ze mika ze.” The decoder uses the phrase translation score, language model, distortion, and phrase count to rank candidates.
The phrase table is not uniformly ambiguous. The distribution of candidate counts shows how often the decoder must choose among alternatives.
PythonIn [24]Expand
import numpy as np
from book_plot_style import PALETTE
translation_counts = np.array(
[len(options) for options in phrase_table.values()], dtype=int
)
max_translations = (
int(translation_counts.max()) if translation_counts.size else 0
)
count_bins = np.arange(0.5, max_translations + 1.5, 1.0)
hist_color = PALETTE["primary"]VisualizationOut [25]Expand

Step 5: Build the Language Model
A bigram model with add- smoothing scores partial hypotheses and full sentences. For , each row is normalized over the training vocabulary, including both boundary tokens. A query with a word or context outside that vocabulary raises an error. The toy decoder's phrase table emits training tokens, so it needs no unknown-token mapping.
PythonIn [26]Expand
class BigramLM:
def __init__(self, sentences, alpha=0.1):
self.alpha = alpha
self.counts = defaultdict(Counter)
self.totals = Counter()
self.vocab = {"<s>", "</s>"}
for sentence in sentences:
tokens = ["<s>"] + list(sentence) + ["</s>"]
self.vocab.update(tokens)
for prev, word in zip(tokens, tokens[1:]):
self.counts[prev][word] += 1
self.totals[prev] += 1
self.v_size = len(self.vocab)
def prob(self, prev, word):
if prev not in self.vocab or word not in self.vocab:
raise ValueError(
"BigramLM expects tokens from its training vocabulary."
)
numerator = self.counts[prev][word] + self.alpha
denominator = self.totals[prev] + self.alpha * self.v_size
return numerator / denominator
def logprob(self, tokens):
padded = ["<s>"] + list(tokens) + ["</s>"]
return sum(
math.log(self.prob(a, b)) for a, b in zip(padded, padded[1:])
)
lm = BigramLM([ze for _, ze in train_pairs])ConsoleOut [27]Expand
Language model vocabulary size: 15 ze mika ze voso tira . log P = -6.126 ze mika tira ze voso . log P = -16.596 ze voso ze mika tira . log P = -6.126
The bigram model prefers both verb-final strings to the English-order string and scores the two verb-final strings equally, at about −6.126. It learns a local word-order preference from target text.
Note that the LM is not scoring whether the sentence is a correct translation. It is scoring whether the sentence looks like Zeta. "ze voso ze mika tira ." is perfectly fluent Zeta; it just means the dog sees the cat rather than the other way around. Nothing in the LM can detect that error, and this is precisely the division of labor the noisy channel sets up: the LM supplies fluency, and the translation model has to supply adequacy. Neither is sufficient alone.
Step 6: The Decoder
The toy decoder gives negative total jump distance a weight of , so a larger jump lowers the score. The weight stored under phrase_penalty is applied to the positive number of phrases used. With the fixture weight of , adding a phrase raises the score by when the other feature totals stay fixed.
PythonIn [28]Expand
@dataclass
class Hypothesis:
lm: float
tm: float
distortion: float
phrases: int
words: tuple
last_src_end: int
last_word: str
score: float = 0.0
WEIGHTS = {"lm": 0.5, "tm": 1.0, "distortion": 0.2, "phrase_penalty": 0.2}
def score_hypothesis(hyp, weights):
return (
weights["lm"] * hyp.lm
+ weights["tm"] * hyp.tm
+ weights["distortion"] * hyp.distortion
+ weights["phrase_penalty"] * hyp.phrases
)
def decode(sentence, table, lm, weights, max_phrase_len=3, beam=40, n_best=3):
n = len(sentence)
full = (1 << n) - 1
start = Hypothesis(
lm=0.0,
tm=0.0,
distortion=0.0,
phrases=0,
words=(),
last_src_end=-1,
last_word="<s>",
)
active = {(0, -1): start}
finished = []
for _ in range(n + 1):
nxt = {}
for (mask, last_end), hyp in active.items():
if mask == full:
finished.append(hyp)
continue
for i in range(n):
if (mask >> i) & 1:
continue
for length in range(1, max_phrase_len + 1):
if i + length > n:
break
span = ((1 << length) - 1) << i
if mask & span:
break
src_phrase = tuple(sentence[i : i + length])
for tgt_phrase, logp in table.get(src_phrase, ())[:n_best]:
previous = (hyp.last_word,) + tgt_phrase[:-1]
lm_gain = sum(
math.log(lm.prob(a, b))
for a, b in zip(previous, tgt_phrase)
)
cand = Hypothesis(
lm=hyp.lm + lm_gain,
tm=hyp.tm + logp,
distortion=hyp.distortion - abs(i - last_end - 1),
phrases=hyp.phrases + 1,
words=hyp.words + tgt_phrase,
last_src_end=i + length - 1,
last_word=tgt_phrase[-1],
)
cand.score = score_hypothesis(cand, weights)
key = (mask | span, i + length - 1)
if key not in nxt or cand.score > nxt[key].score:
nxt[key] = cand
if not nxt:
break
active = dict(sorted(nxt.items(), key=lambda kv: -kv[1].score)[:beam])
finished.extend(h for (mask, _), h in active.items() if mask == full)
if not finished:
return [], float("-inf")
best_hyp, best_score = None, float("-inf")
for hyp in finished:
total = hyp.score + weights["lm"] * math.log(
lm.prob(hyp.last_word, "</s>")
)
if total > best_score:
best_score, best_hyp = total, hyp
return list(best_hyp.words), best_scoreThree behaviors to notice in that code:
- The coverage mask prevents any source word from being translated twice, so the search space is a subset of permutations of phrase segmentations.
- Approximate recombination uses the dictionary key
(mask, last_end). This keeps the higher-scoring prefix for each coverage mask and last input span end. Two such prefixes can end in different target words and score the same continuation differently under the bigram model. Keeping the higher score so far can therefore discard the better completion. - Pruning is a global sort by score, then a truncation to
beam. The code scores the partial hypotheses without a future cost estimate. A finite beam can discard a partial hypothesis that would have scored well after completion.
The decoder keeps at most n_best options for each source phrase, ranked by phrase score. This saves search work when a phrase has many candidates. A lower-ranked option can still lead to a better complete translation once the other score terms enter. The worked table has at most three options per phrase, so n_best=3 keeps them all. Moses User Manual, §3.1.6
Let's run it on the held-out set.
PythonIn [29]Expand
hypotheses = []
references = []
for en, ze, _ in test:
output, _score = decode(en, phrase_table, lm, WEIGHTS)
hypotheses.append(output)
references.append(ze)ConsoleOut [30]Expand
Exact matches: 0/9 Matches after ignoring only the final reference period: 9/9 EN : the bird sees the cat . SYS: ze turi ze mika tira REF: ze turi ze mika tira . EN : the fish is in the dog . SYS: ze paku ze voso ino va REF: ze paku ze voso ino va . EN : the fish chases the cat . SYS: ze paku ze mika kavu REF: ze paku ze mika kavu . EN : the bird sees the bird . SYS: ze turi ze turi tira REF: ze turi ze turi tira . EN : the fish chases the dog . SYS: ze paku ze voso kavu REF: ze paku ze voso kavu . EN : the bird is in the fish . SYS: ze turi ze paku ino va REF: ze turi ze paku ino va .
All nine hypotheses match the reference words in order, and all nine omit the final period. Some extracted multiword spans cover the period's source position while emitting no punctuation, and the coverage mask records only that the position was consumed. It cannot check whether each consumed token produced a corresponding output, so the strict exact-match count is zero.
Step 7: Score with BLEU
This toy BLEU uses one reference per hypothesis, paired by position in equally long lists. It clips each hypothesis's -gram counts against that reference and uses that reference's length in the corpus brevity penalty. The original BLEU definition allows multiple references. The toy defaults to orders one through four.
PythonIn [31]Expand
def ngram_counts(tokens, n):
return Counter(tuple(tokens[i : i + n]) for i in range(len(tokens) - n + 1))
def corpus_bleu(hyps, refs, max_n=4):
matches = [0] * max_n
totals = [0] * max_n
hyp_len = ref_len = 0
for hyp, ref in zip(hyps, refs):
hyp_len += len(hyp)
ref_len += len(ref)
for n in range(1, max_n + 1):
hyp_counts = ngram_counts(hyp, n)
ref_counts = ngram_counts(ref, n)
matches[n - 1] += sum(
min(c, ref_counts[g]) for g, c in hyp_counts.items()
)
totals[n - 1] += max(len(hyp) - n + 1, 0)
precisions = [(matches[i] + 1) / (totals[i] + 1) for i in range(max_n)]
if hyp_len == 0:
return 0.0
if hyp_len > ref_len:
brevity = 1.0
else:
brevity = math.exp(1 - ref_len / hyp_len)
return brevity * math.exp(sum(math.log(p) for p in precisions) / max_n)
bleu = corpus_bleu(hypotheses, references)ConsoleOut [32]Expand
Corpus BLEU: 0.826 Per-sentence unigram precision: 1.000 ze turi ze mika tira 1.000 ze paku ze voso ino va 1.000 ze paku ze mika kavu 1.000 ze turi ze turi tira 1.000 ze paku ze voso kavu 1.000 ze turi ze paku ino va 1.000 ze turi ze paku kavu 1.000 un mika un voso kavu 1.000 un mika un voso tira
This pedagogical variant adds one to the matched and total counts at each order. That keeps the precision positive in this fixture when an order has no matches. The original unsmoothed corpus BLEU of Papineni et al. (2002) uses modified -gram precisions without this add-one step.
The smoothed corpus BLEU is about 0.826 and strict exact match is zero. Each hypothesis matches its reference up to the missing final period. All four clipped precisions equal one, so the brevity penalty accounts for the entire drop from one. Exact match makes the deletion visible alongside the overlap score.
Step 8: Inspect the Learned Lexicon
Finally, a direct look at the matrix that EM produced. Each row is an English word, each column a Zeta word, and the gold links are overlaid.
PythonIn [33]Expand
target_example = ["the", "cat", "sees", "the", "dog", "."]
example = next(
((en, ze, gold) for en, ze, gold in train if en == target_example),
train[0],
)
example_en, example_ze, example_gold = example
lexical_matrix = np.array(
[[t_table[e][f] for f in example_ze] for e in example_en]
)VisualizationOut [34]Expand

Both English “the” rows give the two Zeta “ze” columns the same lexical score. The gold links distinguish the occurrences, but the model's lexical features cannot tell them apart. The “sees” row scores “tira” highly at the fifth Zeta position, before the period. This shows a lexical correspondence despite the shift from the third English position.
Limitations and Impact
The alignment, phrase extraction, feature scoring, and search stages expose different sources of translation error.
Errors can compound through the pipeline. A misplaced alignment link can change which phrase pairs enter the table. Retuning feature weights can change how the decoder ranks candidates, but it leaves the alignments and phrase counts fixed.
The search can exclude useful reorderings. A hard distortion limit prohibits jumps longer than the threshold, even if a resulting translation would receive a high language model score. A soft distortion penalty leaves the candidate eligible and reduces its score.
Rare phrase pairs are hard to estimate. A pair seen once may receive a relative-frequency estimate of one. The inverse score and lexical weight add other information, but the underlying pair count still reflects one observation.
Tuned weights depend on the candidates and the data. Adding a feature changes the ranking objective. Check whether its held-out gains persist on separate test translations, especially when changing domains.
Morphology splits evidence across surface forms. With a word vocabulary, inflected forms have separate entries. Factored translation models can represent more than the surface form, and subword tokenization can share units across forms.
Overlap is only one signal for evaluation. BLEU uses modified -gram precision and a brevity penalty. A dropped negation can leave much of a sentence intact at the token level while reversing its meaning. The later evaluation chapters compare overlap scores with other approaches.
The IBM models learned word-alignment parameters from parallel sentences. Moses packaged phrase-based translation training and decoding in an open-source toolkit. These systems made it possible to inspect links, phrase counts, scores, and search decisions separately.
Beam search and BLEU also appear in neural translation. Word alignment has applications beyond phrase-table construction, including projecting annotations between parallel sentences.
The next chapter trains an encoder and decoder jointly to score translations. The worked example here shows why it helps to inspect model scores and search separately: even the best hypothesis a beam retains can differ from the reference.
Summary
- Statistical MT can frame translation as noisy-channel inference: . The translation model can learn from parallel text and the language model can learn from monolingual text.
- Word alignment is the latent structure used to train the translation model without word-aligned corpora. In Model 1, the alignment sum factors. Computing and accumulating expected counts takes per sentence pair, counting NULL. The M-step then totals and normalizes those counts across the corpus.
- Model 1 assigns each generated occurrence to conditioning positions with posterior weights proportional to . The M-step normalizes positive-count rows and can keep the preceding normalized row when its count is zero. Exact EM cannot decrease likelihood, and identical conditioning tokens have equal posterior weights under Model 1.
- Model 2 adds an absolute-position distribution. HMM alignment uses a first-order dependency on the previous alignment, which supports exact forward-backward inference. Models 3–5 add fertility and distortion, introducing dependencies that make Model 1's independent-position calculation inapplicable.
- Symmetrization combines two directional alignments into a richer relation. The toy uses grow-diag-final-and, with a two-free-endpoint test in its final pass.
- Phrase pairs are extracted by a consistency rule: a source span and target span that align to each other and to nothing else. Phrases are contiguous token sequences, not constituents, and this is why phrase-based MT captures idioms and collocations.
- Phrase tables use direct and inverse relative frequencies alongside lexical weights, which add word-level evidence. Unaligned words contribute their probability under the NULL word.
- The log-linear model ranks translations by a weighted sum of features. Maximum likelihood fits weights to reference translations. MERT tunes weights to an evaluation metric on held-out examples, using a non-convex objective.
- The toy decoder uses approximate beam search over coverage vectors. Recombination and pruning limit the states it keeps. Hard distortion limits can restrict permitted reorderings.
- On our synthetic English–Zeta corpus, IBM Model 1 alignment F1 reaches about 0.706 after two EM updates and then stays flat. The intersection scores about 0.786, while grow-diag-final-and ties the one-way models at about 0.706. The beam decoder puts the words in reference order on all nine held-out sentences and drops the final period on each one.
- Inspect alignment, phrase coverage, and decoder scores when diagnosing a wrong output. Each stage can remove candidates or change their rank.
Quiz
Ready to test your understanding? Take this quick quiz to reinforce what you've learned about statistical machine translation.
Statistical Machine Translation Foundations
Join the discussionAsk a question or share what you learned.
Keep exploring
Reference
Citation details
Cite or share this article.


Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!