Statistical Machine Translation Foundations

Michael BrenndoerferNovember 26, 202659 min read

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
Part 27 of 67Machine Translation and Speech Translation
Chapter 190Statistical Machine Translation Foundations
Reading the full chapter · 12 sections · 59 min12 sections · 59 min

All 12 sections · 59 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Statistical Machine Translation Foundations

Machine translation maps a sentence f=(f1,…,fJ)\mathbf{f} = (f_1, \dots, f_J) in a source language to a sentence e=(e1,…,eI)\mathbf{e} = (e_1, \dots, e_I) 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 e\mathbf{e} as the latent input to a channel and the observed sentence f\mathbf{f} as its output. This is a modeling choice: Bayes' rule lets us rank candidates using the channel and a prior over target sentences.

Modeling P(f∣e)P(\mathbf{f} \mid \mathbf{e}) and P(e)P(\mathbf{e}) 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 f\mathbf{f}. Bayes' rule gives

P(e∣f)=P(f∣e) P(e)P(f).P(\mathbf{e} \mid \mathbf{f}) = \frac{P(\mathbf{f} \mid \mathbf{e})\,P(\mathbf{e})}{P(\mathbf{f})}.

The denominator P(f)P(\mathbf{f}) does not depend on the candidate e\mathbf{e}, so it drops out of the argmax:

e^=arg⁡max⁡e  P(f∣e) P(e).\hat{\mathbf{e}} = \arg\max_{\mathbf{e}} \; P(\mathbf{f} \mid \mathbf{e}) \, P(\mathbf{e}).

Taking logs preserves this ranking for positive scores and turns the product into a sum:

e^=arg⁡max⁡e  [log⁡P(f∣e)+log⁡P(e)].\hat{\mathbf{e}} = \arg\max_{\mathbf{e}} \; \big[ \log P(\mathbf{f} \mid \mathbf{e}) + \log P(\mathbf{e}) \big].

Thirty factors of 10−210^{-2} give 10−6010^{-60}, which fits in a double-precision float. Thirty factors of 10−1110^{-11} give 10−33010^{-330}, which rounds to zero in that format. The log score 30log⁡(10−11)30\log(10^{-11}) remains finite. Working in log space lets the decoder compare such scores by adding the log probabilities.

Noisy Channel Model

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 (P(f∣e)P(\mathbf{f}\mid\mathbf{e})) and by how likely they are as sentences in their own right (P(e)P(\mathbf{e})).

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 P(e∣f)P(\mathbf{e} \mid \mathbf{f}) 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 nn-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. P(f∣e)P(\mathbf{f} \mid \mathbf{e}) 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 ≤0\le 0, 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 f\mathbf{f} given a candidate output e\mathbf{e}. Its alignment can map each observed fjf_j to the candidate token eie_i that generated it. The decoder fixes f\mathbf{f} and searches for e\mathbf{e}.

Third, a vocabulary of 50,000 gives 50,0003050{,}000^{30} 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 e\mathbf{e} for the sentence the alignment model conditions on and f\mathbf{f} for the sentence it generates. In the noisy-channel scoring direction above, e\mathbf{e} is the candidate translation and f\mathbf{f} 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 a\mathbf{a} maps each generated position to a conditioning position. If aj=ia_j=i, then token eie_i generates token fjf_j. The indices are:

  • a=(a1,…,aJ)\mathbf{a} = (a_1, \dots, a_J) assigns one conditioning position to each generated position.
  • aja_j is the conditioning position assigned to generated position jj.
  • ii ranges from 00 to II, with 00 denoting NULL.
  • eie_i is the conditioning token at position ii.
  • fjf_j is the generated token at position jj.

The conditioning sentence gets an extra position e0=NULLe_0 = \text{NULL} for generated tokens without an aligned conditioning word. This covers some articles, particles, morphological differences, and insertions caused by stylistic or tokenization differences.

Word Alignment

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:

  1. Condition on a generated length JJ. To assign probabilities across lengths, specify a separate distribution for JJ.
  2. For each generated position j=1,…,Jj = 1, \dots, J, choose a conditioning position aj∈{0,1,…,I}a_j \in \{0, 1, \dots, I\} uniformly.
  3. Generate fjf_j from eaje_{a_j} with probability t(fj∣eaj)t(f_j \mid e_{a_j}).

The variables are:

  • JJ is the generated sentence length.
  • jj indexes generated tokens from 11 to JJ.
  • aja_j is the conditioning position assigned to generated position jj.
  • II is the number of conditioning tokens excluding NULL.
  • t(fj∣eaj)t(f_j \mid e_{a_j}) is the lexical probability of emitting fjf_j given eaje_{a_j}.

Because the alignment is uniform over the (I+1)J(I+1)^J possible functions, summing over alignments gives

P(f∣e)=ϵ(I+1)J∏j=1J∑i=0It(fj∣ei),P(\mathbf{f} \mid \mathbf{e}) = \frac{\epsilon}{(I+1)^J} \prod_{j=1}^{J} \sum_{i=0}^{I} t(f_j \mid e_i),

where:

  • ϵ=P(J∣e)\epsilon = P(J\mid\mathbf{e}): the normalized probability of the generated length, held fixed while fitting lexical parameters
  • (I+1)J(I+1)^J: the number of possible alignments, since each generated position independently selects one of I+1I+1 conditioning positions (including NULL)
  • t(fj∣ei)t(f_j \mid e_i): the lexical probability that conditioning token eie_i emits generated token fjf_j
  • e0=NULLe_0 = \text{NULL}: the extra conditioning position that can emit insertions

At fixed generated length JJ, the prior gives each of the (I+1)J(I+1)^J alignments probability 1/(I+1)J1/(I+1)^J. Conditional on an alignment, the generated tokens contribute ∏jt(fj∣eaj)\prod_j t(f_j \mid e_{a_j}). Multiplying gives P(f,a∣e,J)P(\mathbf{f},\mathbf{a}\mid\mathbf{e},J). Sum over alignments and multiply by the normalized length probability P(J∣e)P(J\mid\mathbf{e}) 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 KK allowed lengths, a constant of 1/K1/K gives a uniform length distribution. Brown et al. (1993), §4.1

Each lexical factor depends only on the link aja_j at one generated position. The sum over the possible alignments therefore becomes a product of per-position sums. With I≥1I\geq 1, direct enumeration visits (I+1)J(I+1)^J alignments, exponential in JJ. Model 1 evaluates the per-position sums in O((I+1)J)O((I+1)J). 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]
CollapseExpand
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]
CollapseExpand
Three curves on a logarithmic count axis show alignment counts growing with target length for source lengths 4, 9, and 19.
The number of Model 1 alignments grows exponentially with target sentence length for each fixed source sentence length shown. The factorized E-step avoids enumerating those alignments.

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 a\mathbf{a}, 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 P(a∣e,f;θ(t))P(\mathbf{a} \mid \mathbf{e}, \mathbf{f}; \theta^{(t)}). 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 jj, the posterior probability that its parent is position ii is

P(aj=i∣e,f;θ(t))=t(fj∣ei)∑i′=0It(fj∣ei′).P(a_j = i \mid \mathbf{e}, \mathbf{f}; \theta^{(t)}) = \frac{t(f_j \mid e_i)}{\sum_{i'=0}^{I} t(f_j \mid e_{i'})}.

where:

  • aja_j: the latent conditioning position that generated position jj
  • ii: a candidate conditioning position from 00 through II, including NULL
  • t(fj∣ei)t(f_j \mid e_i): the current lexical probability of emitting fjf_j from eie_i
  • ∑i′=0It(fj∣ei′)\sum_{i'=0}^{I} t(f_j \mid e_{i'}): the sum over all conditioning positions

Let D\mathcal{D} be the corpus of sentence pairs, counted with multiplicity, and let QQ denote the expected complete-data log-likelihood:

Q(θ∣θ(t))=∑(e,f)∈D∑aP(a∣e,f;θ(t))log⁡P(f,a∣e;θ).Q(\theta \mid \theta^{(t)}) = \sum_{(\mathbf{e},\mathbf{f}) \in \mathcal{D}} \sum_{\mathbf{a}} P(\mathbf{a} \mid \mathbf{e}, \mathbf{f}; \theta^{(t)}) \log P(\mathbf{f}, \mathbf{a} \mid \mathbf{e}; \theta).

Since log⁡P(f,a∣e;θ)\log P(\mathbf{f}, \mathbf{a} \mid \mathbf{e}; \theta) is a sum of log⁡t(fj∣eaj)\log t(f_j \mid e_{a_j}) 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:

c(f∣e;e,f)=∑j:fj=f∑i:ei=et(fj∣ei)∑i′=0It(fj∣ei′).c(f \mid e; \mathbf{e}, \mathbf{f}) = \sum_{j: f_j=f} \sum_{i: e_i=e} \frac{t(f_j \mid e_i)}{\sum_{i'=0}^{I} t(f_j \mid e_{i'})}.

The masses for one generated occurrence sum to one across conditioning positions. The count cc aggregates occurrences by word type. If a generated word occurs twice or a conditioning word occupies two positions, each occurrence contributes separately.

where:

  • c(f∣e;e,f)c(f \mid e; \mathbf{e}, \mathbf{f}): expected number of links from type ee to type ff for this sentence pair
  • t(f∣e)t(f \mid e): the current lexical probability of emitting type ff from type ee
  • t(fj∣ei)t(f_j \mid e_i): each contribution uses the tokens at the selected positions
  • ∑i′=0It(fj∣ei′)\sum_{i'=0}^{I} t(f_j \mid e_{i'}): the sum at this generated position includes NULL at i′=0i'=0

The M-step sums these expected counts over the corpus and normalizes each row with positive total count:

t(f∣e)=∑(e,f)∈Dc(f∣e;e,f)∑f′∑(e,f)∈Dc(f′∣e;e,f).t(f \mid e) = \frac{\sum_{(\mathbf{e},\mathbf{f}) \in \mathcal{D}} c(f \mid e; \mathbf{e}, \mathbf{f})}{\sum_{f'} \sum_{(\mathbf{e},\mathbf{f}) \in \mathcal{D}} c(f' \mid e; \mathbf{e}, \mathbf{f})}.

The E-step costs O((I+1)J)O((I+1)J) 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 a(i∣j,I,J)a(i \mid j, I, J), the probability of choosing conditioning position ii for generated position jj:

P(f∣e)=ϵ∏j=1J∑i=0It(fj∣ei) a(i∣j,I,J).P(\mathbf{f} \mid \mathbf{e}) = \epsilon \prod_{j=1}^{J} \sum_{i=0}^{I} t(f_j \mid e_i) \, a(i \mid j, I, J).

The sum still factors over generated positions. Expected counts for aa 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 JJ.

P(f,a∣e,J)=∏j=1Jt(fj∣eaj) p(aj∣aj−1,I),P(\mathbf{f}, \mathbf{a} \mid \mathbf{e},J) = \prod_{j=1}^{J} t(f_j \mid e_{a_j}) \, p(a_j \mid a_{j-1}, I),

One way to parameterize the transition is to assign a nonnegative score c(i−i′)c(i-i\prime) to a displacement and normalize over the available destinations:

p(i∣i′,I)=c(i−i′)∑i′′=0Ic(i′′−i′).p(i \mid i', I) = \frac{c(i - i')}{\sum_{i''=0}^{I} c(i'' - i')}.

The jump score c(i−i′)c(i-i') 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 JJ generated positions are time steps and the I+1I+1 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 O(J(I+1)2)O(J(I+1)^2), compared with (I+1)J(I+1)^J 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 0≤ϕ0≤M0 \le \phi_0 \le M. Brown et al. (1993), section 4.4, equations 31–32.

P(f,a∣e)=(Mϕ0)p0M−ϕ0p1ϕ0[∏i=1Iϕi! n(ϕi∣ei)][∏j=1Jt(fj∣eaj)][∏j: aj≠0d(j∣aj,I,J)].P(\mathbf{f},\mathbf{a}\mid\mathbf{e}) = \binom{M}{\phi_0}p_0^{M-\phi_0}p_1^{\phi_0} \left[\prod_{i=1}^{I}\phi_i!\,n(\phi_i\mid e_i)\right] \left[\prod_{j=1}^{J}t(f_j\mid e_{a_j})\right] \left[\prod_{j:\,a_j\ne 0}d(j\mid a_j,I,J)\right].

The terms distinguish ordinary fertility from the NULL insertion process.

  • e=(e1,…,eI)\mathbf{e}=(e_1,\dots,e_I) is the conditioning sentence and e0e_0 denotes NULL.
  • f=(f1,…,fJ)\mathbf{f}=(f_1,\dots,f_J) is the generated sentence. The alignment index aja_j specifies which conditioning token generated fjf_j.
  • ϕi=#{j:aj=i}\phi_i=\#\{j:a_j=i\} counts the generated words linked to eie_i. The non-NULL count is M=J−ϕ0M=J-\phi_0.
  • n(ϕi∣ei)n(\phi_i\mid e_i) is the fertility distribution for a non-NULL conditioning token.
  • p1p_1 is the probability that an ordinary generated word triggers an additional NULL word. The complementary probability is p0=1−p1p_0=1-p_1.
  • t(fj∣eaj)t(f_j\mid e_{a_j}) supplies the lexical probability for every generated word, including those linked to NULL.
  • d(j∣aj,I,J)d(j\mid a_j,I,J) supplies the placement probability for a word linked to a non-NULL conditioning position.

For each ordinary token, the factor ϕi!\phi_i! counts the interchangeable orderings of its generated words before placement.

  • The leading binomial term gives the probability of drawing exactly ϕ0\phi_0 NULL words from MM opportunities.
  • The placement process fills the remaining slots with NULL words in uniformly random order.
  • The NULL placement probability 1/ϕ0!1/\phi_0! cancels the ϕ0!\phi_0! 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 p1=1/4p_1=1/4, the probability of one NULL insertion is (21)(3/4)(1/4)=3/8\binom21(3/4)(1/4)=3/8. The binomial term accounts for either ordinary word triggering the insertion.

Fertility and Distortion

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 Aef∩AfeA_{\text{ef}} \cap A_{\text{fe}}: keeps only links present in both directions. Relative to union, it cannot increase gold-link recall.
  • Union Aef∪AfeA_{\text{ef}} \cup A_{\text{fe}}: 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 Quality Is Measured Against Sparse Gold Data

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.

Phrase Table

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 [i1,i2][i_1, i_2] and a target span [j1,j2][j_1, j_2]:

  1. At least one alignment point connects the two spans.
  2. Every alignment point whose source index is in [i1,i2][i_1, i_2] has its target index in [j1,j2][j_1, j_2].
  3. Every alignment point whose target index is in [j1,j2][j_1, j_2] has its source index in [i1,i2][i_1, i_2].

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-nn sentence has n(n+1)/2n(n+1)/2 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, eˉ\bar e is the phrase we condition on and fˉ\bar f is its paired phrase. The English–Zeta decoder learns that direction from English to Zeta. A relative-frequency estimate is

p(fˉ∣eˉ)=count(eˉ,fˉ)∑fˉ′count(eˉ,fˉ′).p(\bar{f} \mid \bar{e}) = \frac{\text{count}(\bar{e}, \bar{f})}{\sum_{\bar{f}'} \text{count}(\bar{e}, \bar{f}')}.

A phrase seen once with only one observed partner gets a relative-frequency estimate of 1.0 in that direction. The inverse probability p(eˉ∣fˉ)p(\bar{e}\mid\bar{f}) uses the same pair count and sums over conditioning phrases paired with fˉ\bar f 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 fjf_j, let AjA_j be the set of conditioning positions aligned to it within the phrase pair. Let w(fj∣ei)w(f_j \mid e_i) be the word-level probability estimated from aligned counts. Use the special NULL word when AjA_j is empty. Koehn, Och, and Marcu (2003), section 4.4.

lex(fˉ∣eˉ)=∏j=1∣fˉ∣qj,qj={1∣Aj∣∑i∈Ajw(fj∣ei),Aj≠∅,w(fj∣NULL),Aj=∅.\text{lex}(\bar{f} \mid \bar{e}) = \prod_{j=1}^{|\bar{f}|} q_j,\qquad q_j = \begin{cases}\dfrac{1}{|A_j|}\sum_{i \in A_j} w(f_j \mid e_i), & A_j \ne \varnothing, \\[4pt] w(f_j \mid \text{NULL}), & A_j = \varnothing.\end{cases}

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 w(casa∣house)=0.6w(\text{casa}\mid\text{house})=0.6 and w(la∣NULL)=0.1w(\text{la}\mid\text{NULL})=0.1, the lexical weight is 0.6×0.1=0.060.6 \times 0.1=0.06. 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 nn-gram model from Part II approximates that history with a window of at most n−1n-1 tokens:

PLM(e)=∏k=1KPLM(ek∣ek−1,…,ek−n+1),P_{\mathrm{LM}}(\mathbf{e}) = \prod_{k=1}^{K} P_{\mathrm{LM}}(e_k \mid e_{k-1}, \dots, e_{k-n+1}),

Estimate these bounded-history conditionals from target-side text, use smoothing for unseen nn-grams, and evaluate the model with perplexity. Its memory footprint depends on the vocabulary, retained nn-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 n−1n-1 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 f\mathbf{f} is fixed, and e\mathbf{e} ranges over possible translations.

pλ(e∣f)=exp⁡(∑m=1Mλmhm(e,f))∑e′exp⁡(∑m=1Mλmhm(e′,f)),p_{\boldsymbol{\lambda}}(\mathbf{e} \mid \mathbf{f}) = \frac{\exp\left(\sum_{m=1}^{M} \lambda_m h_m(\mathbf{e}, \mathbf{f})\right)}{\sum_{\mathbf{e}'} \exp\left(\sum_{m=1}^{M} \lambda_m h_m(\mathbf{e}', \mathbf{f})\right)},

where:

  • e\mathbf{e} is a candidate translation.
  • f\mathbf{f} is the fixed input sentence.
  • hm(e,f)h_m(\mathbf{e}, \mathbf{f}): the mm-th feature function, scoring the pair (e,f)(\mathbf{e}, \mathbf{f})
  • λm\lambda_m: the tunable weight of feature mm
  • MM: the number of features
  • The denominator sums the exponential scores over candidate translations e′\mathbf{e}' for the same input f\mathbf{f}.

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.

e^=arg⁡max⁡e∑m=1Mλmhm(e,f).\hat{\mathbf{e}} = \arg\max_{\mathbf{e}} \sum_{m=1}^{M} \lambda_m h_m(\mathbf{e}, \mathbf{f}).

Setting h1=log⁡P(f∣e)h_1 = \log P(\mathbf{f}\mid\mathbf{e}), h2=log⁡P(e)h_2 = \log P(\mathbf{e}) and λ1=λ2=1\lambda_1 = \lambda_2 = 1 recovers the noisy-channel ranking. Summing the score exponentials over the full target support then gives P(f)P(\mathbf{f}) 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 log⁡p(eˉ∣fˉ)\log p(\bar e \mid \bar f) over phrase pairs.
  • Inverse phrase translation score sums log⁡p(fˉ∣eˉ)\log p(\bar f \mid \bar e) over phrase pairs.
  • Direct lexical weighting sums log⁡lex(eˉ∣fˉ)\log \text{lex}(\bar e \mid \bar f) over phrase pairs.
  • Inverse lexical weighting sums log⁡lex(fˉ∣eˉ)\log \text{lex}(\bar f \mid \bar e) over phrase pairs.
  • Language model score: ∑klog⁡P(ek∣ek−n+1k−1)\sum_k \log P(e_k \mid e_{k-n+1}^{k-1}), possibly several LMs for different corpora.
  • Distortion: a penalty on reordering, usually the sum of jump distances −∑∣i(k)−iend(k−1)−1∣-\sum |i^{(k)} - i^{(k-1)}_{\text{end}} - 1|.
  • 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 λ\boldsymbol{\lambda} 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 1−BLEU1-\text{BLEU} 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 λm\lambda_m, each candidate translation's score is a linear function of λm\lambda_m. The best-scoring candidate therefore changes only at finitely many breakpoints, and the error as a function of λm\lambda_m 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 NN translations, the score of candidate ii is aiλm+bia_i \lambda_m + b_i, so any two candidates cross at most once, giving at most N2N^2 breakpoints. Sort them, evaluate the metric on each interval, keep the best, and repeat for the next coordinate.

MERT Is Non-Convex, Unstable, and Easy to Overfit

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.
Coverage Vector

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 kk 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 e\mathbf{e} and our miniature target language "Zeta" as the target f\mathbf{f}.

Training corpus, two sentence pairs:

  1. e=(the,cat)\mathbf{e} = (\text{the}, \text{cat}), f=(ze,mika)\mathbf{f} = (\text{ze}, \text{mika})
  2. e=(the,dog)\mathbf{e} = (\text{the}, \text{dog}), f=(ze,voso)\mathbf{f} = (\text{ze}, \text{voso})

The target vocabulary has three words, so we initialize t(f∣e)=1/3t(f \mid e) = 1/3 everywhere.

Iteration 1, E-step. For sentence 1, the source is extended to (NULL,the,cat)(\text{NULL}, \text{the}, \text{cat}). For the target word "ze":

denom=t(ze∣NULL)+t(ze∣the)+t(ze∣cat)=13+13+13=1,\text{denom} = t(\text{ze}\mid\text{NULL}) + t(\text{ze}\mid\text{the}) + t(\text{ze}\mid\text{cat}) = \tfrac13 + \tfrac13 + \tfrac13 = 1,

so each source position receives posterior mass 13\tfrac13. 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 13\tfrac13.

Iteration 1, M-step. Sum the counts. For source word "the", it appears in both sentences and receives 13\tfrac13 from "ze" and 13\tfrac13 from the other target word in each, for a total of 43\tfrac43. Its count for "ze" is 23\tfrac23, so

t(ze∣the)=2/34/3=0.5,t(mika∣the)=t(voso∣the)=0.25.t(\text{ze} \mid \text{the}) = \frac{2/3}{4/3} = 0.5, \qquad t(\text{mika}\mid\text{the}) = t(\text{voso}\mid\text{the}) = 0.25.

Similarly t(ze∣cat)=0.5t(\text{ze}\mid\text{cat}) = 0.5, t(mika∣cat)=0.5t(\text{mika}\mid\text{cat}) = 0.5, and the same for "dog". The model has already learned something: the cross-lexical entries dropped from 0.3330.333 to 0.250.25, and the "the"↔"ze" link rose to 0.50.5.

Iteration 2, E-step. Now the posteriors are no longer uniform. For "ze" in sentence 1, the denominator is

t(ze∣NULL)+t(ze∣the)+t(ze∣cat)=0.5+0.5+0.5=1.5,t(\text{ze}\mid\text{NULL}) + t(\text{ze}\mid\text{the}) + t(\text{ze}\mid\text{cat}) = 0.5 + 0.5 + 0.5 = 1.5,

so each source position still gets a posterior of 0.5/1.5=130.5 / 1.5 = \tfrac13. For "mika" the denominator is

t(mika∣NULL)+t(mika∣the)+t(mika∣cat)=0.25+0.25+0.5=1.0,t(\text{mika}\mid\text{NULL}) + t(\text{mika}\mid\text{the}) + t(\text{mika}\mid\text{cat}) = 0.25 + 0.25 + 0.5 = 1.0,

so "cat" gets posterior mass 0.5/1.0=0.50.5 / 1.0 = 0.5 and the other two get 0.25/1.0=0.250.25 / 1.0 = 0.25 each. The alignment is sharpening exactly where it should.

Iteration 2, M-step. For "the", the two occurrences of "ze" each contribute 13\tfrac13. "Mika" and "voso" each contribute 14\tfrac14 in their respective sentences. The row total is 23+14+14=76\tfrac23+\tfrac14+\tfrac14=\tfrac76, so

t(ze∣the)=2/37/6=47,t(mika∣the)=t(voso∣the)=314.t(\text{ze}\mid\text{the}) = \frac{2/3}{7/6} = \tfrac47, \qquad t(\text{mika}\mid\text{the}) = t(\text{voso}\mid\text{the}) = \tfrac{3}{14}.

"Cat" appears only in sentence 1, where "ze" contributes 13\tfrac13 and "mika" contributes 12\tfrac12. Dividing by their total, 56\tfrac56, gives t(mika∣cat)=35t(\text{mika}\mid\text{cat})=\tfrac35 and t(ze∣cat)=25t(\text{ze}\mid\text{cat})=\tfrac25.

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]
CollapseExpand
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]
CollapseExpand
Line plot shows t(ze | the) and t(mika | cat) rising and t(mika | the) falling from the same initial probability of one-third.
Lexical probabilities before each EM update for three word pairs in the two-sentence example. The two recurring correspondences gain probability, while t(mika | the) loses probability.

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: ino follows 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]
CollapseExpand
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, gold

Now we enumerate every combination, which gives 88 unique sentence pairs.

PythonIn [9]
CollapseExpand
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]
CollapseExpand
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 tt table.

PythonIn [11]
CollapseExpand
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_table

For 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 t(f∣e)t(f\mid e). This is the maximum-posterior alignment under Model 1.

PythonIn [12]
CollapseExpand
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, f1

Now the training loop. We record alignment F1 against gold before each parameter update, so iteration kk reports the quality of the model produced by kk previous updates.

PythonIn [13]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
Precision, recall and F1 start at zero. After two updates the curves level off near 0.776, 0.648 and 0.706 respectively.
Training alignment precision, recall, and F1 measured before each EM update on the English–Zeta corpus. F1 goes from zero to about 0.706 after two updates and stays there for the remaining recorded iterations.

Step 3: Train the Reverse Direction and Symmetrize

In this pipeline, we train a reverse model, t(English∣Zeta)t(\text{English} \mid \text{Zeta}), 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]
CollapseExpand
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]
CollapseExpand
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 links

Now compare the five candidate alignments against gold on the training set.

PythonIn [18]
CollapseExpand
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] = f1
ConsoleOut [19]
CollapseExpand
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]
CollapseExpand
Five F1 bars show the intersection at about 0.786, both single directions and grow-diag-final-and at about 0.706, and union at about 0.641.
Alignment F1 against gold for five strategies on the synthetic training set. Intersection scores highest at about 0.786. Grow-diag-final-and and both directional models are tied at about 0.706.

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]
CollapseExpand
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 pairs

A 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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
Histogram of the number of candidate translations per source phrase.
Distribution of the number of candidate target translations per source phrase in the extracted phrase table. Most source phrases have one candidate. A few have as many as three. The decoder combines phrase scores with language model and reordering scores when choosing among candidates.

Step 5: Build the Language Model

A bigram model with add-α\alpha smoothing scores partial hypotheses and full sentences. For α>0\alpha>0, 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]
CollapseExpand
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]
CollapseExpand
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 0.20.2, 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 0.20.2, adding a phrase raises the score by 0.20.2 when the other feature totals stay fixed.

PythonIn [28]
CollapseExpand
@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_score

Three 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]
CollapseExpand
hypotheses = []
references = []
for en, ze, _ in test:
    output, _score = decode(en, phrase_table, lm, WEIGHTS)
    hypotheses.append(output)
    references.append(ze)
ConsoleOut [30]
CollapseExpand
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 nn-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]
CollapseExpand
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]
CollapseExpand
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 nn-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 t(f∣e)t(f\mid e) matrix that EM produced. Each row is an English word, each column a Zeta word, and the gold links are overlaid.

PythonIn [33]
CollapseExpand
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]
CollapseExpand
Heatmap of lexical translation probabilities with gold alignment links marked as circles.
IBM Model 1 lexical translation probabilities for an English-Zeta sentence pair. Each row is an English source word and each column a Zeta target word. Open circles mark the gold alignment. Repeated determiners share lexical scores across positions. The strong cell at the intersection of “sees” and “tira” shows that Model 1 can learn the verb correspondence without representing the verb’s change in position.

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 nn-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: e^=arg⁡max⁡e[log⁡P(f∣e)+log⁡P(e)]\hat{\mathbf{e}} = \arg\max_{\mathbf{e}} [\log P(\mathbf{f}\mid\mathbf{e}) + \log P(\mathbf{e})]. 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 O((I+1)J)O((I+1)J) 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 t(fj∣ei)t(f_j\mid e_i). 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

Question 1 of 80 of 8 completed
For a fixed source sentence f with positive probability, which noisy-channel score combines the channel likelihood and the target-language prior?
Join the discussionAsk a question or share what you learned.

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!

A different angle
All writing
Language AI Handbook · Vol. 8

Parallel Data Mining and Quality Control

Mine parallel text from the web, align sentences, filter candidate pairs, and screen for training-evaluation contamination in translation corpora.

53 min read
Language AI Handbook · Vol. 8

Neural Machine Translation

Train a toy encoder-decoder Transformer for machine translation. Compare decoding policies, inspect cross-attention weights, and diagnose NMT failure modes.

49 min read
Language AI Handbook · Vol. 8

Translation Evaluation Beyond BLEU

Learn how translation evaluation goes beyond BLEU, covering MQM, human protocols, learned metrics, terminology checks, and paired bootstrap uncertainty.

52 min read

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026statisticalmachine, author = {Michael Brenndoerfer}, title = {Statistical Machine Translation Foundations}, year = {2026}, url = {https://mbrenndoerfer.com/writing/statistical-machine-translation-foundations-ibm-models-phrase-based-decoding}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-12-03} }
APAAcademic
Michael Brenndoerfer (2026). Statistical Machine Translation Foundations. Retrieved from https://mbrenndoerfer.com/writing/statistical-machine-translation-foundations-ibm-models-phrase-based-decoding
MLAAcademic
Michael Brenndoerfer. "Statistical Machine Translation Foundations." 2026. Web. December 3, 2026. <https://mbrenndoerfer.com/writing/statistical-machine-translation-foundations-ibm-models-phrase-based-decoding>.
CHICAGOAcademic
Michael Brenndoerfer. "Statistical Machine Translation Foundations." Accessed December 3, 2026. https://mbrenndoerfer.com/writing/statistical-machine-translation-foundations-ibm-models-phrase-based-decoding.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Statistical Machine Translation Foundations'. Available at: https://mbrenndoerfer.com/writing/statistical-machine-translation-foundations-ibm-models-phrase-based-decoding (Accessed: December 3, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Statistical Machine Translation Foundations. https://mbrenndoerfer.com/writing/statistical-machine-translation-foundations-ibm-models-phrase-based-decoding
Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy