Modelcore
IBM model 2
Also called IBM alignment model 2.
IBM model 1 plus an alignment distribution over source positions that depends on the target position and the sentence lengths.
IBM Model 2 is the second of the translation models of Brown et al. (1993). It keeps the word translation table of IBM Model 1 and replaces the uniform choice of the aligned position with an alignment distribution : the probability that source word is generated by target word , given the two sentence lengths. So the model can learn that words near the same relative position tend to be translations, which Model 1 cannot. The sum over all alignments still factors, so EM costs per sentence pair. Unlike Model 1, the log likelihood is not concave, and the result depends on the start, which is usually the trained Model 1 table.
The machine
Variables. A pair is a source sentence and a target sentence , with the null word . An alignment is with : source word is generated by target word . The model is written in the direction of Brown et al. The reverse direction is a different model and gives different alignments.
Parameters.
- , with for each target word and for the null word;
- for and , with for each ;
- a length distribution , a constant for EM.
How it makes a sentence. Given , draw ; for each , draw from and then from . So
Standing assumptions. The positions are independent of each other given the lengths. Each depends on , and only, not on the words. Each depends only on . With the model is Model 1.
Training. EM is the Model 1 algorithm with one more table of counts.
IBM-MODEL-2-EM(corpus, rounds)- 1
t ← the table of Model 1 after a few rounds; a(i | j, l, m) ← 1 / (l + 1) - 2
repeat rounds times - 3
c(f, e) ← 0 and c(i | j, l, m) ← 0 for all arguments - 4
for each pair (f, e) in the corpus and each j ← 1 to m do - 5
Z ← Σ_{i=0..l} a(i | j, l, m) t(f_j | e_i) - 6
for i ← 0 to l do p ← a(i | j, l, m) t(f_j | e_i) / Z; c(f_j, e_i) += p; c(i | j, l, m) += p - 7
t(f | e) ← c(f, e) / Σ_f' c(f', e); a(i | j, l, m) ← c(i | j, l, m) / Σ_i' c(i' | j, l, m) - 8
return t and a
Line L5 is the normalizer of the posterior of , and line L6 adds that posterior to both tables of counts. Line L7 is the M step: each table is normalized over its own outcome. A shape that does not occur in the corpus keeps its row of ; the code keeps the old values for it.
Example. On the three pairs of the Model 1 page (the house | das Haus, the book | das Buch, a book | ein Buch, no null word), start from the Model 1 table after two rounds and a uniform . All three pairs have , so only the four values are used, and by symmetry .
| round | a(1 | 1, 2, 2) | t(the | das) | t(house | Haus) | likelihood |
|---|---|---|---|---|
| 0 | 1/2 | 7/11 = 0.6364 | 4/7 = 0.5714 | 0.006730 |
| 1 | 45671/64206 = 0.7113 | 0.7479 | 0.6534 | 0.032437 |
| 2 | 0.9016 | 0.9286 | 0.8538 | 0.306533 |
| 3 | 0.9914 | 0.9956 | 0.9833 | 0.902577 |
Round 1 moves exactly as round 3 of Model 1 does, because is still uniform during its E step. After that, the alignment table learns that the first word goes with the first word and the second with the second, and the likelihood grows towards 1. Model 1 cannot get near 1 on this corpus. Under Model 1 the two source words of a pair use the same two rows of with equal weights, so the two per-word sums add up to at most 2, each pair has probability at most , and the corpus at most .
What it counts
The probability of a pair is
because each factor of depends on one only, and the sum over the alignments factors by the distributive law. The posterior of each link is , and the are independent given the pair. One step is one arithmetic operation on real numbers, as on the real RAM.
| Task | Cost per pair |
|---|---|
| instead of | |
| E step (lines L4 to L6) | |
| best alignment | : the best for each alone |
The table has one row for every in the corpus. For sentences up to length that is numbers, and most of them are seen in few pairs. This is the weak point that fast_align removes with one parameter. For long sentences the product over underflows; the code sums logarithms of the inner sums.
Relation to other models
- IBM Model 1. Model 1 is Model 2 with (Brown et al. 1993, Section 4.2).
- fast_align. fast_align fixes the shape of : a null probability and, for the other positions, weights . One number replaces the whole table, and its normalizer has a closed form.
- HMM alignment model. The HMM alignment model makes depend on instead of on . This models the tendency of neighbouring words to move together, which Model 2 cannot express. Its E step is the forward-backward algorithm, per pair.
- IBM Model 3. Model 3 adds fertilities and turns around into a distortion . Its E step does not factor, and Brown et al. use Model 2 to find the starting alignments for it.
- Noisy channel. Any of these models can serve as the translation model of the noisy channel model of translation.
Known results in the model
- The sum factors (theorem). The likelihood, the E step and the best alignment cost per pair, for the same reason as in Model 1. The tests check the E step, the likelihood and the best alignment against all alignments on random small corpora, in exact rational arithmetic.
- EM never decreases the likelihood (theorem). The tests check this round by round.
- The log likelihood is not concave (theorem, by example). Take the single pair a b | x y without a null word. The diagonal solution ( and ) and the crossed solution ( and ) both give likelihood 1. Their midpoint, with every value , gives . A concave function cannot be lower at a midpoint than at both ends, so the log likelihood is not concave in together. The product in each term is the cause.
- The start matters. The midpoint above is a fixed point of EM. A small push of towards one solution sends EM to that solution: in the tests, a push of gives likelihood above 0.99 after 30 rounds, with the alignment a-x, b-y for one sign and a-y, b-x for the other. In practice starts from Model 1, whose likelihood is concave, and starts uniform (Brown et al. 1993).
- Not deficient. Every row of and of sums to 1, so for each length the model gives all its probability to real strings.
- Measured quality. Dyer et al. (2013, Table 2) report alignment error rates for Model 2, fast_align and Model 4 on French-English and Chinese-English test sets. Model 2 had the highest error rate of the three on both sets. These are measurements on their data.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ibm-model-2/. The authors are listed in prov/Z3VPZP.jsonl.
"""IBM Model 2 and its EM training (Brown et al. 1993, Section 4.2).
A pair is (f, e): the generated sentence f = f_1 .. f_m and the given sentence
e = e_1 .. e_l. With null=True, the null word e_0 = NULL is put in front of e
and positions run over 0 .. l; without it they run over 1 .. l.
p(f, a | e) = eps * prod_j a(a_j | j, l, m) t(f_j | e_{a_j})
p(f | e) = eps * prod_j sum_i a(i | j, l, m) t(f_j | e_i)
t maps (f_word, e_word) to t(f_word | e_word); a maps (i, j, l, m) to
a(i | j, l, m). The constant eps does not change EM and is left out. All
arithmetic follows the type of the values: with Fraction values it is exact.
"""
import math
from collections import defaultdict
from fractions import Fraction
from typing import Dict, List, Sequence, Tuple
NULL = "<null>"
Pair = Tuple[Sequence[str], Sequence[str]] # (f, e)
TTable = Dict[Tuple[str, str], Fraction]
ATable = Dict[Tuple[int, int, int, int], Fraction]
def _given(e: Sequence[str], null: bool) -> List[str]:
return ([NULL] if null else []) + list(e)
def _positions(l: int, null: bool) -> range:
return range(0 if null else 1, l + 1)
def uniform_t(corpus: Sequence[Pair], null: bool = False) -> TTable:
vf = sorted({x for f, _ in corpus for x in f})
ve = sorted({y for _, e in corpus for y in _given(e, null)})
return {(x, y): Fraction(1, len(vf)) for x in vf for y in ve}
def uniform_a(corpus: Sequence[Pair], null: bool = False) -> ATable:
"""a(i | j, l, m) = 1 / (number of positions) for every shape (l, m) in the corpus."""
a: ATable = {}
for f, e in corpus:
l, m = len(e), len(f)
pos = _positions(l, null)
for j in range(1, m + 1):
for i in pos:
a[(i, j, l, m)] = Fraction(1, len(pos))
return a
def model1_t(corpus: Sequence[Pair], rounds: int, null: bool = False) -> TTable:
"""Model 1 training: Model 2 EM with a held uniform. Used as the start of Model 2."""
t, a = uniform_t(corpus, null), uniform_a(corpus, null)
for _ in range(rounds):
t, _ = em_step(corpus, t, a, null)
return t
def expected_counts(corpus: Sequence[Pair], t: TTable, a: ATable, null: bool = False):
"""The E step: expected link counts c(f, e) and position counts c(i | j, l, m)."""
ct: Dict[Tuple[str, str], Fraction] = defaultdict(Fraction)
ca: Dict[Tuple[int, int, int, int], Fraction] = defaultdict(Fraction)
for f, e in corpus: # @line L4
l, m = len(e), len(f)
es = _given(e, True) # es[i] is e_i, es[0] is NULL
pos = _positions(l, null)
for j, x in enumerate(f, start=1):
z = sum(a[(i, j, l, m)] * t.get((x, es[i]), 0) for i in pos) # @line L5
for i in pos: # @line L6
p = a[(i, j, l, m)] * t.get((x, es[i]), 0) / z
ct[(x, es[i])] += p
ca[(i, j, l, m)] += p
return ct, ca
def em_step(corpus: Sequence[Pair], t: TTable, a: ATable, null: bool = False) -> Tuple[TTable, ATable]:
"""One EM round; returns the new t and the new a."""
ct, ca = expected_counts(corpus, t, a, null) # @line L3
tot_t: Dict[str, Fraction] = defaultdict(Fraction)
for (x, y), v in ct.items():
tot_t[y] += v
tot_a: Dict[Tuple[int, int, int], Fraction] = defaultdict(Fraction)
for (i, j, l, m), v in ca.items():
tot_a[(j, l, m)] += v
new_t = {k: (ct[k] / tot_t[k[1]] if tot_t[k[1]] else t[k]) for k in t} # @line L7
new_a = {k: (ca[k] / tot_a[k[1:]] if tot_a[k[1:]] else a[k]) for k in a}
return new_t, new_a
def likelihood(corpus: Sequence[Pair], t: TTable, a: ATable, null: bool = False):
"""The corpus likelihood without eps, as a product."""
p = Fraction(1)
for f, e in corpus:
l, m = len(e), len(f)
es = _given(e, True)
for j, x in enumerate(f, start=1):
p *= sum(a[(i, j, l, m)] * t.get((x, es[i]), 0) for i in _positions(l, null))
return p
def log_likelihood(corpus: Sequence[Pair], t: TTable, a: ATable, null: bool = False) -> float:
"""The same in nats, as a sum of logs, so long sentences do not underflow."""
s = 0.0
for f, e in corpus:
l, m = len(e), len(f)
es = _given(e, True)
for j, x in enumerate(f, start=1):
s += math.log(sum(a[(i, j, l, m)] * t.get((x, es[i]), 0) for i in _positions(l, null)))
return s
def train(corpus: Sequence[Pair], rounds: int, null: bool = False, model1_rounds: int = 5,
t: TTable = None, a: ATable = None) -> Tuple[TTable, ATable, list]:
"""EM for Model 2. t starts from Model 1 training unless given; a starts uniform unless given.
Returns t, a and the likelihoods before each round and at the end.
"""
if t is None:
t = model1_t(corpus, model1_rounds, null) # @line L1
if a is None:
a = uniform_a(corpus, null)
history = [likelihood(corpus, t, a, null)]
for _ in range(rounds): # @line L2
t, a = em_step(corpus, t, a, null)
history.append(likelihood(corpus, t, a, null))
return t, a, history # @line L8
def viterbi_alignment(f: Sequence[str], e: Sequence[str], t: TTable, a: ATable, null: bool = False) -> List[int]:
"""The best a_j for each j, independently; the smallest i wins a tie."""
l, m = len(e), len(f)
es = _given(e, True)
out = []
for j, x in enumerate(f, start=1):
pos = list(_positions(l, null))
out.append(max(pos, key=lambda i: (a[(i, j, l, m)] * t.get((x, es[i]), 0), -i)))
return out
test_ibm_model_2.py 173 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ibm-model-2/. The authors are listed in prov/Z3VPZP.jsonl.
import math
import random
from collections import defaultdict
from fractions import Fraction as F
from itertools import product
from ibm_model_2 import (
NULL,
em_step,
expected_counts,
likelihood,
log_likelihood,
model1_t,
train,
uniform_a,
uniform_t,
viterbi_alignment,
)
KOEHN = [(["the", "house"], ["das", "Haus"]), (["the", "book"], ["das", "Buch"]), (["a", "book"], ["ein", "Buch"])]
def random_corpus(rng, n, vf, ve, lmax):
return [([f"f{rng.randrange(vf)}" for _ in range(rng.randint(1, lmax))],
[f"e{rng.randrange(ve)}" for _ in range(rng.randint(1, lmax))]) for _ in range(n)]
def normalize(d, group):
tot = defaultdict(F)
for k, v in d.items():
tot[group(k)] += v
return {k: v / tot[group(k)] for k, v in d.items()}
def random_tables(rng, corpus, null):
t = {k: F(rng.randint(1, 9)) for k in uniform_t(corpus, null)}
a = {k: F(rng.randint(1, 9)) for k in uniform_a(corpus, null)}
return normalize(t, lambda k: k[1]), normalize(a, lambda k: k[1:])
def positions(l, null):
return range(0 if null else 1, l + 1)
def brute(corpus, t, a, null):
"""Likelihood and expected counts by a sum over every alignment."""
ct, ca, total = defaultdict(F), defaultdict(F), F(1)
for f, e in corpus:
l, m = len(e), len(f)
es = [NULL] + list(e)
joint = {}
for al in product(positions(l, null), repeat=m):
p = F(1)
for j, i in enumerate(al, start=1):
p *= a[(i, j, l, m)] * t[(f[j - 1], es[i])]
joint[al] = p
z = sum(joint.values())
total *= z
for al, p in joint.items():
for j, i in enumerate(al, start=1):
ct[(f[j - 1], es[i])] += p / z
ca[(i, j, l, m)] += p / z
return total, ct, ca
def nonzero(d):
return {k: v for k, v in d.items() if v}
def test_e_step_against_all_alignments() -> None:
rng = random.Random(21)
for null in (False, True):
corpus = random_corpus(rng, 3, 3, 3, 4)
t, a = random_tables(rng, corpus, null)
total, bt, ba = brute(corpus, t, a, null)
ct, ca = expected_counts(corpus, t, a, null)
assert nonzero(ct) == nonzero(bt)
assert nonzero(ca) == nonzero(ba)
assert likelihood(corpus, t, a, null) == total
def test_rows_sum_to_one_and_likelihood_never_decreases() -> None:
rng = random.Random(22)
for null in (False, True):
corpus = random_corpus(rng, 3, 3, 3, 3)
# exact: one Model 1 round and one Model 2 round (exact fractions grow long over many rounds)
t, a, hist = train(corpus, 1, null, model1_rounds=1)
assert all(y >= x for x, y in zip(hist, hist[1:]))
for table, group in ((t, lambda k: k[1]), (a, lambda k: k[1:])):
sums = defaultdict(F)
for k, v in table.items():
assert 0 <= v <= 1
sums[group(k)] += v
assert set(sums.values()) == {F(1)}
# floats: ten rounds from a random start, with a tolerance for rounding
tf, af = random_tables(rng, corpus, null)
tf = {k: float(v) for k, v in tf.items()}
af = {k: float(v) for k, v in af.items()}
_, _, hist = train(corpus, 10, null, t=tf, a=af)
assert all(y >= x * (1 - 1e-12) for x, y in zip(hist, hist[1:]))
def test_uniform_a_gives_model_1() -> None:
# with a uniform, the first Model 2 round moves t exactly as Model 1 does
t0, a0 = uniform_t(KOEHN), uniform_a(KOEHN)
t1, a1 = em_step(KOEHN, t0, a0)
assert t1 == model1_t(KOEHN, 1)
assert t1[("the", "das")] == F(1, 2)
t2 = model1_t(KOEHN, 2)
assert t2[("the", "das")] == F(7, 11) and t2[("house", "Haus")] == F(4, 7)
# Model 2 then learns positions: in every pair the first word goes with the first word
t, a, hist = train(KOEHN, 3, model1_rounds=2)
assert a[(1, 1, 2, 2)] > F(1, 2) and a[(2, 2, 2, 2)] > F(1, 2)
assert all(y >= x for x, y in zip(hist, hist[1:]))
assert hist[-1] > likelihood(KOEHN, t2, a0)
def test_not_concave() -> None:
# one pair a b | x y: the diagonal and the crossed solutions both give likelihood 1,
# and their midpoint gives 1/4, so the log likelihood is not concave in (t, a)
corpus = [(["a", "b"], ["x", "y"])]
one, zero = F(1), F(0)
t_diag = {("a", "x"): one, ("b", "x"): zero, ("a", "y"): zero, ("b", "y"): one}
t_cross = {("a", "x"): zero, ("b", "x"): one, ("a", "y"): one, ("b", "y"): zero}
a_diag = {(1, 1, 2, 2): one, (2, 1, 2, 2): zero, (1, 2, 2, 2): zero, (2, 2, 2, 2): one}
a_cross = {(1, 1, 2, 2): zero, (2, 1, 2, 2): one, (1, 2, 2, 2): one, (2, 2, 2, 2): zero}
assert likelihood(corpus, t_diag, a_diag) == 1
assert likelihood(corpus, t_cross, a_cross) == 1
t_mid = {k: (t_diag[k] + t_cross[k]) / 2 for k in t_diag}
a_mid = {k: (a_diag[k] + a_cross[k]) / 2 for k in a_diag}
assert likelihood(corpus, t_mid, a_mid) == F(1, 4)
# the midpoint is a fixed point of EM, and a small push decides which maximum EM reaches
assert em_step(corpus, t_mid, a_mid) == (t_mid, a_mid)
# (in floats: exact fractions grow too long over many rounds)
for eps, want in ((0.05, [1, 2]), (-0.05, [2, 1])):
t = {k: float(v) + (eps if k in (("a", "x"), ("b", "y")) else -eps) for k, v in t_mid.items()}
t, a, hist = train(corpus, 30, t=t, a={k: float(v) for k, v in a_mid.items()})
assert hist[-1] > 0.99
assert viterbi_alignment(["a", "b"], ["x", "y"], t, a) == want
def test_viterbi_against_brute_force() -> None:
rng = random.Random(23)
for null in (False, True):
corpus = random_corpus(rng, 5, 3, 3, 4)
t, a = random_tables(rng, corpus, null)
for f, e in corpus:
l, m = len(e), len(f)
es = [NULL] + list(e)
def score(al):
p = F(1)
for j, i in enumerate(al, start=1):
p *= a[(i, j, l, m)] * t[(f[j - 1], es[i])]
return p
best = max(score(al) for al in product(positions(l, null), repeat=m))
assert score(viterbi_alignment(f, e, t, a, null)) == best
def test_long_sentence_log_space() -> None:
m = 200
f = [f"f{j % 50}" for j in range(m)]
e = [f"e{j % 50}" for j in range(m)]
corpus = [(f, e)]
t = {k: float(v) for k, v in uniform_t(corpus).items()}
a = {k: float(v) for k, v in uniform_a(corpus).items()}
per_word = [sum(a[(i, j, m, m)] * t[(f[j - 1], e[i - 1])] for i in range(1, m + 1)) for j in range(1, m + 1)]
assert math.prod(per_word) == 0.0
assert math.isclose(log_likelihood(corpus, t, a), -m * math.log(50), rel_tol=1e-12)
References
- Brown, Della Pietra, Della Pietra and Mercer 1993, Section 4.2 (Model 2, its EM updates, and Model 1 as the special case of uniform alignment probabilities)
- Dyer, Chahuneau and Smith 2013, the reparameterization of the alignment distribution of Model 2, and Table 2 (alignment error rates of Model 2, the reparameterized model and Model 4)
- Philipp Koehn, Statistical Machine Translation, Cambridge University Press, 2010, Chapter 4, Section 4.4 (the higher IBM models)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag Z3VPZP Edit this page History Report an error Markdown