Algorithm Search⌘K

Modelcore

HMM alignment model

Also called Vogel HMM alignment.

Word alignment as an HMM over source positions, with jump probabilities that depend on the distance between successive aligned positions.

The HMM alignment model treats a word alignment as the hidden state sequence of a hidden Markov model. The states are the positions 1,…,l1, \ldots, l of the target sentence ee. As the model reads the source sentence f=f1…fmf = f_1 \ldots f_m from left to right, it moves from the position aligned to fj−1f_{j-1} to the position aligned to fjf_j, and the probability of the move depends only on its width aj−aj−1a_j - a_{j-1}. Each state emits its source word from the table t(f∣e)t(f \mid e) of IBM Model 1. So the model prefers alignments in which neighbouring source words go to neighbouring target words, which neither Model 1 nor Model 2 can express. Because it is an HMM, the sum over all alignments and the best alignment are exact by the forward-backward and Viterbi algorithms in Θ(ml2)\Theta(m l^2) time per pair. Vogel, Ney and Tillmann (1996) proposed the model, and Och and Ney (2003) added the null word.

The machine

Variables. A pair is f=f1…fmf = f_1 \ldots f_m and 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): source word jj is generated by target word aja_j. The reverse direction is a different model and gives different alignments; the two are often combined by grow-diag-final.

Parameters.

  • t(f∣e)t(f \mid e), with a row for the null word;
  • a weight c(d)≥0c(d) \ge 0 for each jump width dd; for a sentence of length ll the jump from position rr to position ii has probability c(i−r)/∑i′=1lc(i′−r)c(i - r) / \sum_{i'=1}^{l} c(i' - r) (Vogel et al. 1996);
  • the null probability p0p_0, a fixed number. The code uses p0=0.2p_0 = 0.2, the value of Och and Ney (2003).

The null word. A source word aligned to the null word has no target position, so the next jump needs another starting point. Och and Ney (2003) double the state set: state i+li + l is "null, after position ii". From a state that remembers position rr (the real state rr or the null state r+lr + l), the model goes to the null state of rr with probability p0p_0, or to a real position ii with probability (1−p0)(1 - p_0) times the jump probability from rr to ii. This page writes rjr_j for the last real position aligned at or before jj. The code also puts a virtual position r0=0r_0 = 0 in front of the sentence, so the first word uses the jump from 0, and it keeps a null state for that position too. Then

p(f,a∣e)=∏j=1mp(aj∣rj−1,l) t(fj∣eaj),p(i∣r,l)={p0i=0,(1−p0)c(i−r)∑i′=1lc(i′−r)i≥1.p(f, a \mid e) = \prod_{j=1}^{m} p(a_j \mid r_{j-1}, l) \, t(f_j \mid e_{a_j}), \qquad p(i \mid r, l) = \begin{cases} p_0 & i = 0, \\ (1 - p_0) \dfrac{c(i - r)}{\sum_{i'=1}^{l} c(i' - r)} & i \ge 1. \end{cases}

For example, with l=3l = 3, r=1r = 1, c(0)=1c(0) = 1, c(1)=4c(1) = 4, c(2)=2c(2) = 2 and p0=0.2p_0 = 0.2, the next word goes to position 1, 2 or 3 with probabilities 0.8⋅1/70.8 \cdot 1/7, 0.8⋅4/70.8 \cdot 4/7 and 0.8⋅2/70.8 \cdot 2/7, that is 0.114, 0.457 and 0.229, and to the null word with probability 0.2.

Standing assumptions. The jump probabilities depend on the width only, not on the words or the absolute position. Each source word depends only on the target word of its state. A state path with nonzero probability is fixed by the alignment, so sums over state paths are sums over alignments.

Training. EM is Baum-Welch with tied transition parameters. One round, in log space:

  1. HMM-ALIGNMENT-EM-ROUND(corpus, t, c)
  2. 1for each pair (f, e) in the corpus do
  3. 2α ← the forward table of ln probabilities, from the jumps out of position 0
  4. 3β ← the backward table of ln probabilities
  5. 4ln p(f | e) ← ln Σ_s exp α_m(s)
  6. 5for each j and state s: add γ_j(s) = exp(α_j(s) + β_j(s) - ln p(f | e)) to c_t(f_j, word of s)
  7. 6for each j and real position i: add the expected number of jumps r → i at j to N(r, i, l)
  8. 7t(f | e) ← c_t(f, e) / Σ_f' c_t(f', e)
  9. 8c' ← the count update: c'(d) proportional to Σ over i - r = d of N(r, i, l)
  10. 9c ← the best of c and c', improved by gradient ascent on Q(ln c), keeping only steps that raise Q
  11. 10return t and c

Lines L2 to L4 are the forward algorithm and the backward pass of the HMM, with the log-sum-exp helper of the area, so that long sentences do not underflow. Line L6 needs the forward value at j−1j - 1, the jump, the emission and the backward value at jj. Line L7 is the exact M step for tt.

The jump step. The M step for cc maximizes Q(c)=∑r,i,lN(r,i,l)ln⁡(c(i−r)/∑i′c(i′−r))Q(c) = \sum_{r, i, l} N(r, i, l) \ln \bigl( c(i - r) / \sum_{i'} c(i' - r) \bigr). The rows rr have different normalizers, so the simple count update of line L8 is not the maximizer. From uniform cc and uniform tt, every row of posteriors is uniform and uniform cc is optimal, but small widths occur in more rows, so the count update favours them and lowers QQ; the tests show such a case. In θ=ln⁡c\theta = \ln c, QQ is a linear function minus a sum of log-sum-exp terms, so it is concave, and line L9 climbs it with backtracking steps. The round is then a generalized EM step, and the likelihood never decreases.

Example. Twelve pairs in which every target word eke_k is translated in place by fkf_k, with random words and lengths 2 to 5, trained from uniform tt and cc with the null word:

round log likelihood share of c(1)c(1) t(f3∣e3)t(f_3 \mid e_3)
0 -68.09 0.10 0.167
2 -37.90 0.15 0.578
4 -14.13 0.57 0.936
6 -7.73 0.95 1.000

In the first rounds tt learns the lexicon while cc stays near uniform. Then the jump of width 1 takes most of the weight. For the pair f3f1f1f4∣e3e1e1e4f_3 f_1 f_1 f_4 \mid e_3 e_1 e_1 e_4 the trained model gives the alignment (1,2,3,4)(1, 2, 3, 4). With the same tt and uniform jumps the two copies of e1e_1 tie, and the tie rule gives (1,2,2,4)(1, 2, 2, 4). These numbers are a measurement on a toy corpus.

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. With 2l+12l + 1 states and transitions that are dense among the real states, the costs per pair are:

Task Algorithm Cost
p(f∣e)p(f \mid e) forward algorithm Θ(ml2)\Theta(m l^2)
posteriors of links and jumps (E step) forward-backward Θ(ml2)\Theta(m l^2)
best alignment arg⁡max⁡ap(a∣f,e)\arg\max_a p(a \mid f, e) Viterbi algorithm Θ(ml2)\Theta(m l^2)
the same by enumeration Θ(m(l+1)m)\Theta(m (l + 1)^m)

The M step for tt is linear in the size of the counts. The jump step works on the counts N(r,i,l)N(r, i, l), whose number is at most the number of distinct (r,i,l)(r, i, l) in the corpus.

Relation to other models

  • Hidden Markov model. The model is a hidden Markov model whose states are target positions and whose outputs are source words. The transition matrix is different for each sentence length but tied through cc, and the emission matrix is tied through tt.
  • IBM Model 1. With all c(d)c(d) equal and no null word, every jump has probability 1/l1/l, and the model is Model 1 without the null word. The tests check this.
  • IBM Model 2. In Model 2 the position aja_j depends on jj and the lengths, not on aj−1a_{j-1}. Vogel et al. (1996) compare the two.
  • fast_align. fast_align keeps the independence of Model 2 and pulls links towards the diagonal. It is faster, with an E step of Θ(lm)\Theta(l m) per pair, but it cannot model a block of words that moves together.
  • IBM Models 3 and 4. Model 3 adds fertility, and Model 4 makes the position of a word depend on the position of the previous group, which is close to the jump idea. Their E steps are approximate. Och and Ney (2003) train Model 1, then the HMM, and use it to start Models 3 and 4.

Known results in the model

  • Exact inference (theorem). The forward algorithm computes the sum over all alignments, and the Viterbi algorithm the best alignment, in Θ(ml2)\Theta(m l^2) per pair, because the alignment is a Markov chain over positions. The tests compare both with the enumeration of all alignments, and the link posteriors with the brute-force posteriors. So word alignment under this model is solvable exactly, unlike under Model 3, where the best alignment is NP-hard.
  • EM never decreases the likelihood (theorem). This holds for the exact M step and for any step that does not lower QQ. The tests check it round by round on random corpora with and without the null word.
  • The count update is not the M step (shown by example). The simple update of line L8 can lower QQ, as described above; the tests show a case. This is an observation of this page, not a claim of the papers.
  • Local maxima. Like other HMMs, the model has a likelihood that is not concave in general, and EM reaches a local maximum. The usual start is the table tt of Model 1 (Och and Ney 2003).
  • Underflow. A pair of 200 source words, each with probability 1/501/50, has p(f∣e)=50−200p(f \mid e) = 50^{-200}, which is 0 in double precision. The log-space forward pass returns −200ln⁡50-200 \ln 50; 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.

hmm_alignment_model.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hmm-alignment-model/. The authors are listed in prov/S290AK.jsonl.

"""The HMM alignment model (Vogel, Ney and Tillmann 1996) with the null word
extension of Och and Ney (2003), trained by EM with forward-backward in log space.

A pair is (f, e): the generated sentence f = f_1 .. f_m and the given sentence
e = e_1 .. e_l. An alignment a has a_j in 0 .. l, with 0 for the null word.

    p(f, a | e) = prod_j p(a_j | r_{j-1}, l) t(f_j | e_{a_j})

where r_j is the last real position aligned at or before j (r_0 = 0, a virtual
position in front of the sentence). With p0 the null probability,

    p(a_j = i | r, l) = (1 - p0) c(i - r) / sum_{i'=1..l} c(i' - r)   for i >= 1
    p(a_j = 0 | r, l) = p0

c maps a jump width d to a weight c(d) >= 0. With null=False, p0 = 0.

The hidden states are the real positions 1 .. l and, with null=True, one null
state for each remembered position r = 0 .. l. A state path with nonzero
probability is fixed by the alignment, so sums over paths are sums over alignments.
"""

import math
from collections import defaultdict
from typing import Dict, List, Sequence, Tuple

from nlslog import NEG_INF, argmax, log_sum, safe_log

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


def uniform_t(corpus: Sequence[Pair]) -> Dict[Tuple[str, str], float]:
    vf = sorted({x for f, _ in corpus for x in f})
    ve = sorted({y for _, e in corpus for y in e}) + [NULL]
    return {(x, y): 1.0 / len(vf) for x in vf for y in ve}


def uniform_c(corpus: Sequence[Pair]) -> Dict[int, float]:
    """c(d) = 1 for every jump width d that can occur: -(L - 1) .. L for the longest e."""
    lmax = max(len(e) for _, e in corpus)
    return {d: 1.0 for d in range(-(lmax - 1), lmax + 1)}


def states(l: int, null: bool) -> List[Tuple[str, int]]:
    """('w', i) for the real positions, ('n', r) for the null states."""
    out = [("w", i) for i in range(1, l + 1)]
    if null:
        out += [("n", r) for r in range(0, l + 1)]
    return out


def log_jump_row(r: int, l: int, c: Dict[int, float], p0: float, null: bool) -> Dict[Tuple[str, int], float]:
    """ln p(next state | remembered position r): the row of the transition matrix."""
    z = sum(c.get(i - r, 0.0) for i in range(1, l + 1))
    row = {}
    for i in range(1, l + 1):
        row[("w", i)] = safe_log(1 - p0) + safe_log(c.get(i - r, 0.0)) - math.log(z) if z > 0 else NEG_INF
    if null:
        row[("n", r)] = safe_log(p0)
    return row


def _model(f, e, t, c, p0, null):
    l = len(e)
    ss = states(l, null)
    rows = {r: log_jump_row(r, l, c, p0, null) for r in range(0, l + 1)}
    es = [NULL] + list(e)

    def emit(j, s):
        word = es[s[1]] if s[0] == "w" else NULL
        return safe_log(t.get((f[j], word), 0.0))

    def trans(s_prev, s):
        return rows[s_prev[1]].get(s, NEG_INF)

    return ss, rows, emit, trans


def forward_backward(f, e, t, c, p0=0.2, null=True):
    """Log-space forward and backward tables (lists over j of dicts over states) and ln p(f | e)."""
    ss, rows, emit, trans = _model(f, e, t, c, p0, null)
    m = len(f)
    alpha = [{s: rows[0].get(s, NEG_INF) + emit(0, s) for s in ss}]  # @line L2
    for j in range(1, m):
        alpha.append({s: emit(j, s) + log_sum(alpha[j - 1][q] + trans(q, s) for q in ss) for s in ss})
    beta = [None] * m  # @line L3
    beta[m - 1] = {s: 0.0 for s in ss}
    for j in range(m - 2, -1, -1):
        beta[j] = {q: log_sum(trans(q, s) + emit(j + 1, s) + beta[j + 1][s] for s in ss) for q in ss}
    logp = log_sum(alpha[m - 1].values())  # @line L4
    return alpha, beta, logp


def log_likelihood(corpus: Sequence[Pair], t, c, p0=0.2, null=True) -> float:
    return sum(forward_backward(f, e, t, c, p0, null)[2] for f, e in corpus)


def expected_counts(corpus: Sequence[Pair], t, c, p0=0.2, null=True):
    """The E step: link counts for t and jump counts N[(r, i, l)] into real positions."""
    ct: Dict[Tuple[str, str], float] = defaultdict(float)
    nj: Dict[Tuple[int, int, int], float] = defaultdict(float)
    for f, e in corpus:  # @line L1
        l, m = len(e), len(f)
        es = [NULL] + list(e)
        alpha, beta, logp = forward_backward(f, e, t, c, p0, null)
        ss, rows, emit, trans = _model(f, e, t, c, p0, null)
        for j in range(m):
            for s in ss:
                g = math.exp(alpha[j][s] + beta[j][s] - logp)  # @line L5
                if g > 0:
                    ct[(f[j], es[s[1]] if s[0] == "w" else NULL)] += g
        for i in range(1, l + 1):  # the first word, from the virtual position 0
            g = math.exp(rows[0][("w", i)] + emit(0, ("w", i)) + beta[0][("w", i)] - logp)
            nj[(0, i, l)] += g
        for j in range(1, m):
            for q in ss:
                for i in range(1, l + 1):
                    s = ("w", i)
                    x = alpha[j - 1][q] + trans(q, s) + emit(j, s) + beta[j][s] - logp  # @line L6
                    if x > NEG_INF:
                        nj[(q[1], i, l)] += math.exp(x)
    return ct, nj


def jump_objective(nj, c) -> float:
    """The part of the expected complete-data log likelihood that depends on c."""
    total = 0.0
    for (r, i, l), n in nj.items():
        if n <= 0:
            continue
        z = sum(c.get(k - r, 0.0) for k in range(1, l + 1))
        w = c.get(i - r, 0.0)
        if w <= 0 or z <= 0:
            return NEG_INF
        total += n * (math.log(w) - math.log(z))
    return total


def count_update(nj, c) -> Dict[int, float]:
    """c(d) proportional to the expected number of jumps of width d. Simple, but not the
    exact M step, because the rows r have different normalizers."""
    cand = {d: 0.0 for d in c}
    for (r, i, l), n in nj.items():
        cand[i - r] = cand.get(i - r, 0.0) + n
    s = sum(cand.values())
    return {d: v / s for d, v in cand.items()} if s > 0 else dict(c)


def jump_m_step(nj, c, iterations: int = 40) -> Dict[int, float]:
    """Maximize jump_objective over c. In theta = ln c the objective is concave (a linear
    term minus log-sum-exp terms), so gradient ascent works; a step is kept only if it
    raises the objective, so the result is never worse than c."""
    best = dict(c)
    q_best = jump_objective(nj, best)
    cand = count_update(nj, c)  # @line L8
    q_cand = jump_objective(nj, cand)
    if q_cand > q_best:
        best, q_best = cand, q_cand
    theta = {d: (math.log(v) if v > 0 else NEG_INF) for d, v in best.items()}
    rows: Dict[Tuple[int, int], float] = defaultdict(float)
    for (r, i, l), n in nj.items():
        rows[(r, l)] += n
    for _ in range(iterations):
        grad = {d: 0.0 for d in theta}
        for (r, i, l), n in nj.items():
            grad[i - r] += n
        for (r, l), n in rows.items():
            z = log_sum(theta.get(k - r, NEG_INF) for k in range(1, l + 1))
            for k in range(1, l + 1):
                d = k - r
                if theta.get(d, NEG_INF) > NEG_INF:
                    grad[d] -= n * math.exp(theta[d] - z)
        gmax = max(abs(g) for g in grad.values())
        if gmax < 1e-10:
            break
        step = 1.0 / gmax
        for _ in range(30):
            trial = {d: (th + step * grad[d] if th > NEG_INF else th) for d, th in theta.items()}
            c_trial = {d: math.exp(th) if th > NEG_INF else 0.0 for d, th in trial.items()}
            q = jump_objective(nj, c_trial)
            if q > q_best:
                theta, best, q_best = trial, c_trial, q
                break
            step /= 2
        else:
            break
    return best


def em_step(corpus: Sequence[Pair], t, c, p0=0.2, null=True):
    """One generalized EM round. t gets the exact M step; c gets a step that does not
    lower its part of the expected complete-data log likelihood."""
    ct, nj = expected_counts(corpus, t, c, p0, null)
    tot: Dict[str, float] = defaultdict(float)
    for (x, y), v in ct.items():
        tot[y] += v
    new_t = {k: (ct.get(k, 0.0) / tot[k[1]] if tot[k[1]] > 0 else v) for k, v in t.items()}  # @line L7
    new_c = jump_m_step(nj, c)  # @line L9
    return new_t, new_c  # @line L10


def train(corpus: Sequence[Pair], rounds: int, p0=0.2, null=True, t=None, c=None):
    """EM from uniform t and c unless given. Returns t, c and the log likelihoods."""
    t = uniform_t(corpus) if t is None else t
    c = uniform_c(corpus) if c is None else c
    hist = [log_likelihood(corpus, t, c, p0, null)]
    for _ in range(rounds):
        t, c = em_step(corpus, t, c, p0, null)
        hist.append(log_likelihood(corpus, t, c, p0, null))
    return t, c, hist


def viterbi_alignment(f, e, t, c, p0=0.2, null=True) -> Tuple[List[int], float]:
    """The most probable alignment and its log probability; on ties the first state in
    the order real positions 1 .. l, then null states, wins."""
    ss, rows, emit, trans = _model(f, e, t, c, p0, null)
    m = len(f)
    delta = [[rows[0].get(s, NEG_INF) + emit(0, s) for s in ss]]
    back = []
    for j in range(1, m):
        row, bp = [], []
        for s in ss:
            cands = [delta[j - 1][k] + trans(q, s) for k, q in enumerate(ss)]
            k = argmax(cands)
            bp.append(k)
            row.append(cands[k] + emit(j, s))
        delta.append(row)
        back.append(bp)
    k = argmax(delta[m - 1])
    best = delta[m - 1][k]
    path = [k]
    for bp in reversed(back):
        k = bp[k]
        path.append(k)
    path.reverse()
    return [ss[k][1] if ss[k][0] == "w" else 0 for k in path], best
nlslog.py 152 lines
# SPDX-License-Identifier: MIT
# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Log-space arithmetic and semirings for the natural-language-and-speech pages.

Every log is the natural log. A probability of 0 is NEG_INF (float("-inf")),
never a large negative number. A cost is -log p, so a probability of 0 is a
cost of POS_INF.

The semirings are (K, plus, times, zero, one) as on the weighted-automaton page:

    PROB      probabilities         plus = +        times = *   zero = 0       one = 1
    LOG       log probabilities     plus = log_add  times = +   zero = -inf    one = 0
    VITERBI   log probabilities     plus = max      times = +   zero = -inf    one = 0
    TROPICAL  costs -log p          plus = min      times = +   zero = +inf    one = 0
    LOG_COST  costs -log p          plus = -log_add(-a, -b), times = +, zero = +inf, one = 0
    BOOLEAN   truth values          plus = or       times = and zero = False   one = True
    COUNTING  path counts           plus = +        times = *   zero = 0       one = 1

This module holds no algorithm of any page: no forward, Viterbi, CKY, Eisner,
CTC or DTW recursion. The pages build their dynamic programs on top of it.
"""

import math
from dataclasses import dataclass
from typing import Any, Callable, Iterable, List, Sequence

NEG_INF = float("-inf")
POS_INF = float("inf")


def safe_log(p) -> float:
    """Return log p, and NEG_INF for p = 0. Raise ValueError for p < 0."""
    if p < 0:
        raise ValueError("log of a negative number")
    if p == 0:
        return NEG_INF
    return math.log(p)


def log_add(a: float, b: float) -> float:
    """Return log(exp(a) + exp(b)) = max(a, b) + log(1 + exp(-|a - b|)).

    log_add(NEG_INF, NEG_INF) is NEG_INF. No exp of a large number is taken.
    """
    if a < b:
        a, b = b, a
    if b == NEG_INF or a == POS_INF:
        return a
    return a + math.log1p(math.exp(b - a))


def log_sum(xs: Iterable[float]) -> float:
    """Return log(sum of exp(x)) over xs. An empty input gives NEG_INF."""
    xs = list(xs)
    if not xs:
        return NEG_INF
    m = max(xs)
    if m == NEG_INF or m == POS_INF:
        return m
    return m + math.log(math.fsum(math.exp(x - m) for x in xs))


def log_normalize(xs: Sequence[float]) -> List[float]:
    """Return the list x - log_sum(xs): log values whose exps sum to 1.

    Raise ValueError if every value is NEG_INF (nothing to normalize).
    """
    z = log_sum(xs)
    if z == NEG_INF:
        raise ValueError("every weight is zero")
    return [x - z for x in xs]


def log_softmax(xs: Sequence[float]) -> List[float]:
    """Return log softmax(xs): the logits xs turned into log probabilities."""
    return log_normalize(xs)


def softmax(xs: Sequence[float], temperature: float = 1.0) -> List[float]:
    """Return the probabilities exp(x / temperature) / sum, computed stably.

    The temperature must be positive. Logits of NEG_INF get probability 0.
    """
    if not temperature > 0:
        raise ValueError("the temperature must be positive")
    m = max(xs)
    if m == NEG_INF:
        raise ValueError("every logit is -inf")
    es = [math.exp((x - m) / temperature) for x in xs]
    s = math.fsum(es)
    return [e / s for e in es]


def argmax(xs: Sequence[Any]) -> int:
    """Return the first index of a largest value. Raise ValueError if xs is empty."""
    if len(xs) == 0:
        raise ValueError("argmax of an empty sequence")
    best = 0
    for i in range(1, len(xs)):
        if xs[i] > xs[best]:
            best = i
    return best


@dataclass(frozen=True)
class Semiring:
    """A semiring (K, plus, times, zero, one). idempotent is True when a plus a = a."""

    name: str
    plus: Callable[[Any, Any], Any]
    times: Callable[[Any, Any], Any]
    zero: Any
    one: Any
    idempotent: bool


def _add(a, b):
    return a + b


def _mul(a, b):
    return a * b


def _log_add_cost(a: float, b: float) -> float:
    return -log_add(-a, -b)


PROB = Semiring("probability", _add, _mul, 0, 1, False)
LOG = Semiring("log", log_add, _add, NEG_INF, 0.0, False)
VITERBI = Semiring("viterbi", max, _add, NEG_INF, 0.0, True)
TROPICAL = Semiring("tropical", min, _add, POS_INF, 0.0, True)
LOG_COST = Semiring("log-cost", _log_add_cost, _add, POS_INF, 0.0, False)
BOOLEAN = Semiring("boolean", lambda a, b: a or b, lambda a, b: a and b, False, True, True)
COUNTING = Semiring("counting", _add, _mul, 0, 1, False)


def sr_sum(sr: Semiring, xs: Iterable[Any]) -> Any:
    """Return the semiring sum of xs, and sr.zero for an empty input."""
    acc = sr.zero
    for x in xs:
        acc = sr.plus(acc, x)
    return acc


def sr_prod(sr: Semiring, xs: Iterable[Any]) -> Any:
    """Return the semiring product of xs, and sr.one for an empty input."""
    acc = sr.one
    for x in xs:
        acc = sr.times(acc, x)
    return acc
test_hmm_alignment_model.py 167 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hmm-alignment-model/. The authors are listed in prov/S290AK.jsonl.

import math
import random
from collections import defaultdict
from itertools import product

from hmm_alignment_model import (
    NULL,
    count_update,
    em_step,
    expected_counts,
    forward_backward,
    jump_m_step,
    jump_objective,
    log_jump_row,
    log_likelihood,
    train,
    uniform_c,
    uniform_t,
    viterbi_alignment,
)


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_params(rng, corpus):
    t = {k: rng.random() + 0.05 for k in uniform_t(corpus)}
    tot = defaultdict(float)
    for (x, y), v in t.items():
        tot[y] += v
    t = {(x, y): v / tot[y] for (x, y), v in t.items()}
    c = {d: rng.random() + 0.05 for d in uniform_c(corpus)}
    return t, c


def joint(f, e, a, t, c, p0, null):
    """p(f, a | e) straight from the definition, with the remembered position r."""
    l = len(e)
    r, p = 0, 1.0
    for j, i in enumerate(a):
        if i == 0:
            if not null:
                return 0.0
            p *= p0 * t[(f[j], NULL)]
        else:
            z = sum(c[k - r] for k in range(1, l + 1))
            p *= (1 - p0) * c[i - r] / z * t[(f[j], e[i - 1])]
            r = i
    return p


def alignments(m, l, null):
    return product(range(0 if null else 1, l + 1), repeat=m)


def test_forward_and_posteriors_against_all_alignments() -> None:
    rng = random.Random(41)
    for null in (False, True):
        corpus = random_corpus(rng, 4, 3, 3, 4)
        t, c = random_params(rng, corpus)
        p0 = 0.2 if null else 0.0
        ct, nj = expected_counts(corpus, t, c, p0, null)
        bt = defaultdict(float)
        for f, e in corpus:
            ps = {a: joint(f, e, a, t, c, p0, null) for a in alignments(len(f), len(e), null)}
            z = sum(ps.values())
            assert math.isclose(forward_backward(f, e, t, c, p0, null)[2], math.log(z), rel_tol=1e-12)
            for a, p in ps.items():
                for j, i in enumerate(a):
                    bt[(f[j], e[i - 1] if i else NULL)] += p / z
        for k in set(ct) | set(bt):
            assert math.isclose(ct.get(k, 0.0), bt.get(k, 0.0), rel_tol=1e-9, abs_tol=1e-12)
        # every source word gives one unit to the link counts and one jump or null step
        assert math.isclose(sum(ct.values()), sum(len(f) for f, _ in corpus))


def test_rows_are_distributions() -> None:
    c = {d: 1.0 + 0.1 * d * d for d in range(-4, 6)}
    for null, p0 in ((False, 0.0), (True, 0.2)):
        for l in (1, 3, 5):
            for r in range(0, l + 1):
                row = log_jump_row(r, l, c, p0, null)
                assert math.isclose(sum(math.exp(v) for v in row.values()), 1.0, rel_tol=1e-12)


def test_viterbi_against_brute_force() -> None:
    rng = random.Random(42)
    for null in (False, True):
        corpus = random_corpus(rng, 6, 3, 3, 4)
        t, c = random_params(rng, corpus)
        p0 = 0.2 if null else 0.0
        for f, e in corpus:
            a, lp = viterbi_alignment(f, e, t, c, p0, null)
            best = max(joint(f, e, b, t, c, p0, null) for b in alignments(len(f), len(e), null))
            assert math.isclose(lp, math.log(best), rel_tol=1e-12)
            assert math.isclose(joint(f, e, tuple(a), t, c, p0, null), best, rel_tol=1e-12)


def test_likelihood_never_decreases() -> None:
    rng = random.Random(43)
    for null in (False, True):
        corpus = random_corpus(rng, 5, 4, 4, 4)
        t, c = random_params(rng, corpus)
        p0 = 0.2 if null else 0.0
        _, _, hist = train(corpus, 6, p0, null, t=t, c=c)
        assert all(y >= x - 1e-9 for x, y in zip(hist, hist[1:]))
        # the jump step never lowers its part of the expected complete-data log likelihood,
        # and it is at least as good as the plain count update
        _, nj = expected_counts(corpus, t, c, p0, null)
        _, c2 = em_step(corpus, t, c, p0, null)
        assert jump_objective(nj, c2) >= jump_objective(nj, c)
        assert jump_objective(nj, c2) >= jump_objective(nj, count_update(nj, c)) - 1e-12


def test_count_update_is_not_the_m_step() -> None:
    # from uniform t and c the posteriors of each row are uniform, so uniform c is optimal;
    # the count update favours small widths, which occur in more rows, and lowers the objective
    rng = random.Random(46)
    corpus = random_corpus(rng, 6, 4, 4, 5)
    t, c = uniform_t(corpus), uniform_c(corpus)
    _, nj = expected_counts(corpus, t, c, 0.2, True)
    q = jump_objective(nj, c)
    assert jump_objective(nj, count_update(nj, c)) < q - 1e-6
    assert math.isclose(jump_objective(nj, jump_m_step(nj, c)), q, rel_tol=1e-9)


def test_uniform_jumps_give_model_1() -> None:
    rng = random.Random(44)
    corpus = random_corpus(rng, 4, 3, 3, 4)
    t, _ = random_params(rng, corpus)
    c = uniform_c(corpus)
    for f, e in corpus:
        m1 = sum(math.log(sum(t[(x, y)] for y in e) / len(e)) for x in f)
        assert math.isclose(forward_backward(f, e, t, c, 0.0, False)[2], m1, rel_tol=1e-12)


def test_learns_short_forward_jumps() -> None:
    # a corpus where every word is translated in place, with the word pairs mixed up
    rng = random.Random(45)
    lex = {f"e{k}": f"f{k}" for k in range(6)}
    corpus = []
    for _ in range(12):
        e = [f"e{rng.randrange(6)}" for _ in range(rng.randint(2, 5))]
        corpus.append(([lex[y] for y in e], e))
    t, c, hist = train(corpus, 6, 0.2, True)
    assert max(c, key=c.get) == 1
    f, e = ["f3", "f1", "f1", "f4"], ["e3", "e1", "e1", "e4"]
    a, _ = viterbi_alignment(f, e, t, c, 0.2, True)
    assert a == [1, 2, 3, 4]


def test_long_sentence_log_space() -> None:
    # 200 source words of 50 types and a 4-word target: p(f | e) = 50^-200 underflows
    m = 200
    f = [f"f{j % 50}" for j in range(m)]
    e = ["e0", "e1", "e2", "e3"]
    corpus = [(f, e)]
    t, c = uniform_t(corpus), uniform_c(corpus)
    assert math.prod(sum(t[(x, y)] / len(e) for y in e) for x in f) == 0.0
    for null, p0 in ((False, 0.0), (True, 0.2)):
        _, _, logp = forward_backward(f, e, t, c, p0, null)
        assert math.isclose(logp, -m * math.log(50), rel_tol=1e-12)

References

  1. Vogel, Ney and Tillmann 1996, the model, the jump width parameterization of the alignment probabilities, and the comparison with Model 2
  2. Och and Ney 2003, Section 2 (the HMM alignment model, Equations 12 to 16, and its extension with the empty word)
  3. Och and Ney 2000, the conference version of the empty word extension

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