Algorithm Search⌘K

Modeladvanced

IBM model 3

Also called fertility-based alignment model.

A translation model in which each source word has a fertility, the number of target words it produces, plus distortion; trained by approximate EM.

IBM Model 3 is the third of the translation models of Brown et al. (1993). It adds two ideas to IBM Model 2. Each target word eie_i has a fertility φi\varphi_i, the number of source words it generates, drawn from a table n(φ∣ei)n(\varphi \mid e_i). The positions of the generated words come from a distortion table d(j∣i,l,m)d(j \mid i, l, m). A null word e0e_0 adds source words that no target word explains. The model can express that one English word becomes two French words, which Models 1 and 2 can only do by chance. The price is that the sum over alignments no longer factors: EM needs a sum over all (l+1)m(l + 1)^m alignments, and Brown et al. approximate it with a set of good alignments found by hill climbing. The model is also deficient: it gives some probability to outputs that are not strings.

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\}, in the direction p(f∣e)p(f \mid e) of Brown et al. The fertility of eie_i in aa is φi=∣{j:aj=i}∣\varphi_i = |\{j : a_j = i\}|, and φ0\varphi_0 is the number of source words aligned to the null word. The reverse direction is a different model with different alignments.

Parameters.

  • t(f∣e)t(f \mid e), the word translation table, with a row for the null word;
  • n(φ∣e)n(\varphi \mid e), the fertility table, a distribution over φ=0,1,2,…\varphi = 0, 1, 2, \ldots for each target word;
  • d(j∣i,l,m)d(j \mid i, l, m), the distortion table, a distribution over source positions j=1,…,mj = 1, \ldots, m for each (i,l,m)(i, l, m) with i≥1i \ge 1;
  • p1p_1, with p0=1−p1p_0 = 1 - p_1: after each word generated by a real target word, one null word is added with probability p1p_1.

How it makes a sentence. Given ee:

  1. for each i=1,…,li = 1, \ldots, l, draw φi\varphi_i from n(⋅∣ei)n(\cdot \mid e_i), and let φ′=φ1+⋯+φl\varphi' = \varphi_1 + \cdots + \varphi_l;
  2. draw φ0\varphi_0 from the binomial distribution with φ′\varphi' trials and success probability p1p_1, and set m=φ′+φ0m = \varphi' + \varphi_0;
  3. for each i≥1i \ge 1, draw φi\varphi_i words from t(⋅∣ei)t(\cdot \mid e_i), and draw φ0\varphi_0 words from t(⋅∣e0)t(\cdot \mid e_0);
  4. for each word of each eie_i with i≥1i \ge 1, draw its position from d(⋅∣i,l,m)d(\cdot \mid i, l, m), independently;
  5. put the null words into the φ0\varphi_0 positions that are left, in one of the φ0!\varphi_0! orders, each with the same probability.

Step 4 can put two words in the same position. Then the output is not a string, and the model has lost that probability.

The probability of a pair and an alignment. Summing over the orders inside each fertility group gives Equation 32 of Brown et al.:

p(f,a∣e)=(m−φ0φ0)p0 m−2φ0p1 φ0∏i=1lφi! n(φi∣ei)∏j=1mt(fj∣eaj)∏j:aj≠0d(j∣aj,l,m).p(f, a \mid e) = \binom{m - \varphi_0}{\varphi_0} p_0^{\,m - 2\varphi_0} p_1^{\,\varphi_0} \prod_{i=1}^{l} \varphi_i! \, n(\varphi_i \mid e_i) \prod_{j=1}^{m} t(f_j \mid e_{a_j}) \prod_{j : a_j \ne 0} d(j \mid a_j, l, m).

The factor φi!\varphi_i! counts the orders of the words of eie_i that give the same alignment. The binomial factor is 0 if 2φ0>m2 \varphi_0 > m: there are at most as many null words as real ones.

Training: the approximate E step. The E step needs the posterior over all alignments, and no factoring is known. Brown et al. collect the counts over a set SS of alignments that hold most of the posterior mass.

  1. MODEL-3-E-STEP(f, e)
  2. 1a⁰ ← the best alignment of a simpler model (here: the best i for each j of t times d)
  3. 2a ← HILL-CLIMB(a⁰, no peg)
  4. 3S ← {a} ∪ N(a)
  5. 4for i ← 0 to l and j ← 1 to m do
  6. 5b ← HILL-CLIMB(a⁰ with a_j set to i, peg (i, j))
  7. 6S ← S ∪ {b} ∪ N(b)
  8. 7for each a' in S: w(a') ← p(f, a' | e)
  9. 8add w(a') / Σ_{a'' in S} w(a'') to the counts of t, n, d, p₀ and p₁ of every a' in S
  10. HILL-CLIMB(a, peg)
  11. 9repeat
  12. 10b ← the best alignment in N(a) that keeps the peg, or a if none is better
  13. 11if b = a then return a
  14. 12a ← b

N(a)N(a) is the neighbourhood of aa: every alignment that differs from aa by one move (one aja_j changed) or one swap (the values of aja_j and aj′a_{j'} exchanged). A move changes two fertilities; a swap changes none. Line L5 is pegging: it fixes the link (i,j)(i, j) and climbs from there, so that for every link SS contains a good alignment that has it. The M step is the usual one: each table is normalized over its outcome, and p1=c1/(c0+c1)p_1 = c_1 / (c_0 + c_1), where c1c_1 is the expected number of null words and c0c_0 the expected value of m−2φ0m - 2 \varphi_0. Brown et al. start the climb from alignments of Model 2; the code starts from the best link for each source word under t⋅dt \cdot d, which has the same role.

Tie rule. Line L10 replaces aa only on a strict increase, and among equal neighbours it keeps the first in the order moves, then swaps.

Example. Take e=xe = x with n(2∣x)=1n(2 \mid x) = 1, no null words (p1=0p_1 = 0) and d(1∣1,1,2)=d(2∣1,1,2)=1/2d(1 \mid 1, 1, 2) = d(2 \mid 1, 1, 2) = 1/2. The model always makes two words, and step 4 puts them in the same position with probability 1/21/2. Summed over all alignments and all words, Equation 32 gives 1/21/2, not 1: half of the probability is lost. In a larger case in the tests, with two target words, fertilities up to 2 and p1=1/4p_1 = 1/4, the lost part is 0.3880.388. The tests compare the sum of Equation 32 over every length and alignment with an independent enumeration of the five steps above, in exact rational arithmetic.

What it counts

The model assigns p(f∣e)=∑ap(f,a∣e)p(f \mid e) = \sum_a p(f, a \mid e), a sum over (l+1)m(l + 1)^m alignments. One step is one arithmetic operation on real numbers, as on the real RAM.

Task Cost
p(f,a∣e)p(f, a \mid e) for one alignment, Equation 32 Θ(l+m)\Theta(l + m)
p(f∣e)p(f \mid e) or the exact E step, by enumeration Θ((l+1)m(l+m))\Theta((l + 1)^m (l + m))
neighbourhood N(a)N(a) mlm l moves and at most m(m−1)/2m (m - 1) / 2 swaps
one climbing step of line L10 O(m(l+m))O(m (l + m)) neighbours; with ratio updates each costs O(1)O(1)
pegging, lines L4 to L6 (l+1)m(l + 1) m climbs

No polynomial algorithm is known for the exact sum or for the best alignment. By the results of Udupa and Maji (2006) below, none exists for the best alignment unless P = NP, and none exists for the sum unless P = #P. The probability of one alignment of a long pair underflows in double precision; the code also gives ln⁡p(f,a∣e)\ln p(f, a \mid e) as a sum of logarithms.

Relation to other models

  • IBM Models 1 and 2. Model 1 and Model 2 have no fertility. Their alignments are independent across jj, so their sums factor. Brown et al. train Model 1, then Model 2, and use Model 2 to start Model 3.
  • IBM Models 4 and 5. Model 4 replaces the distortion d(j∣i,l,m)d(j \mid i, l, m) with a distribution over the jump from the position of the previous group, which keeps groups of words together. Model 4 is still deficient. Model 5 places each word only in a vacant position, so it is not deficient (Brown et al. 1993, Sections 4.5 to 4.7).
  • HMM alignment model. The HMM alignment model models jumps between neighbouring source words but has no fertility. Its E step is exact by forward-backward, so it is often used in place of Model 2 to start Models 3 and 4.
  • Search. The approximate E step is local search on the alignments with the move and swap neighbourhood. It finds a local maximum, not always the best alignment.
  • Noisy channel. Model 3 can serve as the translation model of the noisy channel model of translation.

Known results in the model

  • Equation 32 (theorem). Summing the five steps over the φi!\varphi_i! orders that give the same alignment gives Equation 32 (Brown et al. 1993, Section 4.4). The tests check it against an enumeration of the steps.
  • Deficiency (theorem). Models 3 and 4 give part of their probability to outputs with two words in one position, so ∑fp(f∣e)<1\sum_f p(f \mid e) < 1 in general. Model 5 is not deficient (Brown et al. 1993, Section 4.5). The example above loses half of its probability.
  • The best alignment is hard (theorem). Udupa and Maji (2006) prove that finding the Viterbi alignment of Models 3, 4 and 5 is NP-hard, and that computing the expectations of the E step and the conditional probability p(f∣e)p(f \mid e) is #P-complete. So the approximation of lines L1 to L8 is not a shortcut around an easy problem.
  • Hill climbing finds local maxima only (measurement). In the tests, on 80 random pairs with m≤4m \le 4, l≤3l \le 3 and random parameters, hill climbing alone stopped below the best alignment 7 times. In all 80 cases the pegged set SS contained the best alignment. Pegging gives no such guarantee in general; this is a measurement on small random cases.
  • Approximate EM. Because the counts come from SS and not from all alignments, the training is not EM in the exact sense, and the likelihood can decrease. With the exact E step, which the code also offers for small pairs, it is EM and the likelihood never decreases; the tests check this.

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_3.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ibm-model-3/. The authors are listed in prov/2CTGQ5.jsonl.

"""IBM Model 3 (Brown et al. 1993, Section 4.4, Equation 32), its exact E step by
enumeration for small pairs, and the approximate E step by hill climbing and pegging.

A pair is (f, e): the generated sentence f = f_1 .. f_m and the given sentence
e = e_1 .. e_l, with the null word e_0. An alignment is a list a of length m with
a[j - 1] = a_j in 0 .. l. The parameters are a dict with

    t[(f_word, e_word)]   t(f | e), e_word may be NULL
    n[(phi, e_word)]      n(phi | e) for phi = 0 .. phi_max
    d[(j, i, l, m)]       d(j | i, l, m) for i >= 1
    p1                    the probability of a null word after each real word

    p(f, a | e) = C(m - phi_0, phi_0) p0^(m - 2 phi_0) p1^phi_0
                  * prod_{i>=1} phi_i! n(phi_i | e_i)
                  * prod_j t(f_j | e_{a_j}) * prod_{j: a_j > 0} d(j | a_j, l, m)

The arithmetic follows the type of the values: with Fraction values it is exact.
"""

import math
from collections import defaultdict
from fractions import Fraction
from itertools import product
from typing import Dict, List, Sequence, Set, Tuple

NULL = "<null>"
Pair = Tuple[Sequence[str], Sequence[str]]


def fertilities(a: Sequence[int], l: int) -> List[int]:
    phi = [0] * (l + 1)
    for i in a:
        phi[i] += 1
    return phi


def structure_prob(a: Sequence[int], e: Sequence[str], m: int, params: dict):
    """Equation 32 without the factors t: the fertility, null and distortion part."""
    l = len(e)
    phi = fertilities(a, l)
    phi0 = phi[0]
    if 2 * phi0 > m:
        return 0 * params["p1"]
    p1 = params["p1"]
    p0 = 1 - p1
    w = math.comb(m - phi0, phi0) * p0 ** (m - 2 * phi0) * p1 ** phi0
    for i in range(1, l + 1):
        w *= math.factorial(phi[i]) * params["n"].get((phi[i], e[i - 1]), 0)
    for j, i in enumerate(a, start=1):
        if i > 0:
            w *= params["d"].get((j, i, l, m), 0)
    return w


def prob(f: Sequence[str], e: Sequence[str], a: Sequence[int], params: dict):
    """p(f, a | e), Equation 32."""
    es = [NULL] + list(e)
    w = structure_prob(a, e, len(f), params)
    for j, i in enumerate(a):
        w *= params["t"].get((f[j], es[i]), 0)
    return w


def log_prob(f: Sequence[str], e: Sequence[str], a: Sequence[int], params: dict) -> float:
    """ln p(f, a | e) as a sum of logs, for sentences whose product would underflow.

    Returns -inf if a factor is 0.
    """
    l, m = len(e), len(f)
    es = [NULL] + list(e)
    phi = fertilities(a, l)
    phi0 = phi[0]
    p1 = float(params["p1"])
    factors = [float(params["t"].get((f[j], es[i]), 0)) for j, i in enumerate(a)]
    factors += [float(params["n"].get((phi[i], e[i - 1]), 0)) for i in range(1, l + 1)]
    factors += [float(params["d"].get((j, i, l, m), 0)) for j, i in enumerate(a, start=1) if i > 0]
    if 2 * phi0 > m or min(factors, default=1.0) <= 0 or (phi0 and p1 <= 0) or (m > 2 * phi0 and p1 >= 1):
        return -math.inf
    s = math.log(math.comb(m - phi0, phi0)) + phi0 * (math.log(p1) if phi0 else 0.0)
    s += (m - 2 * phi0) * (math.log(1 - p1) if m > 2 * phi0 else 0.0)
    s += sum(math.lgamma(phi[i] + 1) for i in range(1, l + 1))
    return s + sum(math.log(x) for x in factors)


def all_alignments(m: int, l: int):
    return product(range(l + 1), repeat=m)


def neighbours(a: Sequence[int], l: int, peg: Tuple[int, int] = None):
    """All alignments one move (change one a_j) or one swap (exchange a_j and a_j') away.

    With peg = (i, j), only neighbours with a_j = i are returned.
    """
    a = list(a)
    m = len(a)
    out = []
    for j in range(m):
        for i in range(l + 1):
            if i != a[j]:
                b = a[:]
                b[j] = i
                out.append(tuple(b))
    for j in range(m):
        for k in range(j + 1, m):
            if a[j] != a[k]:
                b = a[:]
                b[j], b[k] = b[k], b[j]
                out.append(tuple(b))
    if peg is not None:
        i, j = peg
        out = [b for b in out if b[j - 1] == i]
    return out


def hill_climb(f, e, a, params, peg=None) -> Tuple[int, ...]:
    """Go to the best neighbour while it is strictly better; the first of equal neighbours wins."""
    a = tuple(a)
    pa = prob(f, e, a, params)
    while True:  # @line L9
        best, pb = a, pa
        for b in neighbours(a, len(e), peg):  # @line L10
            w = prob(f, e, b, params)
            if w > pb:
                best, pb = b, w
        if best == a:  # @line L11
            return a
        a, pa = best, pb  # @line L12


def start_alignment(f, e, params) -> Tuple[int, ...]:
    """For each j, the i with the largest t(f_j | e_i) d(j | i, l, m), or t(f_j | NULL) p1 for i = 0."""
    es = [NULL] + list(e)
    l, m = len(e), len(f)
    out = []
    for j, x in enumerate(f, start=1):
        def score(i):
            t = params["t"].get((x, es[i]), 0)
            return t * (params["p1"] if i == 0 else params["d"].get((j, i, l, m), 0))
        out.append(max(range(l + 1), key=lambda i: (score(i), -i)))
    return tuple(out)


def pegged_set(f, e, params) -> Set[Tuple[int, ...]]:
    """The set S of Brown et al.: the neighbourhoods of the hill-climbed alignment and of the
    best alignment found with each link (i, j) pegged."""
    l, m = len(e), len(f)
    a0 = start_alignment(f, e, params)  # @line L1
    a = hill_climb(f, e, a0, params)  # @line L2
    s = {a, *neighbours(a, l)}  # @line L3
    for i in range(l + 1):  # @line L4
        for j in range(1, m + 1):
            b = list(a0)
            b[j - 1] = i
            b = hill_climb(f, e, b, params, peg=(i, j))  # @line L5
            s.add(b)  # @line L6
            s.update(neighbours(b, l))
    return s


def viterbi_brute(f, e, params) -> Tuple[Tuple[int, ...], object]:
    best, pb = None, None
    for a in all_alignments(len(f), len(e)):
        w = prob(f, e, a, params)
        if pb is None or w > pb:
            best, pb = a, w
    return best, pb


def expected_counts(corpus: Sequence[Pair], params: dict, exact: bool = True):
    """The E step. exact=True sums over all (l + 1)^m alignments; exact=False over the set S."""
    zero = 0 * params["p1"]
    c = {"t": defaultdict(lambda: zero), "n": defaultdict(lambda: zero), "d": defaultdict(lambda: zero),
         "p0": zero, "p1": zero}
    for f, e in corpus:
        l, m = len(e), len(f)
        es = [NULL] + list(e)
        cands = all_alignments(m, l) if exact else pegged_set(f, e, params)
        weights = [(a, prob(f, e, a, params)) for a in cands]  # @line L7
        z = sum(w for _, w in weights)
        for a, w in weights:  # @line L8
            if not w:
                continue
            q = w / z
            phi = fertilities(a, l)
            for j, i in enumerate(a, start=1):
                c["t"][(f[j - 1], es[i])] += q
                if i > 0:
                    c["d"][(j, i, l, m)] += q
            for i in range(1, l + 1):
                c["n"][(phi[i], es[i])] += q
            c["p1"] += phi[0] * q
            c["p0"] += (m - 2 * phi[0]) * q
    return c


def _normalize(old: dict, counts: dict, group) -> dict:
    tot = defaultdict(int)
    for k, v in counts.items():
        tot[group(k)] += v
    return {k: (counts.get(k, 0) / tot[group(k)] if tot[group(k)] else v) for k, v in old.items()}


def em_step(corpus: Sequence[Pair], params: dict, exact: bool = True) -> dict:
    """One EM round: the E step, then the M step for t, n, d and p1."""
    c = expected_counts(corpus, params, exact)
    total = c["p0"] + c["p1"]
    return {
        "t": _normalize(params["t"], c["t"], lambda k: k[1]),
        "n": _normalize(params["n"], c["n"], lambda k: k[1]),
        "d": _normalize(params["d"], c["d"], lambda k: k[1:]),
        "p1": c["p1"] / total if total else params["p1"],
    }


def log_likelihood(corpus: Sequence[Pair], params: dict) -> float:
    """sum over the pairs of ln p(f | e), with p(f | e) summed over all alignments."""
    s = 0.0
    for f, e in corpus:
        s += math.log(sum(prob(f, e, a, params) for a in all_alignments(len(f), len(e))))
    return s


def uniform_params(corpus: Sequence[Pair], phi_max: int = 2, p1=Fraction(1, 5)) -> dict:
    """t uniform over the source words, n uniform over 0 .. phi_max, d uniform over 1 .. m."""
    vf = sorted({x for f, _ in corpus for x in f})
    ve = sorted({y for _, e in corpus for y in e})
    t = {(x, y): Fraction(1, len(vf)) for x in vf for y in ve + [NULL]}
    n = {(k, y): Fraction(1, phi_max + 1) for k in range(phi_max + 1) for y in ve}
    d = {}
    for f, e in corpus:
        l, m = len(e), len(f)
        for i in range(1, l + 1):
            for j in range(1, m + 1):
                d[(j, i, l, m)] = Fraction(1, m)
    return {"t": t, "n": n, "d": d, "p1": p1}
test_ibm_model_3.py 190 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ibm-model-3/. The authors are listed in prov/2CTGQ5.jsonl.

import math
import random
from collections import defaultdict
from fractions import Fraction as F
from itertools import product

from ibm_model_3 import (
    NULL,
    all_alignments,
    em_step,
    expected_counts,
    hill_climb,
    log_likelihood,
    log_prob,
    neighbours,
    pegged_set,
    prob,
    start_alignment,
    structure_prob,
    uniform_params,
    viterbi_brute,
)


def normalize(d, group):
    tot = defaultdict(float)
    for k, v in d.items():
        tot[group(k)] += v
    return {k: v / tot[group(k)] for k, v in d.items()}


def random_params(rng, corpus, phi_max=2, exact=False):
    p = uniform_params(corpus, phi_max)
    draw = (lambda: F(rng.randint(1, 9))) if exact else (lambda: rng.random() + 0.01)
    for key in ("t", "n", "d"):
        p[key] = {k: draw() for k in p[key]}
    p["t"] = normalize(p["t"], lambda k: k[1])
    p["n"] = normalize(p["n"], lambda k: k[1])
    p["d"] = normalize(p["d"], lambda k: k[1:])
    p["p1"] = F(1, 5) if exact else 0.2
    return p


def random_pair(rng, mmax, lmax):
    m, l = rng.randint(2, mmax), rng.randint(1, lmax)
    return [f"f{rng.randrange(3)}" for _ in range(m)], [f"e{rng.randrange(3)}" for _ in range(l)]


def test_equation_32_by_hand() -> None:
    # e = x, f = a b, a = (1, 0): phi_1 = 1, phi_0 = 1, m = 2
    p = {"t": {("a", "x"): F(1, 2), ("b", NULL): F(1, 3)},
         "n": {(1, "x"): F(2, 5)},
         "d": {(1, 1, 1, 2): F(3, 4)},
         "p1": F(1, 10)}
    # C(1, 1) p0^0 p1^1 * 1! n(1 | x) * t(a | x) t(b | NULL) * d(1 | 1, 1, 2)
    assert prob(["a", "b"], ["x"], (1, 0), p) == F(1, 10) * F(2, 5) * F(1, 2) * F(1, 3) * F(3, 4)
    # two null words need at least four words: C(m - 2, 2) = 0 for m = 3
    p["t"][("c", NULL)] = F(1, 3)
    p["n"][(1, "x")] = F(1)
    assert prob(["b", "c", "a"], ["x"], (0, 0, 1), p) == 0


def test_deficiency() -> None:
    # Sum Equation 32 (without t, whose rows sum to 1 over f) over every length and alignment,
    # and compare with the success probability of the generative story; the gap is the mass
    # the story puts on two words in one position, which is not a string.
    e = ["x", "y"]
    phi_max, p1 = 2, F(1, 4)
    n = {(0, "x"): F(1, 4), (1, "x"): F(1, 2), (2, "x"): F(1, 4),
         (0, "y"): F(1, 3), (1, "y"): F(1, 3), (2, "y"): F(1, 3)}
    mmax = 2 * len(e) * phi_max
    d = {}
    for m in range(1, mmax + 1):
        for i in (1, 2):
            w = {j: F(1 + (j == i) + (j == 2 * i), 1) for j in range(1, m + 1)}
            tot = sum(w.values())
            for j in range(1, m + 1):
                d[(j, i, 2, m)] = w[j] / tot
    params = {"t": {}, "n": n, "d": d, "p1": p1}
    total = F(0)
    for m in range(0, mmax + 1):
        for a in all_alignments(m, len(e)):
            total += structure_prob(a, e, m, params)
    story = F(0)
    for phi in product(range(phi_max + 1), repeat=len(e)):
        pphi = n[(phi[0], "x")] * n[(phi[1], "y")]
        words = [i for i in (1, 2) for _ in range(phi[i - 1])]
        k = len(words)
        for phi0 in range(k + 1):
            m = k + phi0
            pn = math.comb(k, phi0) * p1 ** phi0 * (1 - p1) ** (k - phi0)
            for pos in product(range(1, m + 1), repeat=k):
                if len(set(pos)) == k:
                    pd = F(1)
                    for i, j in zip(words, pos):
                        pd *= d[(j, i, 2, m)]
                    story += pphi * pn * pd
    assert total == story
    assert total < 1
    assert float(1 - total) > 0.1
    # the hand case: one target word with fertility 2, no null words, d(j | 1, 1, 2) = 1/2;
    # the two words land in the same position with probability 1/2
    hand = {"t": {}, "n": {(2, "x"): F(1)}, "d": {(1, 1, 1, 2): F(1, 2), (2, 1, 1, 2): F(1, 2)}, "p1": F(0)}
    assert sum(structure_prob(a, ["x"], 2, hand) for a in all_alignments(2, 1)) == F(1, 2)


def test_neighbours() -> None:
    a = (1, 0, 1)
    nb = neighbours(a, 2)
    # moves: 3 positions times 2 other values; swaps: the pairs with different values
    assert len(nb) == 3 * 2 + 2
    assert all(sum(x != y for x, y in zip(a, b)) in (1, 2) for b in nb)
    assert all(b[1] == 2 for b in neighbours(a, 2, peg=(2, 2)))


def test_exact_e_step_and_em() -> None:
    corpus = [(["a", "b"], ["x"]), (["a", "c", "b"], ["x", "y"])]
    p = uniform_params(corpus)
    c = expected_counts(corpus, p)
    # every source word gives one unit of count to t, and every real target word one unit to n
    assert sum(c["t"].values()) == 5
    assert sum(c["n"].values()) == 3
    p2 = em_step(corpus, p)
    for key, group in (("t", lambda k: k[1]), ("n", lambda k: k[1]), ("d", lambda k: k[1:])):
        sums = defaultdict(F)
        for k, v in p2[key].items():
            assert 0 <= v <= 1
            sums[group(k)] += v
        assert set(sums.values()) == {F(1)}
    assert 0 < p2["p1"] < 1
    # exact EM never decreases the likelihood (floats for more rounds)
    rng = random.Random(31)
    for _ in range(3):
        corpus = [random_pair(rng, 3, 2) for _ in range(3)]
        q = random_params(rng, corpus)
        hist = [log_likelihood(corpus, q)]
        for _ in range(6):
            q = em_step(corpus, q)
            hist.append(log_likelihood(corpus, q))
        assert all(y >= x - 1e-9 for x, y in zip(hist, hist[1:]))


def test_hill_climbing_and_pegging_against_brute_force() -> None:
    rng = random.Random(32)
    stuck = 0
    for _ in range(80):
        f, e = random_pair(rng, 4, 3)
        p = random_params(rng, [(f, e)])
        best, pbest = viterbi_brute(f, e, p)
        a = hill_climb(f, e, start_alignment(f, e, p), p)
        pa = prob(f, e, a, p)
        assert pa <= pbest
        assert all(prob(f, e, b, p) <= pa for b in neighbours(a, len(e)))  # a local maximum
        stuck += pa < pbest
        s = pegged_set(f, e, p)
        assert max(prob(f, e, b, p) for b in s) == pbest
    # hill climbing alone stops below the best alignment in some cases; pegging recovers them here
    assert stuck >= 3


def test_pegged_counts_equal_exact_on_tiny_pairs() -> None:
    # for m = 2 and l = 1 the set S contains every alignment, so the two E steps agree
    rng = random.Random(33)
    corpus = [(["a", "b"], ["x"]), (["b", "b"], ["x"])]
    p = random_params(rng, corpus, exact=True)
    assert pegged_set(["a", "b"], ["x"], p) == set(all_alignments(2, 1))
    assert expected_counts(corpus, p, exact=True) == expected_counts(corpus, p, exact=False)


def test_log_prob_long_sentence() -> None:
    m = 200
    f = [f"f{j % 50}" for j in range(m)]
    e = [f"e{j % 50}" for j in range(m)]
    a = tuple(range(1, m + 1))
    vf = sorted(set(f))
    p = {"t": {(x, y): 1 / 50 for x in vf for y in sorted(set(e))},
         "n": {(1, y): 0.5 for y in set(e)},
         "d": {(j, j, m, m): 0.5 for j in range(1, m + 1)},
         "p1": 0.1}
    assert prob(f, e, a, p) == 0.0
    want = m * (math.log(0.9) + math.log(0.5) + math.log(1 / 50) + math.log(0.5))
    assert math.isclose(log_prob(f, e, a, p), want, rel_tol=1e-12)
    small = (["a", "b"], ["x"])
    q = random_params(random.Random(34), [small])
    for al in all_alignments(2, 1):
        w = prob(*small, al, q)
        assert (w == 0 and log_prob(*small, al, q) == -math.inf) or math.isclose(log_prob(*small, al, q), math.log(w))

References

  1. Brown, Della Pietra, Della Pietra and Mercer 1993, Section 4.3 (Viterbi and pegged alignments), Section 4.4 (Model 3, Equation 32, moves, swaps and the set S of Equation 44), Section 4.5 (deficiency), Section 4.7 (Model 5) and Appendix B.5
  2. Udupa and Maji 2006, the hardness of the Viterbi alignment and of the expectation and conditional probability problems for Models 3 to 5
  3. Philipp Koehn, Statistical Machine Translation, Cambridge University Press, 2010, Chapter 4, Section 4.4 (the higher IBM models)

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