Algorithm Search⌘K

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 e=e1…ele = e_1 \ldots e_l of one language is translated as a sentence f=f1…fmf = f_1 \ldots f_m of another. Each source word fjf_j picks a target position aj∈{0,…,l}a_j \in \{0, \ldots, l\} uniformly at random, where e0e_0 is the null word, and is then drawn from a word translation table t(fj∣eaj)t(f_j \mid e_{a_j}). The only parameters are the table tt. The hidden choices a=a1…ama = a_1 \ldots a_m are a word alignment, and EM on a parallel corpus learns tt without any aligned data. The log likelihood is concave in tt, so EM reaches a global maximum, but the maximizer need not be unique.

The machine

Variables. A pair is a source sentence f=f1…fmf = f_1 \ldots f_m and a target sentence e=e1…ele = e_1 \ldots e_l, with the null word e0e_0 in front of ee. An alignment is a=a1…ama = a_1 \ldots a_m with aj∈{0,…,l}a_j \in \{0, \ldots, l\}: source word jj is generated by target word aja_j, and aj=0a_j = 0 means that it has no partner. This is the direction of Brown et al., who translate from French ff to English ee and model p(f∣e)p(f \mid e). 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 ee (including the null word) and every source word ff, the table holds t(f∣e)≥0t(f \mid e) \ge 0, with ∑ft(f∣e)=1\sum_f t(f \mid e) = 1 for each ee. A length distribution ε=p(m∣e)\varepsilon = p(m \mid e) completes the model. It is a constant for EM, and the code leaves it out.

How it makes a sentence. Given ee: draw the length mm with probability ε\varepsilon; for j=1,…,mj = 1, \ldots, m draw aja_j uniformly from {0,…,l}\{0, \ldots, l\}, then draw fjf_j from the row t(⋅∣eaj)t(\cdot \mid e_{a_j}). So

p(f,a∣e)=ε(l+1)m∏j=1mt(fj∣eaj).p(f, a \mid e) = \frac{\varepsilon}{(l + 1)^m} \prod_{j=1}^{m} t(f_j \mid e_{a_j}).

Standing assumptions. The position aja_j does not depend on jj, on ll beyond the uniform choice, or on the other positions. So the model ignores word order completely: if you permute the words of ff or of ee, the probability of the pair does not change. Each fjf_j depends only on the one word eaje_{a_j}.

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 tt. The M step sets t(f∣e)t(f \mid e) to the expected count of (f,e)(f, e) divided by the expected count of ee.

  1. IBM-MODEL-1-EM(corpus, rounds)
  2. 1t(f | e) ← 1 / |V_F| for every source word f and target word e
  3. 2repeat rounds times
  4. 3c(f, e) ← 0 for every pair of words
  5. 4for each pair (f, e) in the corpus and each j ← 1 to m do
  6. 5Z ← t(f_j | e_0) + t(f_j | e_1) + .. + t(f_j | e_l)
  7. 6for i ← 0 to l do c(f_j, e_i) ← c(f_j, e_i) + t(f_j | e_i) / Z
  8. 7for each target word e: t(f | e) ← c(f, e) / Σ_f' c(f', e)
  9. 8return t

Line L5 is the normalizer of the posterior of aja_j. Line L6 adds that posterior to the counts, so each source word spreads exactly one unit of count over the l+1l + 1 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 tt 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 t(English∣German)t(\text{English} \mid \text{German}). There is no null word, and tt starts uniform at 1/41/4 over the 4 English words. The likelihood column is ∏j1l∑it(fj∣ei)\prod_j \frac{1}{l} \sum_i t(f_j \mid e_i) over the corpus, without ε\varepsilon.

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 t(the∣das)=1/(1+1/2+1/2)=1/2t(\text{the} \mid \text{das}) = 1 / (1 + 1/2 + 1/2) = 1/2. In round 2 the other values of the "das" and "Buch" rows are 2/11 each, and t(a∣ein)=4/7t(\text{a} \mid \text{ein}) = 4/7. The likelihood after two rounds is 114511401/17014071844114511401 / 17014071844 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

p(f∣e)=∑ap(f,a∣e)=ε(l+1)m∏j=1m∑i=0lt(fj∣ei).p(f \mid e) = \sum_a p(f, a \mid e) = \frac{\varepsilon}{(l + 1)^m} \prod_{j=1}^{m} \sum_{i=0}^{l} t(f_j \mid e_i).

The second form holds because the sum over the (l+1)m(l + 1)^m alignments is a sum of products in which each factor depends on one aja_j only, so it factors by the distributive law. The same factoring gives the posterior of each link separately:

p(aj=i∣f,e)=t(fj∣ei)∑i′=0lt(fj∣ei′),p(a_j = i \mid f, e) = \frac{t(f_j \mid e_i)}{\sum_{i'=0}^{l} t(f_j \mid e_{i'})},

and the positions a1,…,ama_1, \ldots, a_m are independent given ff and ee. The size of a pair is measured by mm and ll, and one step is one arithmetic operation on real numbers, as on the real RAM.

Task Direct method With the factoring
p(f∣e)p(f \mid e) sum over (l+1)m(l + 1)^m alignments, Θ(m(l+1)m)\Theta(m (l + 1)^m) product of mm sums, Θ(lm)\Theta(l m)
expected link counts (E step) the same sum, once per link lines L4 to L6, Θ(lm)\Theta(l m)
best alignment arg⁡max⁡ap(a∣f,e)\arg\max_a p(a \mid f, e) maximum over (l+1)m(l + 1)^m alignments best ii for each jj alone, Θ(lm)\Theta(l m)
one EM round on a corpus Θ(∑lm)\Theta(\sum l m) over the pairs, plus the size of tt

The product over jj underflows in double precision for long sentences: 200 words with a probability of 1/501/50 each give 50−20050^{-200}, below the smallest double. The code therefore sums ln⁡∑it(fj∣ei)\ln \sum_i t(f_j \mid e_i) 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 p(f∣e)p(f \mid e) of the noisy channel model of translation. A language model p(e)p(e) supplies the word order that Model 1 ignores.
  • IBM Model 2. Model 2 replaces the uniform 1/(l+1)1/(l + 1) with an alignment distribution a(i∣j,l,m)a(i \mid j, l, m). Model 1 is the case of a uniform aa. Model 2 is usually trained from the Model 1 table.
  • HMM alignment model. The HMM alignment model makes aja_j depend on aj−1a_{j-1} through the jump aj−aj−1a_j - a_{j-1}. With all jumps equally likely, it is Model 1 again.
  • fast_align. fast_align is a Model 2 with one parameter λ\lambda that pulls the links to the diagonal. With λ=0\lambda = 0 it is a Model 1 in which the null word has a fixed probability p0p_0.
  • 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 l+1l + 1 rows t(⋅∣ei)t(\cdot \mid e_i) 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). ∑a∏jt(fj∣eaj)=∏j∑it(fj∣ei)\sum_a \prod_j t(f_j \mid e_{a_j}) = \prod_j \sum_i t(f_j \mid e_i), by the distributive law (Brown et al. 1993, Appendix B.3). So the likelihood, the E step and the best alignment each cost Θ(lm)\Theta(l m) per pair instead of a sum or maximum over (l+1)m(l + 1)^m 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 ε\varepsilon terms, the log likelihood is ∑pairs∑jln⁡∑it(fj∣ei)−mln⁡(l+1)\sum_{\text{pairs}} \sum_j \ln \sum_i t(f_j \mid e_i) - m \ln(l + 1). Each inner sum is linear in tt, 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 tt 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 t(a∣x)=t(b∣y)=pt(a \mid x) = t(b \mid y) = p and t(b∣x)=t(a∣y)=1−pt(b \mid x) = t(a \mid y) = 1 - p gives the maximum likelihood 1/41/4 and is a fixed point of EM. With p=4/5p = 4/5 the best alignment is a-x, b-y, and with p=1/5p = 1/5 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 mm, ∑fp(f∣e)=ε\sum_f p(f \mid e) = \varepsilon. 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.

ibm_model_1.pyI0RawGitHub
# 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

  1. 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)
  2. Toutanova and Galley 2011, the likelihood is not strictly concave, so it can have many global maxima, and the start changes the alignments
  3. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/Q63VWQ/text.yaml