Modelcore
IBM model 1
Also called IBM alignment model 1.
A translation model in which each source word is generated by a uniformly chosen target word. EM reaches a global maximum of its concave likelihood, but the maximizer need not be unique.
IBM Model 1 is the simplest of the five translation models of Brown et al. (1993). It gives the probability that a sentence of one language is translated as a sentence of another. Each source word picks a target position uniformly at random, where is the null word, and is then drawn from a word translation table . The only parameters are the table . The hidden choices are a word alignment, and EM on a parallel corpus learns without any aligned data. The log likelihood is concave in , so EM reaches a global maximum, but the maximizer need not be unique.
The machine
Variables. A pair is a source sentence and a target sentence , with the null word in front of . An alignment is with : source word is generated by target word , and means that it has no partner. This is the direction of Brown et al., who translate from French to English and model . The two directions give different alignments: in this direction every source word has exactly one link, but a target word can have many.
Parameters. For every target word (including the null word) and every source word , the table holds , with for each . A length distribution completes the model. It is a constant for EM, and the code leaves it out.
How it makes a sentence. Given : draw the length with probability ; for draw uniformly from , then draw from the row . So
Standing assumptions. The position does not depend on , on beyond the uniform choice, or on the other positions. So the model ignores word order completely: if you permute the words of or of , the probability of the pair does not change. Each depends only on the one word .
Training. Given a corpus of pairs, EM alternates two steps. The E step finds the expected number of links between each source word and each target word, under the current . The M step sets to the expected count of divided by the expected count of .
IBM-MODEL-1-EM(corpus, rounds)- 1
t(f | e) ← 1 / |V_F| for every source word f and target word e - 2
repeat rounds times - 3
c(f, e) ← 0 for every pair of words - 4
for each pair (f, e) in the corpus and each j ← 1 to m do - 5
Z ← t(f_j | e_0) + t(f_j | e_1) + .. + t(f_j | e_l) - 6
for i ← 0 to l do c(f_j, e_i) ← c(f_j, e_i) + t(f_j | e_i) / Z - 7
for each target word e: t(f | e) ← c(f, e) / Σ_f' c(f', e) - 8
return t
Line L5 is the normalizer of the posterior of . Line L6 adds that posterior to the counts, so each source word spreads exactly one unit of count over the target words. Line L7 is the M step: it follows from the Lagrange condition for a maximum of the expected complete log likelihood with each row of summing to 1. A word pair that never occurs in the same sentence pair keeps a count of 0. If a row has no count at all, the code keeps the old row.
Example. Take the three pairs of Koehn (2010, Section 4.2): the house | das Haus, the book | das Buch, a book | ein Buch. Here the English words are generated from the German words, so the table is . There is no null word, and starts uniform at over the 4 English words. The likelihood column is over the corpus, without .
| round | t(the | das) | t(house | Haus) | t(book | Buch) | t(book | ein) | likelihood |
|---|---|---|---|---|---|
| 0 | 1/4 | 1/4 | 1/4 | 1/4 | 1/4096 = 0.000244 |
| 1 | 1/2 | 1/2 | 1/2 | 1/2 | 81/16384 = 0.004944 |
| 2 | 7/11 | 4/7 | 7/11 | 3/7 | 0.006730 |
| 3 | 29435/39357 | 164/251 | 29435/39357 | 87/251 | 0.008697 |
In round 1, the word "the" occurs with "das" in two pairs and gets the full count 1 from them, while "house" and "book" get 1/2 each from "das", so . In round 2 the other values of the "das" and "Buch" rows are 2/11 each, and . The likelihood after two rounds is exactly. The table moves towards the word pairs the-das, house-Haus, book-Buch and a-ein, because "das" and "Buch" occur twice and explain "the" and "book" better than the words that occur once. The tests compute every value of this table in exact rational arithmetic.
What it counts
The model assigns to a pair the probability
The second form holds because the sum over the alignments is a sum of products in which each factor depends on one only, so it factors by the distributive law. The same factoring gives the posterior of each link separately:
and the positions are independent given and . The size of a pair is measured by and , and one step is one arithmetic operation on real numbers, as on the real RAM.
| Task | Direct method | With the factoring |
|---|---|---|
| sum over alignments, | product of sums, | |
| expected link counts (E step) | the same sum, once per link | lines L4 to L6, |
| best alignment | maximum over alignments | best for each alone, |
| one EM round on a corpus | over the pairs, plus the size of |
The product over underflows in double precision for long sentences: 200 words with a probability of each give , below the smallest double. The code therefore sums for the log likelihood, which needs no log-sum-exp because each inner sum has positive terms of moderate size.
Relation to other models
- Noisy channel. Model 1 is the simplest translation model of the noisy channel model of translation. A language model supplies the word order that Model 1 ignores.
- IBM Model 2. Model 2 replaces the uniform with an alignment distribution . Model 1 is the case of a uniform . Model 2 is usually trained from the Model 1 table.
- HMM alignment model. The HMM alignment model makes depend on through the jump . With all jumps equally likely, it is Model 1 again.
- fast_align. fast_align is a Model 2 with one parameter that pulls the links to the diagonal. With it is a Model 1 in which the null word has a fixed probability .
- IBM Model 3 and later. Model 3 adds a fertility for each target word. Its training starts from Models 1 and 2, because its own E step has no factoring.
- Mixture models. Each source word is drawn from an equal-weight mixture of the rows of its sentence pair. EM for Model 1 is EM for the components of such mixtures, with the weights fixed and the components shared across the corpus, as in a Gaussian mixture with discrete components and known weights.
Known results in the model
- The sum factors (theorem). , by the distributive law (Brown et al. 1993, Appendix B.3). So the likelihood, the E step and the best alignment each cost per pair instead of a sum or maximum over alignments. The tests check the E step and the likelihood against the sum over all alignments.
- EM never decreases the likelihood (theorem). This holds for every EM algorithm, and the tests check it round by round on random corpora.
- The log likelihood is concave (theorem). Up to the constant terms, the log likelihood is . Each inner sum is linear in , the logarithm of a positive linear function is concave, and a sum of concave functions is concave. The set of tables whose rows sum to 1 is convex. So every local maximum is a global maximum, and the set of maximizers is convex. Brown et al. (1993, Appendix B) use this to argue that EM reaches the global maximum from any start with all positive.
- The maximizer need not be unique. The log likelihood is not strictly concave, so many tables can reach the same maximum, and they can imply different alignments (Toutanova and Galley 2011). This corrects the claim of Brown et al. that the maximum is unique. For the single pair a b | x y without a null word, every table with and gives the maximum likelihood and is a fixed point of EM. With the best alignment is a-x, b-y, and with it is a-y, b-x. So the alignment EM returns depends on the start.
- Not deficient. Model 1 gives all its probability to real strings: for each length , . Models 3 and 4 do not have this property.
- Order free. The probability of a pair does not change under a permutation of the words of either sentence. The model therefore cannot tell a crossed alignment from a monotone one. Model 2, the HMM model and fast_align add this information.
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-1/. The authors are listed in prov/Q63VWQ.jsonl.
"""IBM Model 1 and its EM training (Brown et al. 1993, Section 4.1).
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.
The table t maps (f_word, e_word) to t(f_word | e_word).
p(f | e) = eps / (l + 1)^m * prod_j sum_{i=0..l} t(f_j | e_i) (with NULL)
p(f | e) = eps / l^m * prod_j sum_{i=1..l} t(f_j | e_i) (without)
The constant eps (the length probability) does not change EM, and the
functions here leave it out. All arithmetic follows the type of t: with
fractions.Fraction values every step 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)
Table = Dict[Tuple[str, str], Fraction]
def _given(e: Sequence[str], null: bool) -> List[str]:
return ([NULL] if null else []) + list(e)
def uniform_table(corpus: Sequence[Pair], null: bool = False) -> Table:
"""t(f | e) = 1 / |V_F| for every source word f and every given word e."""
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 expected_counts(corpus: Sequence[Pair], t: Table, null: bool = False) -> Dict[Tuple[str, str], Fraction]:
"""The E step: the expected number of links between f_j and e_i, summed over the corpus."""
c: Dict[Tuple[str, str], Fraction] = defaultdict(Fraction)
for f, e in corpus: # @line L4
es = _given(e, null)
for x in f:
z = sum(t.get((x, y), 0) for y in es) # @line L5
for y in es: # @line L6
c[(x, y)] += t.get((x, y), 0) / z
return c
def em_step(corpus: Sequence[Pair], t: Table, null: bool = False) -> Table:
"""One EM iteration; returns the new table."""
c = expected_counts(corpus, t, null) # @line L3
total: Dict[str, Fraction] = defaultdict(Fraction)
for (x, y), v in c.items():
total[y] += v
new = {key: (c[key] / total[key[1]] if total[key[1]] else t[key]) for key in t} # @line L7
return new
def likelihood(corpus: Sequence[Pair], t: Table, null: bool = False):
"""The corpus likelihood without eps, as a product (exact with Fraction values)."""
p = Fraction(1)
for f, e in corpus:
es = _given(e, null)
for x in f:
p *= Fraction(sum(t.get((x, y), 0) for y in es)) / len(es)
return p
def log_likelihood(corpus: Sequence[Pair], t: Table, null: bool = False) -> float:
"""The same in nats, as a sum of logs, so long corpora do not underflow."""
s = 0.0
for f, e in corpus:
es = _given(e, null)
for x in f:
s += math.log(sum(t.get((x, y), 0) for y in es)) - math.log(len(es))
return s
def train(corpus: Sequence[Pair], iterations: int, null: bool = False, t: Table = None) -> Tuple[Table, list]:
"""Run EM from t (uniform if None). Returns t and the likelihoods before each step and at the end."""
if t is None:
t = uniform_table(corpus, null) # @line L1
history = [likelihood(corpus, t, null)]
for _ in range(iterations): # @line L2
t = em_step(corpus, t, null)
history.append(likelihood(corpus, t, null))
return t, history # @line L8
def viterbi_alignment(f: Sequence[str], e: Sequence[str], t: Table, null: bool = False) -> List[int]:
"""The best a_j for each j, independently; the smallest i wins a tie.
Positions are 0 .. l with NULL (0 is NULL), or 1 .. l without it.
"""
es = _given(e, null)
first = 0 if null else 1
return [first + max(range(len(es)), key=lambda k: (t.get((x, es[k]), 0), -k)) for x in f]
test_ibm_model_1.py 158 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ibm-model-1/. The authors are listed in prov/Q63VWQ.jsonl.
import math
import random
from collections import defaultdict
from fractions import Fraction as F
from itertools import product
from ibm_model_1 import (
NULL,
em_step,
expected_counts,
likelihood,
log_likelihood,
train,
uniform_table,
viterbi_alignment,
)
# Koehn's example: English (the generated side) given German, no null word.
KOEHN = [(["the", "house"], ["das", "Haus"]), (["the", "book"], ["das", "Buch"]), (["a", "book"], ["ein", "Buch"])]
def test_check_values() -> None:
t, hist = train(KOEHN, 3)
assert hist[0] == F(1, 4096)
assert hist[1] == F(81, 16384)
assert hist[2] == F(114511401, 17014071844)
assert math.isclose(float(hist[2]), 0.0067304, rel_tol=1e-4)
assert math.isclose(float(hist[3]), 0.0086974, rel_tol=1e-4)
t1 = em_step(KOEHN, uniform_table(KOEHN))
assert t1[("the", "das")] == F(1, 2) and t1[("house", "Haus")] == F(1, 2)
t2 = em_step(KOEHN, t1)
assert t2[("the", "das")] == F(7, 11) and t2[("book", "Buch")] == F(7, 11)
assert t2[("house", "Haus")] == F(4, 7) and t2[("the", "Haus")] == F(3, 7)
assert t2[("a", "ein")] == F(4, 7) and t2[("book", "ein")] == F(3, 7)
for key in [("a", "Buch"), ("the", "Buch"), ("book", "das"), ("house", "das")]:
assert t2[key] == F(2, 11)
assert t[("the", "das")] == F(29435, 39357)
assert t[("house", "Haus")] == F(164, 251)
def test_rows_sum_to_one() -> None:
t, _ = train(KOEHN, 2, null=True)
rows = defaultdict(F)
for (x, y), v in t.items():
rows[y] += v
assert 0 <= v <= 1
assert set(rows.values()) == {F(1)}
assert NULL in rows
def brute_counts(corpus, t, null):
"""Expected link counts by a sum over all (l + 1)^m (or l^m) alignments."""
c = defaultdict(F)
for f, e in corpus:
es = ([NULL] if null else []) + list(e)
joint = {}
for a in product(range(len(es)), repeat=len(f)):
p = F(1)
for j, i in enumerate(a):
p *= t[(f[j], es[i])]
joint[a] = p
z = sum(joint.values())
for a, p in joint.items():
for j, i in enumerate(a):
c[(f[j], es[i])] += p / z
return c
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 random_table(rng, corpus, null):
t = uniform_table(corpus, null)
for key in t:
t[key] = F(rng.randint(1, 9))
rows = defaultdict(F)
for (x, y), v in t.items():
rows[y] += v
return {(x, y): v / rows[y] for (x, y), v in t.items()}
def test_e_step_against_all_alignments() -> None:
rng = random.Random(4)
for null in (False, True):
corpus = random_corpus(rng, 3, 3, 3, 4)
t = random_table(rng, corpus, null)
fast = expected_counts(corpus, t, null)
slow = brute_counts(corpus, t, null)
assert {k: v for k, v in fast.items() if v} == {k: v for k, v in slow.items() if v}
# the likelihood is the sum over all alignments, divided by (l + 1)^m or l^m
total = F(1)
for f, e in corpus:
es = ([NULL] if null else []) + list(e)
s = F(0)
for a in product(range(len(es)), repeat=len(f)):
p = F(1)
for j, i in enumerate(a):
p *= t[(f[j], es[i])]
s += p
total *= s / F(len(es)) ** len(f)
assert likelihood(corpus, t, null) == total
def test_likelihood_never_decreases() -> None:
rng = random.Random(9)
for null in (False, True):
corpus = random_corpus(rng, 4, 3, 3, 3)
_, hist = train(corpus, 4, null)
assert all(b >= a for a, b in zip(hist, hist[1:]))
def test_log_likelihood_is_concave() -> None:
rng = random.Random(12)
corpus = random_corpus(rng, 5, 4, 4, 4)
for _ in range(20):
t1, t2 = random_table(rng, corpus, True), random_table(rng, corpus, True)
mid = {k: (t1[k] + t2[k]) / 2 for k in t1}
lhs = log_likelihood(corpus, mid, True)
rhs = (log_likelihood(corpus, t1, True) + log_likelihood(corpus, t2, True)) / 2
assert lhs >= rhs - 1e-12
def test_maximizer_not_unique() -> None:
# one pair (a b | x y): every t with t(a | x) = p, t(a | y) = 1 - p has likelihood 1/4,
# the maximum, and EM does not move it, so the start decides the alignment
corpus = [(["a", "b"], ["x", "y"])]
for p in (F(1, 5), F(1, 2), F(4, 5)):
t = {("a", "x"): p, ("b", "x"): 1 - p, ("a", "y"): 1 - p, ("b", "y"): p}
assert likelihood(corpus, t) == F(1, 4)
assert em_step(corpus, t) == t
t_left = {("a", "x"): F(4, 5), ("b", "x"): F(1, 5), ("a", "y"): F(1, 5), ("b", "y"): F(4, 5)}
t_right = {("a", "x"): F(1, 5), ("b", "x"): F(4, 5), ("a", "y"): F(4, 5), ("b", "y"): F(1, 5)}
assert viterbi_alignment(["a", "b"], ["x", "y"], t_left) == [1, 2]
assert viterbi_alignment(["a", "b"], ["x", "y"], t_right) == [2, 1]
def test_viterbi_and_null() -> None:
t, _ = train(KOEHN, 3)
assert viterbi_alignment(["the", "house"], ["das", "Haus"], t) == [1, 2]
assert viterbi_alignment(["a", "book"], ["ein", "Buch"], t) == [1, 2]
tn, _ = train(KOEHN, 3, null=True)
assert viterbi_alignment(["the", "house"], ["das", "Haus"], tn, null=True) == [1, 2]
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)]
t = uniform_table([(f, e)])
tf = {k: float(v) for k, v in t.items()}
per_word = [sum(tf[(x, y)] for y in e) / len(e) for x in f]
assert math.prod(per_word) == 0.0
assert math.isclose(log_likelihood([(f, e)], tf), -m * math.log(50), rel_tol=1e-12)
References
- Brown, Della Pietra, Della Pietra and Mercer 1993, Section 4.1 (Model 1 and its EM updates) and Appendix B.3 (the sum over alignments as a product of sums, and the concavity argument)
- Toutanova and Galley 2011, the likelihood is not strictly concave, so it can have many global maxima, and the start changes the alignments
- Philipp Koehn, Statistical Machine Translation, Cambridge University Press, 2010, Chapter 4, Section 4.2 (Model 1, the EM algorithm and the das Haus example)
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 Q63VWQ Edit this page History Report an error Markdown