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 of the target sentence . As the model reads the source sentence from left to right, it moves from the position aligned to to the position aligned to , and the probability of the move depends only on its width . Each state emits its source word from the table 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 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 and , with the null word . An alignment is with , in the direction : source word is generated by target word . The reverse direction is a different model and gives different alignments; the two are often combined by grow-diag-final.
Parameters.
- , with a row for the null word;
- a weight for each jump width ; for a sentence of length the jump from position to position has probability (Vogel et al. 1996);
- the null probability , a fixed number. The code uses , 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 is "null, after position ". From a state that remembers position (the real state or the null state ), the model goes to the null state of with probability , or to a real position with probability times the jump probability from to . This page writes for the last real position aligned at or before . The code also puts a virtual position 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
For example, with , , , , and , the next word goes to position 1, 2 or 3 with probabilities , and , 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:
HMM-ALIGNMENT-EM-ROUND(corpus, t, c)- 1
for each pair (f, e) in the corpus do - 2
α ← the forward table of ln probabilities, from the jumps out of position 0 - 3
β ← the backward table of ln probabilities - 4
ln p(f | e) ← ln Σ_s exp α_m(s) - 5
for 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) - 6
for each j and real position i: add the expected number of jumps r → i at j to N(r, i, l) - 7
t(f | e) ← c_t(f, e) / Σ_f' c_t(f', e) - 8
c' ← the count update: c'(d) proportional to Σ over i - r = d of N(r, i, l) - 9
c ← the best of c and c', improved by gradient ascent on Q(ln c), keeping only steps that raise Q - 10
return 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 , the jump, the emission and the backward value at . Line L7 is the exact M step for .
The jump step. The M step for maximizes . The rows have different normalizers, so the simple count update of line L8 is not the maximizer. From uniform and uniform , every row of posteriors is uniform and uniform is optimal, but small widths occur in more rows, so the count update favours them and lowers ; the tests show such a case. In , 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 is translated in place by , with random words and lengths 2 to 5, trained from uniform and with the null word:
| round | log likelihood | share of | |
|---|---|---|---|
| 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 learns the lexicon while stays near uniform. Then the jump of width 1 takes most of the weight. For the pair the trained model gives the alignment . With the same and uniform jumps the two copies of tie, and the tie rule gives . These numbers are a measurement on a toy corpus.
What it counts
The model assigns , a sum over alignments. One step is one arithmetic operation on real numbers, as on the real RAM. With states and transitions that are dense among the real states, the costs per pair are:
| Task | Algorithm | Cost |
|---|---|---|
| forward algorithm | ||
| posteriors of links and jumps (E step) | forward-backward | |
| best alignment | Viterbi algorithm | |
| the same by enumeration |
The M step for is linear in the size of the counts. The jump step works on the counts , whose number is at most the number of distinct 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 , and the emission matrix is tied through .
- IBM Model 1. With all equal and no null word, every jump has probability , and the model is Model 1 without the null word. The tests check this.
- IBM Model 2. In Model 2 the position depends on and the lengths, not on . 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 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 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 . 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 , 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 of Model 1 (Och and Ney 2003).
- Underflow. A pair of 200 source words, each with probability , has , which is 0 in double precision. The log-space forward pass returns ; 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.
# 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
- Vogel, Ney and Tillmann 1996, the model, the jump width parameterization of the alignment probabilities, and the comparison with Model 2
- Och and Ney 2003, Section 2 (the HMM alignment model, Equations 12 to 16, and its extension with the empty word)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag S290AK Edit this page History Report an error Markdown