Algorithm Search⌘K

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 t(f∣e)t(f \mid e) of IBM Model 1 and replaces the uniform choice of the aligned position with an alignment distribution a(i∣j,l,m)a(i \mid j, l, m): the probability that source word jj is generated by target word ii, 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 Θ(lm)\Theta(l m) 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 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. 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. The model is written in the direction p(f∣e)p(f \mid e) of Brown et al. The reverse direction is a different model and gives different alignments.

Parameters.

  • t(f∣e)t(f \mid e), with ∑ft(f∣e)=1\sum_f t(f \mid e) = 1 for each target word ee and for the null word;
  • a(i∣j,l,m)a(i \mid j, l, m) for 0≤i≤l0 \le i \le l and 1≤j≤m1 \le j \le m, with ∑i=0la(i∣j,l,m)=1\sum_{i=0}^{l} a(i \mid j, l, m) = 1 for each (j,l,m)(j, l, m);
  • a length distribution ε=p(m∣e)\varepsilon = p(m \mid e), a constant for EM.

How it makes a sentence. Given ee, draw mm; for each jj, draw aja_j from a(⋅∣j,l,m)a(\cdot \mid j, l, m) and then fjf_j from t(⋅∣eaj)t(\cdot \mid e_{a_j}). So

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

Standing assumptions. The positions a1,…,ama_1, \ldots, a_m are independent of each other given the lengths. Each aja_j depends on jj, ll and mm only, not on the words. Each fjf_j depends only on eaje_{a_j}. With a(i∣j,l,m)=1/(l+1)a(i \mid j, l, m) = 1/(l + 1) the model is Model 1.

Training. EM is the Model 1 algorithm with one more table of counts.

  1. IBM-MODEL-2-EM(corpus, rounds)
  2. 1t ← the table of Model 1 after a few rounds; a(i | j, l, m) ← 1 / (l + 1)
  3. 2repeat rounds times
  4. 3c(f, e) ← 0 and c(i | j, l, m) ← 0 for all arguments
  5. 4for each pair (f, e) in the corpus and each j ← 1 to m do
  6. 5Z ← Σ_{i=0..l} a(i | j, l, m) t(f_j | e_i)
  7. 6for 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
  8. 7t(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)
  9. 8return t and a

Line L5 is the normalizer of the posterior of aja_j, 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 (j,l,m)(j, l, m) that does not occur in the corpus keeps its row of aa; 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 aa. All three pairs have l=m=2l = m = 2, so only the four values a(i∣j,2,2)a(i \mid j, 2, 2) are used, and by symmetry a(1∣1,2,2)=a(2∣2,2,2)a(1 \mid 1, 2, 2) = a(2 \mid 2, 2, 2).

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 tt exactly as round 3 of Model 1 does, because aa 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 tt with equal weights, so the two per-word sums add up to at most 2, each pair has probability at most 1/41/4, and the corpus at most 1/64=0.01561/64 = 0.0156.

What it counts

The probability of a pair is

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

because each factor of p(f,a∣e)p(f, a \mid e) depends on one aja_j only, and the sum over the (l+1)m(l + 1)^m alignments factors by the distributive law. The posterior of each link is p(aj=i∣f,e)=a(i∣j,l,m) t(fj∣ei)/Zjp(a_j = i \mid f, e) = a(i \mid j, l, m) \, t(f_j \mid e_i) / Z_j, and the aja_j are independent given the pair. One step is one arithmetic operation on real numbers, as on the real RAM.

Task Cost per pair
p(f∣e)p(f \mid e) Θ(lm)\Theta(l m) instead of Θ(m(l+1)m)\Theta(m (l + 1)^m)
E step (lines L4 to L6) Θ(lm)\Theta(l m)
best alignment Θ(lm)\Theta(l m): the best ii for each jj alone

The table aa has one row for every (j,l,m)(j, l, m) in the corpus. For sentences up to length LL that is Θ(L4)\Theta(L^4) 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 jj underflows; the code sums logarithms of the inner sums.

Relation to other models

  • IBM Model 1. Model 1 is Model 2 with a(i∣j,l,m)=1/(l+1)a(i \mid j, l, m) = 1/(l + 1) (Brown et al. 1993, Section 4.2).
  • fast_align. fast_align fixes the shape of aa: a null probability p0p_0 and, for the other positions, weights exp⁡(−λ∣i/l−j/m∣)\exp(-\lambda |i/l - j/m|). One number λ\lambda replaces the whole table, and its normalizer has a closed form.
  • HMM alignment model. The HMM alignment model makes aja_j depend on aj−1a_{j-1} instead of on jj. This models the tendency of neighbouring words to move together, which Model 2 cannot express. Its E step is the forward-backward algorithm, Θ(l2m)\Theta(l^2 m) per pair.
  • IBM Model 3. Model 3 adds fertilities and turns aa around into a distortion d(j∣i,l,m)d(j \mid i, l, m). 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 Θ(lm)\Theta(l m) 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 (t(a∣x)=t(b∣y)=1t(a \mid x) = t(b \mid y) = 1 and a(1∣1)=a(2∣2)=1a(1 \mid 1) = a(2 \mid 2) = 1) and the crossed solution (t(a∣y)=t(b∣x)=1t(a \mid y) = t(b \mid x) = 1 and a(2∣1)=a(1∣2)=1a(2 \mid 1) = a(1 \mid 2) = 1) both give likelihood 1. Their midpoint, with every value 1/21/2, gives (1/2)2=1/4(1/2)^2 = 1/4. A concave function cannot be lower at a midpoint than at both ends, so the log likelihood is not concave in (t,a)(t, a) together. The product a⋅ta \cdot t in each term is the cause.
  • The start matters. The midpoint above is a fixed point of EM. A small push of tt towards one solution sends EM to that solution: in the tests, a push of ±0.05\pm 0.05 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 tt starts from Model 1, whose likelihood is concave, and aa starts uniform (Brown et al. 1993).
  • Not deficient. Every row of aa and of tt 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.

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

  1. 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)
  2. 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)
  3. 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.

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/Z3VPZP/text.yaml