Algorithmadvanced
Fast align
Also called diagonal reparameterization of IBM model 2.
A log-linear reparameterization of IBM model 2 that favors alignments near the diagonal, trained fast by EM with closed-form normalizers.
- Solves
- Word alignment
- Time
- Θ(n m l) worst
- Space
- Θ(l) extra
- Where
- l = the largest target length; m = the largest source length; n = the number of sentence pairs
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Chris Dyer, Victor Chahuneau, Noah A. Smith, 2013
Fast align is a word alignment model and its training method. It is IBM Model 2 with the table of alignment probabilities replaced by a log-linear distortion with one parameter , the tension, that pulls each source word toward the matching place on the diagonal of the sentence pair. The normalizer of the distortion is a sum of two geometric series, so it costs per position. The model is trained by EM, whose E step is exact and costs per pair. Dyer, Chahuneau and Smith (2013) measured it as about ten times faster to train than IBM Model 4, with similar BLEU in their translation systems.
In plain words
When you align the words of a sentence with the words of its translation, a word near the start usually goes with a word near the start, and a word near the end with one near the end. Fast align makes this a rule with one dial.
Each word of the source picks a partner in the target, or picks "no partner". The model likes partners that are close to the same relative place in the other sentence. The dial says how strongly. With the dial at zero, position does not matter. With a high dial, words stick to the diagonal.
Training repeats two steps. First, for each word, compute how likely each partner is now. Then count those guesses to update the word translation table and set the dial to the value that best fits the guesses. A simple formula for the sums makes each step fast.
The problem
The direction is , as for the IBM models. A pair has the source and the target , plus the null word . Each source position has one link . The model is
with and . The paper writes the model in the other direction, with for the target position and for the source length; this page uses the area notation. With the distortion is uniform over the real words, which is IBM Model 1 with a null word of fixed probability .
The task is to fit and to a parallel corpus by maximum likelihood, and then to output for each pair the best alignment.
The algorithm
FAST-ALIGN-EM(corpus, p_0, λ, K) ▷ EM; the direction is p(f | e)- 1
θ(f | e) ← 1 / |V_F| for every source word f and every target word e, NULL included - 2
repeat K times - 3
for each pair (f_1 .. f_m, e_1 .. e_l) and each j ← 1 to m do - 4
Z ← PARTITION(j, m, l, λ) - 5
w_0 ← p_0 θ(f_j | NULL); w_i ← (1 - p_0) e^{λ h(i, j, m, l)} / Z · θ(f_j | e_i) for i = 1 .. l - 6
for i ← 0 to l do q ← w_i / Σ w; c(f_j, e_i) += q; if i ≥ 1 then S += q h(i, j, m, l); N(j, m, l) += q - 7
θ(f | e) ← c(f, e) / Σ_{f'} c(f', e) - 8
λ ← the maximizer in [0, Λ] of λ S - Σ N(j, m, l) ln Z_λ(j, m, l), by bisection on its derivative - 9
return θ, λ PARTITION(j, m, l, λ) ▷ O(1)- 10
u ← floor(j l / m); r ← e^{-λ / l} - 11
return s_u(e^{λ h(u, j, m, l)}, r) + s_{l - u}(e^{λ h(u + 1, j, m, l)}, r) ▷ s_n(g, r) = g (1 - r^n) / (1 - r)
Line L1 starts from a uniform translation table. Lines L3 to L6 are the E step. By the distributive law, the posterior over the alignments is a product of one distribution per source position, so the expected count of a link is just its share of the sum at line L6. The variable collects the expected value of over the links to real words, and collects the posterior mass on real words at the positions with the same . Line L7 is the M step for , a normalization of the counts. Line L8 is the M step for . Its objective is concave, because is convex in , and its derivative is .
The partition function. The real position splits the targets into positions at or before it and after it. On each side, one step away from the diagonal multiplies by . So each side is a geometric series, and line L11 adds the two closed forms. In the same way, is a sum of two arithmetic-geometric series, also . The paper writes the second count as with , which is one term short; the right count is the number of positions after , which is . The tests check the closed form against the direct sum for all small .
This implementation and the paper. The paper fixes and starts with . It puts a Dirichlet prior on and estimates it by mean-field variational Bayes, and it updates by gradient steps. The code of this page uses plain EM for and an exact line search for , so the likelihood never decreases. The cap is .
Decoding. After training, the best alignment is found per source position: , with the smallest on a tie. This is exact for the model, because the alignment probability is a product of one factor per .
Example
Take , , and . The diagonal point is , so : two targets before it and five after. With ,
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | |
|---|---|---|---|---|---|---|---|
| -0.2571 | -0.1143 | -0.0286 | -0.1714 | -0.3143 | -0.4571 | -0.6 | |
| 0.3575 | 0.6331 | 0.8920 | 0.5037 | 0.2845 | 0.1606 | 0.0907 | |
| 0.1126 | 0.1993 | 0.2808 | 0.1586 | 0.0896 | 0.0506 | 0.0286 |
The lower series is and the upper series is , so , the sum of the middle row. The closest target, , gets the largest weight, and the weights fall by the factor per step on each side.
Now train on five German to English pairs: (das haus ist klein | the house is small), (das haus ist alt | the house is old), (das buch ist klein | the book is small), (ein buch | a book) and (klein ist das haus | the house is small), with and at the start.
| iteration | before | log likelihood before | |
|---|---|---|---|
| 0 | 4.0 | -35.0264 | 0.1429 |
| 1 | 4.0 | -20.2495 | 0.3652 |
| 2 | 6.4646 | -14.8438 | 0.5182 |
| 3 | 10.6607 | -11.1635 | 0.6511 |
| 4 | 16.8848 | -9.5740 | 0.6962 |
| 5 | 24.5069 | -9.2468 | 0.6843 |
In the first iteration stays at 4. With a uniform the posterior of each position equals its prior , so the expected under the posterior equals and the derivative at line L8 is zero. After that, four of the five pairs are monotone, and grows. The likelihood rises at each step. The Viterbi alignment of the last pair is : klein to the, ist to house, das to is, haus to small. The tension wins over the lexicon, and the pair that is not monotone is aligned wrongly. With fixed at 0, the same training aligns klein to small and haus to house in that pair.
Correctness
Three claims are exact. First, line L11 equals the sum : the split at puts each in exactly one geometric series. Second, lines L5 and L6 give the exact posterior counts, because is a product over . Third, each iteration does not lower the likelihood: line L7 maximizes the expected log likelihood in , line L8 does not lower it in , and the EM inequality turns a gain in the expected log likelihood into a gain in the likelihood. The full proof is in the proofs file.
EM can stop at a local maximum. The quality of the alignments is a measurement, not a theorem.
Proof: The fast align normalizer is a sum of two geometric series, and its EM never lowers the likelihoodfull
Notation as on the page. A pair has the source and the target , with and the null word . For and let , and for let . The distortion is and for , with .
The normalizer
Lemma 1. Let and . Then
where an empty sum is 0. So with for and .
Proof. Since , we have , so . By the definition of the floor, exactly when . For , , so and for . These are the terms with . For , , so and for . These are the other terms. Every in is in exactly one group. The closed form of is the finite geometric sum.
The count of the second series is , the number of target positions after . The implementation writes as , which is the same number and has no cancellation near .
Lemma 2. , and every .
Proof. as a sum of positive terms, and .
Lemma 3. is a convex function of , and , the mean of under the weights .
Proof. , so . Then , a variance, so it is .
is also : the numerator splits into the same two groups as in Lemma 1, and in each group it is , an arithmetic-geometric sum with a closed form.
The E step
The model is over all (the length of is given).
Lemma 4. , and the posterior is with .
Proof. The sum over of a product of factors that each depend on one is the product of the sums, by the distributive law. Divide by .
So the expected count of the link under the posterior is , which is what lines L5 and L6 compute. This costs per source position, per pair, instead of a sum over alignments.
Monotonicity
Let be the current parameters, and let
with computed from . The standard EM argument gives , where is the log likelihood. It follows from Jensen's inequality applied to . So it is enough that .
splits into a part in and a part in ( is fixed).
Lemma 5. Line L7 maximizes the part.
Proof. For each target word , the part is with . By Gibbs' inequality (the Kullback-Leibler divergence is non-negative) the maximum is at .
Lemma 6. The part is , with over the links with and the posterior mass on at the positions with these values. is concave, and its derivative is non-increasing.
Proof. for , and . Sum with the weights . Concavity and the derivative follow from Lemma 3 and .
So line L8 can find the maximum of on by bisection on the sign of the derivative: if the derivative is at 0 the maximum is at 0, if it is at the maximum is at , and otherwise bisection converges to the root. The implementation keeps the new only if , which holds for the exact maximizer and protects against the rounding of the bisection.
Theorem. One iteration of lines L3 to L8 gives parameters with a log likelihood at least that of the old ones.
Proof. By Lemma 5 the part of does not decrease, and by the test after line L8 the part does not decrease. So , and by the EM inequality.
This is a theorem about the likelihood only. EM can stop at a local maximum, because the log likelihood of Model 2 is not concave in . On data that is exactly diagonal, grows without bound and the best is , the cap of the implementation.
Complexity
In the real RAM model, with at unit cost: line L4 is by line L11, and lines L5 and L6 cost per source position. So the E step costs per pair and per iteration in the worst case. Line L7 costs one pass over the counts. Line L8 does bisection steps (60 in the code), each of which evaluates once per distinct triple , at most triples and in practice far fewer. A direct sum for and for would cost each time instead of . Dyer et al. report that computing the partition values for took 0.62 s with the closed form against 6.49 s with the direct sum (a measurement). The working memory is for the weights of one position plus the tables of counts and of .
Properties
- Few parameters. The distortion has one parameter, , against the table of Model 2, so it does not overfit rare lengths.
- Model 1 inside. At the distortion is uniform over the real words.
- Exact decoding. The best alignment is found per position in per pair.
- Not concave. The likelihood is not concave in , so the start matters. The paper uses no staged start from Model 1.
- Measured quality. On French to English and Chinese to English test sets, Dyer et al. report alignment error rates of 16.6 and 44.1 with the variational version, against 21.4 and 53.3 for Model 2 and 10.4 and 45.8 for Model 4. In their translation systems for Chinese, French and Arabic to English, BLEU was slightly higher than with Model 4 alignments (for example 27.7 against 27.4 for French). These are measurements on their data.
Variants and improvements
- Variational Bayes. A Dirichlet prior with a small concentration (0.01 in the paper) on makes the translation distributions sparse, which lowers the alignment error in their experiments.
- The reverse direction. Run the model with and swapped, then combine the two alignments with grow-diag-final or the intersection.
- Fixed tension. Without the optimization of line L8, stays at its start value, which is a common setting.
- HMM alignment. The HMM alignment model conditions each link on the previous one instead of on the diagonal, which handles blocks that move. It costs per pair.
When to use it
Use fast align to align a large corpus quickly before phrase pair extraction, or when you need many alignments for a quick experiment. It is best for language pairs with mostly monotone word order, such as French and English. For pairs with long distance reordering, the HMM model or Model 4 can align better, at a much higher cost. For a small corpus, the speed does not matter, and the choice should follow the alignment error rate or, better, the final translation quality.
Pitfalls
- One term short in line L11. With the count in the upper series, the farthest target is lost and does not sum to 1. Use .
- Cancellation near . The form loses digits when is close to 1. Compute it with expm1, as the code does, or switch to the direct sum.
- A tension that never stops. On data that is close to monotone, the optimum of line L8 can grow without bound, and then each source word is forced to the diagonal, as in the example. Cap , or keep it fixed.
- The wrong direction. normalizes over the target positions for each source position . If line L10 or L11 sums over instead, the weights of the choices of do not sum to , and the model is no longer a distribution over alignments.
- Products of probabilities. The likelihood of a long sentence is a product of hundreds of small numbers and underflows in double precision. Sum the logarithms of the per-position sums, as the code does.
Implementations
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/fast-align/. The authors are listed in prov/NW40F8.jsonl.
"""Fast align: IBM Model 2 with a diagonal distortion (Dyer, Chahuneau and Smith 2013).
Notation of the page, not of the paper. A pair is (f, e) with the source
f = f_1 .. f_m and the target e = e_1 .. e_l, plus the null word e_0 = NULL.
The model generates f from e (the direction p(f | e)); each source position j
has one link a_j in {0, .., l}. The distortion is
delta(0 | j, m, l) = p0,
delta(i | j, m, l) = (1 - p0) exp(lam * h(i, j, m, l)) / Z(j, m, l, lam), i >= 1,
h(i, j, m, l) = -|i / l - j / m|.
Z is a sum of two geometric series, so it costs O(1) (lines L10 and L11).
Training is EM. The E step is exact. The M step for theta is a normalization.
The M step for lam maximizes the expected log likelihood, which is concave in
lam, by bisection on its derivative; the new lam is kept only if it does not
lower that objective, so the likelihood never decreases. The paper uses
variational Bayes for theta and gradient steps for lam; this file uses plain
EM, as the page says.
"""
import math
from collections import defaultdict
from typing import Dict, List, Sequence, Tuple
NULL = "<null>"
Pair = Tuple[Sequence[str], Sequence[str]] # (f, e)
def h(i: int, j: int, m: int, l: int) -> float:
"""The feature -|i / l - j / m| of the link from source j to target i."""
return -abs(i / l - j / m)
def geo(g: float, log_r: float, n: int) -> float:
"""g + g r + .. + g r^(n-1) with r = exp(log_r) <= 1.
The form expm1(n log_r) / expm1(log_r) stays accurate when r is close to 1.
"""
if n <= 0:
return 0.0
if log_r == 0.0:
return g * n
return g * math.expm1(n * log_r) / math.expm1(log_r)
def partition(j: int, m: int, l: int, lam: float) -> float:
"""Z(j, m, l, lam) = sum over i = 1 .. l of exp(lam h(i, j, m, l)), in O(1)."""
i_up = (j * l) // m # @line L10
log_r = -lam / l
lower = geo(math.exp(lam * h(i_up, j, m, l)), log_r, i_up) if i_up >= 1 else 0.0
upper = geo(math.exp(lam * h(i_up + 1, j, m, l)), log_r, l - i_up) if i_up < l else 0.0
return lower + upper # @line L11
def partition_direct(j: int, m: int, l: int, lam: float) -> float:
"""The same sum, term by term, in O(l). For tests."""
return sum(math.exp(lam * h(i, j, m, l)) for i in range(1, l + 1))
def _arith_geo(a: float, d: float, g: float, r: float, n: int) -> float:
"""sum over k = 0 .. n-1 of (a + k d) g r^k."""
if n <= 0:
return 0.0
if 1.0 - r < 1e-4:
# the closed form cancels badly near r = 1; n <= l, so add the terms
return sum((a + k * d) * g * r**k for k in range(n))
s0 = (1.0 - r**n) / (1.0 - r)
s1 = r * (1.0 - n * r ** (n - 1) + (n - 1) * r**n) / (1.0 - r) ** 2
return g * (a * s0 + d * s1)
def expected_h(j: int, m: int, l: int, lam: float) -> float:
"""E[h] under exp(lam h(i)) / Z over i = 1 .. l, in O(1). This is d ln Z / d lam."""
i_up = (j * l) // m
r = math.exp(-lam / l)
num = 0.0
if i_up >= 1:
a = h(i_up, j, m, l)
num += _arith_geo(a, -1.0 / l, math.exp(lam * a), r, i_up)
if i_up < l:
a = h(i_up + 1, j, m, l)
num += _arith_geo(a, -1.0 / l, math.exp(lam * a), r, l - i_up)
return num / partition(j, m, l, lam)
def distortion(i: int, j: int, m: int, l: int, lam: float, p0: float) -> float:
"""delta(i | j, m, l)."""
if i == 0:
return p0
return (1.0 - p0) * math.exp(lam * h(i, j, m, l)) / partition(j, m, l, lam)
def _targets(e: Sequence[str]) -> List[str]:
return [NULL] + list(e)
def log_likelihood(corpus: Sequence[Pair], theta: Dict[Tuple[str, str], float], lam: float, p0: float) -> float:
"""sum over pairs and j of ln sum over i = 0 .. l of delta(i | j, m, l) theta(f_j | e_i)."""
total = 0.0
for f, e in corpus:
m, l, es = len(f), len(e), _targets(e)
for j in range(1, m + 1):
s = sum(distortion(i, j, m, l, lam, p0) * theta.get((f[j - 1], es[i]), 0.0) for i in range(l + 1))
total += math.log(s)
return total
def _lambda_objective(lam: float, s_h: float, mass: Dict[Tuple[int, int, int], float]) -> float:
"""The part of the expected log likelihood that depends on lam."""
return lam * s_h - sum(n * math.log(partition(j, m, l, lam)) for (j, m, l), n in mass.items())
def _lambda_step(lam: float, s_h: float, mass: Dict[Tuple[int, int, int], float],
lam_max: float = 100.0, steps: int = 60) -> float:
"""Maximize lam * s_h - sum n ln Z over [0, lam_max] by bisection on the derivative."""
def grad(x: float) -> float:
return s_h - sum(n * expected_h(j, m, l, x) for (j, m, l), n in mass.items())
if grad(0.0) <= 0.0:
best = 0.0
elif grad(lam_max) >= 0.0:
best = lam_max
else:
lo, hi = 0.0, lam_max
for _ in range(steps):
mid = (lo + hi) / 2.0
if grad(mid) > 0.0:
lo = mid
else:
hi = mid
best = (lo + hi) / 2.0
# keep the old value unless the new one is at least as good (generalized EM)
if _lambda_objective(best, s_h, mass) >= _lambda_objective(lam, s_h, mass):
return best
return lam
def em_step(corpus: Sequence[Pair], theta: Dict[Tuple[str, str], float], lam: float, p0: float,
optimize_lambda: bool = True) -> Tuple[Dict[Tuple[str, str], float], float]:
"""One EM iteration. Returns the new (theta, lam)."""
counts: Dict[Tuple[str, str], float] = defaultdict(float)
totals: Dict[str, float] = defaultdict(float)
s_h = 0.0
mass: Dict[Tuple[int, int, int], float] = defaultdict(float)
for f, e in corpus: # @line L3
m, l, es = len(f), len(e), _targets(e)
for j in range(1, m + 1):
z = partition(j, m, l, lam) # @line L4
w = [p0 * theta.get((f[j - 1], NULL), 0.0)]
for i in range(1, l + 1):
w.append((1.0 - p0) * math.exp(lam * h(i, j, m, l)) / z * theta.get((f[j - 1], es[i]), 0.0)) # @line L5
total = sum(w)
for i in range(l + 1): # @line L6
q = w[i] / total
counts[(f[j - 1], es[i])] += q
totals[es[i]] += q
if i >= 1:
s_h += q * h(i, j, m, l)
mass[(j, m, l)] += q
new_theta = {(x, y): c / totals[y] for (x, y), c in counts.items()} # @line L7
if optimize_lambda:
lam = _lambda_step(lam, s_h, mass) # @line L8
return new_theta, lam
def train(corpus: Sequence[Pair], iterations: int = 5, lam: float = 4.0, p0: float = 0.08,
optimize_lambda: bool = True) -> Tuple[Dict[Tuple[str, str], float], float, List[float]]:
"""Run EM. Returns theta, lam and the log likelihood before each iteration and at the end."""
vf = sorted({x for f, _ in corpus for x in f})
ve = sorted({y for _, e in corpus for y in e}) + [NULL]
theta = {(x, y): 1.0 / len(vf) for x in vf for y in ve} # @line L1
history = [log_likelihood(corpus, theta, lam, p0)]
for _ in range(iterations): # @line L2
theta, lam = em_step(corpus, theta, lam, p0, optimize_lambda)
history.append(log_likelihood(corpus, theta, lam, p0))
return theta, lam, history # @line L9
def viterbi_alignment(f: Sequence[str], e: Sequence[str], theta: Dict[Tuple[str, str], float],
lam: float, p0: float = 0.08) -> List[int]:
"""The best a_j for each j, chosen independently; the smallest i wins a tie. 0 is NULL."""
m, l, es = len(f), len(e), _targets(e)
out = []
for j in range(1, m + 1):
scores = [distortion(i, j, m, l, lam, p0) * theta.get((f[j - 1], es[i]), 0.0) for i in range(l + 1)]
out.append(max(range(l + 1), key=lambda i: (scores[i], -i)))
return out
test_fast_align.py 157 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fast-align/. The authors are listed in prov/NW40F8.jsonl.
import math
import random
from collections import defaultdict
from itertools import product
from fast_align import (
NULL,
distortion,
em_step,
expected_h,
geo,
h,
log_likelihood,
partition,
partition_direct,
train,
viterbi_alignment,
)
def test_partition_closed_form() -> None:
for m in range(1, 9):
for l in range(1, 9):
for j in range(1, m + 1):
for lam in (0.0, 1e-7, 0.3, 4.0, 25.0):
assert math.isclose(partition(j, m, l, lam), partition_direct(j, m, l, lam), rel_tol=1e-9)
def test_partition_term_count() -> None:
# above the diagonal point there are l - i_up terms; with one term fewer the last one is lost
j, m, l, lam = 2, 5, 7, 4.0
i_up = j * l // m
lower = geo(math.exp(lam * h(i_up, j, m, l)), -lam / l, i_up)
short = lower + geo(math.exp(lam * h(i_up + 1, j, m, l)), -lam / l, l - i_up - 1)
assert not math.isclose(short, partition_direct(j, m, l, lam), rel_tol=1e-6)
assert math.isclose(short + math.exp(lam * h(l, j, m, l)), partition_direct(j, m, l, lam), rel_tol=1e-12)
def test_expected_h() -> None:
for m, l, j in [(1, 1, 1), (3, 5, 2), (6, 4, 6), (7, 7, 3), (2, 9, 1)]:
for lam in (0.0, 0.5, 4.0, 30.0):
z = partition_direct(j, m, l, lam)
direct = sum(h(i, j, m, l) * math.exp(lam * h(i, j, m, l)) for i in range(1, l + 1)) / z
assert math.isclose(expected_h(j, m, l, lam), direct, rel_tol=1e-9, abs_tol=1e-12)
# it is the derivative of ln Z
eps = 1e-6
num = (math.log(partition(j, m, l, lam + eps)) - math.log(partition(j, m, l, lam + 2 * eps))) / -eps
assert math.isclose(expected_h(j, m, l, lam + 1.5 * eps), num, rel_tol=1e-4, abs_tol=1e-7)
def test_distortion_sums_to_one() -> None:
for m, l in [(1, 1), (4, 3), (5, 8)]:
for j in range(1, m + 1):
assert math.isclose(sum(distortion(i, j, m, l, 4.0, 0.08) for i in range(l + 1)), 1.0, rel_tol=1e-12)
# lam = 0 gives a uniform distortion over the real words, as in Model 1
assert all(math.isclose(distortion(i, 2, 3, 4, 0.0, 0.08), 0.92 / 4) for i in range(1, 5))
def random_corpus(rng: random.Random, n: int, vf: int, ve: int, lmax: int):
out = []
for _ in range(n):
m, l = rng.randint(1, lmax), rng.randint(1, lmax)
out.append(([f"f{rng.randrange(vf)}" for _ in range(m)], [f"e{rng.randrange(ve)}" for _ in range(l)]))
return out
def test_e_step_against_all_alignments() -> None:
rng = random.Random(3)
corpus = random_corpus(rng, 4, 3, 3, 3)
vf = sorted({x for f, _ in corpus for x in f})
ve = sorted({y for _, e in corpus for y in e}) + [NULL]
theta = {(x, y): rng.uniform(0.1, 1.0) for x in vf for y in ve}
for y in ve:
s = sum(theta[(x, y)] for x in vf)
for x in vf:
theta[(x, y)] /= s
lam, p0 = 2.5, 0.08
counts = defaultdict(float)
for f, e in corpus:
m, l, es = len(f), len(e), [NULL] + e
joint = {}
for a in product(range(l + 1), repeat=m):
p = 1.0
for j in range(1, m + 1):
p *= distortion(a[j - 1], j, m, l, lam, p0) * theta[(f[j - 1], es[a[j - 1]])]
joint[a] = p
z = sum(joint.values())
for a, p in joint.items():
for j in range(1, m + 1):
counts[(f[j - 1], es[a[j - 1]])] += p / z
totals = defaultdict(float)
for (x, y), c in counts.items():
totals[y] += c
new_theta, new_lam = em_step(corpus, theta, lam, p0, optimize_lambda=False)
assert new_lam == lam
for key, c in counts.items():
assert math.isclose(new_theta[key], c / totals[key[1]], rel_tol=1e-9)
# the likelihood is the log of the sum over all alignments
brute = 0.0
for f, e in corpus:
m, l, es = len(f), len(e), [NULL] + e
s = 0.0
for a in product(range(l + 1), repeat=m):
p = 1.0
for j in range(1, m + 1):
p *= distortion(a[j - 1], j, m, l, lam, p0) * theta[(f[j - 1], es[a[j - 1]])]
s += p
brute += math.log(s)
assert math.isclose(log_likelihood(corpus, theta, lam, p0), brute, rel_tol=1e-12)
def test_likelihood_never_decreases() -> None:
rng = random.Random(11)
for _ in range(3):
corpus = random_corpus(rng, 8, 5, 5, 6)
_, _, hist = train(corpus, iterations=6)
for a, b in zip(hist, hist[1:]):
assert b >= a - 1e-9
def test_diagonal_corpus() -> None:
# word k of e translates to word k of f, in the same order
rng = random.Random(5)
corpus = []
for _ in range(30):
n = rng.randint(3, 7)
ids = [rng.randrange(6) for _ in range(n)]
corpus.append(([f"f{k}" for k in ids], [f"e{k}" for k in ids]))
theta, lam, hist = train(corpus, iterations=5)
assert lam > 4.0
f, e = ["f1", "f1", "f2", "f1"], ["e1", "e1", "e2", "e1"]
assert viterbi_alignment(f, e, theta, lam) == [1, 2, 3, 4]
# without the tension every f1 goes to the first e1
assert viterbi_alignment(f, e, theta, 0.0) == [1, 1, 3, 1]
def test_lambda_fixed_option() -> None:
corpus = [(["a", "b"], ["x", "y"])]
_, lam, _ = train(corpus, iterations=2, lam=4.0, optimize_lambda=False)
assert lam == 4.0
def test_long_sentence_no_underflow() -> None:
# with theta uniform over 50 source words, each position has probability 1/50
m = 200
f = [f"f{j % 50}" for j in range(m)]
e = [f"e{j % 50}" for j in range(m)]
theta, lam, hist = train([(f, e)], iterations=0)
probs = []
for j in range(1, m + 1):
probs.append(sum(distortion(i, j, m, m, lam, 0.08) * theta.get((f[j - 1], ([NULL] + e)[i]), 0.0)
for i in range(m + 1)))
assert math.prod(probs) == 0.0
assert math.isclose(hist[0], -m * math.log(50), rel_tol=1e-12)
History
Brown, Della Pietra, Della Pietra and Mercer (1993) defined Model 2 with a table of alignment probabilities. Chris Dyer, Victor Chahuneau and Noah Smith (2013) replaced that table by the diagonal distortion with one parameter, showed the closed form of its normalizer and of its gradient, and trained with variational Bayes. Their tool, fast_align, became a common choice to align large corpora because it trains in a fraction of the time of the IBM Model 4 pipeline (17.2 CPU hours against 1.7 for one direction of 117 million French to English tokens, in their measurement).
References
- Dyer, Chahuneau and Smith 2013, Section 2 (the model, the closed-form partition function and the gradient of lambda), Section 3 (the experiments, Tables 1 to 3)
- Brown et al. 1993, Section 4.2 (Model 2)
- Philipp Koehn, Statistical Machine Translation, Cambridge University Press, 2010, Section 4.4 (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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag NW40F8 Edit this page History Report an error Markdown