Algorithm Search⌘K

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.

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
Properties
deterministicnot exactofflineiterative
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 λ\lambda, 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 O(1)O(1) per position. The model is trained by EM, whose E step is exact and costs O(lm)O(l m) 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 p(f∣e)p(f \mid e), as for the IBM models. A pair has the source f=f1…fmf = f_1 \ldots f_m and the target e=e1…ele = e_1 \ldots e_l, plus the null word e0e_0. Each source position jj has one link aj∈{0,…,l}a_j \in \{0, \ldots, l\}. The model is

p(f,a∣e)=∏j=1mδ(aj∣j,m,l)  θ(fj∣eaj),p(f, a \mid e) = \prod_{j=1}^{m} \delta(a_j \mid j, m, l)\; \theta(f_j \mid e_{a_j}),
δ(i∣j,m,l)={p0i=0,(1−p0) eλh(i,j,m,l)Zλ(j,m,l)1≤i≤l,h(i,j,m,l)=−∣il−jm∣,\delta(i \mid j, m, l) = \begin{cases} p_0 & i = 0, \\ (1 - p_0)\, \dfrac{e^{\lambda h(i, j, m, l)}}{Z_\lambda(j, m, l)} & 1 \le i \le l, \end{cases} \qquad h(i, j, m, l) = -\left| \frac{i}{l} - \frac{j}{m} \right|,

with Zλ(j,m,l)=∑i=1leλh(i,j,m,l)Z_\lambda(j, m, l) = \sum_{i=1}^{l} e^{\lambda h(i, j, m, l)} and λ≥0\lambda \ge 0. The paper writes the model in the other direction, with ii for the target position and nn for the source length; this page uses the area notation. With λ=0\lambda = 0 the distortion is uniform over the real words, which is IBM Model 1 with a null word of fixed probability p0p_0.

The task is to fit θ\theta and λ\lambda to a parallel corpus by maximum likelihood, and then to output for each pair the best alignment.

The algorithm

  1. FAST-ALIGN-EM(corpus, p_0, λ, K) ▷ EM; the direction is p(f | e)
  2. 1θ(f | e) ← 1 / |V_F| for every source word f and every target word e, NULL included
  3. 2repeat K times
  4. 3for each pair (f_1 .. f_m, e_1 .. e_l) and each j ← 1 to m do
  5. 4Z ← PARTITION(j, m, l, λ)
  6. 5w_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
  7. 6for 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
  8. 7θ(f | e) ← c(f, e) / Σ_{f'} c(f', e)
  9. 8λ ← the maximizer in [0, Λ] of λ S - Σ N(j, m, l) ln Z_λ(j, m, l), by bisection on its derivative
  10. 9return θ, λ
  11. PARTITION(j, m, l, λ) ▷ O(1)
  12. 10u ← floor(j l / m); r ← e^{-λ / l}
  13. 11return 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 (l+1)m(l + 1)^m alignments is a product of one distribution per source position, so the expected count of a link is just its share qq of the sum at line L6. The variable SS collects the expected value of hh over the links to real words, and N(j,m,l)N(j, m, l) collects the posterior mass on real words at the positions with the same (j,m,l)(j, m, l). Line L7 is the M step for θ\theta, a normalization of the counts. Line L8 is the M step for λ\lambda. Its objective is concave, because ln⁡Zλ\ln Z_\lambda is convex in λ\lambda, and its derivative is S−∑N(j,m,l) Eλ[h∣j,m,l]S - \sum N(j, m, l)\, E_\lambda[h \mid j, m, l].

The partition function. The real position jl/mj l / m splits the targets into u=⌊jl/m⌋u = \lfloor j l / m \rfloor positions at or before it and l−ul - u after it. On each side, one step away from the diagonal multiplies eλhe^{\lambda h} by r=e−λ/lr = e^{-\lambda / l}. So each side is a geometric series, and line L11 adds the two closed forms. In the same way, Eλ[h]E_\lambda[h] is a sum of two arithmetic-geometric series, also O(1)O(1). The paper writes the second count as n−j↓n - j_\downarrow with j↓=j↑+1j_\downarrow = j_\uparrow + 1, which is one term short; the right count is the number of positions after uu, which is l−ul - u. The tests check the closed form against the direct sum for all small (j,m,l)(j, m, l).

This implementation and the paper. The paper fixes p0=0.08p_0 = 0.08 and starts with λ=4\lambda = 4. It puts a Dirichlet prior on θ\theta and estimates it by mean-field variational Bayes, and it updates λ\lambda by gradient steps. The code of this page uses plain EM for θ\theta and an exact line search for λ\lambda, so the likelihood never decreases. The cap is Λ=100\Lambda = 100.

Decoding. After training, the best alignment is found per source position: aj=arg⁡max⁡iδ(i∣j,m,l) θ(fj∣ei)a_j = \arg\max_i \delta(i \mid j, m, l)\, \theta(f_j \mid e_i), with the smallest ii on a tie. This is exact for the model, because the alignment probability is a product of one factor per jj.

Example

Take j=2j = 2, m=5m = 5, l=7l = 7 and λ=4\lambda = 4. The diagonal point is jl/m=2.8j l / m = 2.8, so u=2u = 2: two targets before it and five after. With r=e−4/7=0.5647r = e^{-4/7} = 0.5647,

ii 1 2 3 4 5 6 7
h(i)h(i) -0.2571 -0.1143 -0.0286 -0.1714 -0.3143 -0.4571 -0.6
eλh(i)e^{\lambda h(i)} 0.3575 0.6331 0.8920 0.5037 0.2845 0.1606 0.0907
δ(i∣2,5,7)\delta(i \mid 2, 5, 7) 0.1126 0.1993 0.2808 0.1586 0.0896 0.0506 0.0286

The lower series is 0.6331(1+r)=0.99060.6331 (1 + r) = 0.9906 and the upper series is 0.8920(1−r5)/(1−r)=1.93150.8920 (1 - r^5)/(1 - r) = 1.9315, so Z=2.9222Z = 2.9222, the sum of the middle row. The closest target, i=3i = 3, gets the largest weight, and the weights fall by the factor rr 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 p0=0.08p_0 = 0.08 and λ=4\lambda = 4 at the start.

iteration λ\lambda before log likelihood before θ(haus∣house)\theta(\text{haus} \mid \text{house})
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 λ\lambda stays at 4. With a uniform θ\theta the posterior of each position equals its prior δ\delta, so the expected hh under the posterior equals Eλ[h]E_\lambda[h] and the derivative at line L8 is zero. After that, four of the five pairs are monotone, and λ\lambda grows. The likelihood rises at each step. The Viterbi alignment of the last pair is (1,2,3,4)(1, 2, 3, 4): 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 λ\lambda 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 ∑i=1leλh(i)\sum_{i=1}^l e^{\lambda h(i)}: the split at uu puts each ii in exactly one geometric series. Second, lines L5 and L6 give the exact posterior counts, because p(a∣f,e)p(a \mid f, e) is a product over jj. Third, each iteration does not lower the likelihood: line L7 maximizes the expected log likelihood in θ\theta, line L8 does not lower it in λ\lambda, 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 f1…fmf_1 \ldots f_m and the target e1…ele_1 \ldots e_l, with m,l≥1m, l \ge 1 and the null word e0e_0. For 1≤j≤m1 \le j \le m and 1≤i≤l1 \le i \le l let h(i)=h(i,j,m,l)=−∣i/l−j/m∣h(i) = h(i, j, m, l) = -|i/l - j/m|, and for λ≥0\lambda \ge 0 let Z=∑i=1leλh(i)Z = \sum_{i=1}^{l} e^{\lambda h(i)}. The distortion is δ(0)=p0\delta(0) = p_0 and δ(i)=(1−p0)eλh(i)/Z\delta(i) = (1 - p_0) e^{\lambda h(i)} / Z for i≥1i \ge 1, with 0<p0<10 < p_0 < 1.

The normalizer

Lemma 1. Let u=⌊jl/m⌋u = \lfloor j l / m \rfloor and r=e−λ/lr = e^{-\lambda / l}. Then

Z=∑k=0u−1eλh(u)rk+∑k=0l−u−1eλh(u+1)rk,Z = \sum_{k=0}^{u-1} e^{\lambda h(u)} r^k + \sum_{k=0}^{l-u-1} e^{\lambda h(u+1)} r^k,

where an empty sum is 0. So Z=su(eλh(u),r)+sl−u(eλh(u+1),r)Z = s_u(e^{\lambda h(u)}, r) + s_{l-u}(e^{\lambda h(u+1)}, r) with sn(g,r)=g(1−rn)/(1−r)s_n(g, r) = g(1 - r^n)/(1 - r) for r<1r < 1 and sn(g,1)=gns_n(g, 1) = g n.

Proof. Since 1≤j≤m1 \le j \le m, we have 0<jl/m≤l0 < j l / m \le l, so 0≤u≤l0 \le u \le l. By the definition of the floor, i/l≤j/mi / l \le j / m exactly when i≤ui \le u. For 1≤i≤u1 \le i \le u, h(i)=i/l−j/mh(i) = i/l - j/m, so h(u−k)=h(u)−k/lh(u - k) = h(u) - k/l and eλh(u−k)=eλh(u)rke^{\lambda h(u-k)} = e^{\lambda h(u)} r^k for k=0,…,u−1k = 0, \ldots, u - 1. These are the uu terms with i≤ui \le u. For u+1≤i≤lu + 1 \le i \le l, h(i)=j/m−i/lh(i) = j/m - i/l, so h(u+1+k)=h(u+1)−k/lh(u + 1 + k) = h(u + 1) - k/l and eλh(u+1+k)=eλh(u+1)rke^{\lambda h(u+1+k)} = e^{\lambda h(u+1)} r^k for k=0,…,l−u−1k = 0, \ldots, l - u - 1. These are the other l−ul - u terms. Every ii in 1…l1 \ldots l is in exactly one group. The closed form of sns_n is the finite geometric sum. □\square

The count of the second series is l−ul - u, the number of target positions after uu. The implementation writes sns_n as g⋅expm1(nln⁡r)/expm1(ln⁡r)g \cdot \mathrm{expm1}(n \ln r) / \mathrm{expm1}(\ln r), which is the same number and has no cancellation near r=1r = 1.

Lemma 2. ∑i=0lδ(i)=1\sum_{i=0}^{l} \delta(i) = 1, and every δ(i)>0\delta(i) > 0.

Proof. Z>0Z > 0 as a sum of positive terms, and ∑i≥1(1−p0)eλh(i)/Z=1−p0\sum_{i \ge 1} (1 - p_0) e^{\lambda h(i)} / Z = 1 - p_0. □\square

Lemma 3. ln⁡Z\ln Z is a convex function of λ\lambda, and ddλln⁡Z=Eλ[h]\frac{d}{d\lambda} \ln Z = E_\lambda[h], the mean of h(i)h(i) under the weights eλh(i)/Ze^{\lambda h(i)} / Z.

Proof. Z′=∑ih(i)eλh(i)Z' = \sum_i h(i) e^{\lambda h(i)}, so (ln⁡Z)′=Z′/Z=Eλ[h](\ln Z)' = Z'/Z = E_\lambda[h]. Then (ln⁡Z)′′=Eλ[h2]−Eλ[h]2(\ln Z)'' = E_\lambda[h^2] - E_\lambda[h]^2, a variance, so it is ≥0\ge 0. □\square

Eλ[h]E_\lambda[h] is also O(1)O(1): the numerator ∑ih(i)eλh(i)\sum_i h(i) e^{\lambda h(i)} splits into the same two groups as in Lemma 1, and in each group it is ∑k(a−k/l) g rk\sum_k (a - k/l)\, g\, r^k, an arithmetic-geometric sum with a closed form.

The E step

The model is p(f,a∣e)=∏j=1mδ(aj∣j,m,l) θ(fj∣eaj)p(f, a \mid e) = \prod_{j=1}^m \delta(a_j \mid j, m, l)\, \theta(f_j \mid e_{a_j}) over all a∈{0,…,l}ma \in \{0, \ldots, l\}^m (the length of ff is given).

Lemma 4. p(f∣e)=∏j=1m∑i=0lδ(i∣j) θ(fj∣ei)p(f \mid e) = \prod_{j=1}^m \sum_{i=0}^l \delta(i \mid j)\, \theta(f_j \mid e_i), and the posterior is p(a∣f,e)=∏jqj(aj)p(a \mid f, e) = \prod_j q_j(a_j) with qj(i)=δ(i∣j)θ(fj∣ei)/∑i′δ(i′∣j)θ(fj∣ei′)q_j(i) = \delta(i \mid j) \theta(f_j \mid e_i) / \sum_{i'} \delta(i' \mid j) \theta(f_j \mid e_{i'}).

Proof. The sum over aa of a product of factors that each depend on one aja_j is the product of the sums, by the distributive law. Divide p(f,a∣e)p(f, a \mid e) by p(f∣e)p(f \mid e). □\square

So the expected count of the link (fj,ei)(f_j, e_i) under the posterior is qj(i)q_j(i), which is what lines L5 and L6 compute. This costs O(l)O(l) per source position, O(lm)O(l m) per pair, instead of a sum over (l+1)m(l + 1)^m alignments.

Monotonicity

Let ϕ=(θ,λ)\phi = (\theta, \lambda) be the current parameters, and let

Q(ϕ′)=∑pairs∑j∑iqj(i)(ln⁡θ′(fj∣ei)+ln⁡δ′(i∣j)),Q(\phi') = \sum_{\text{pairs}} \sum_{j} \sum_{i} q_j(i) \bigl( \ln \theta'(f_j \mid e_i) + \ln \delta'(i \mid j) \bigr),

with qq computed from ϕ\phi. The standard EM argument gives L(ϕ′)−L(ϕ)≥Q(ϕ′)−Q(ϕ)L(\phi') - L(\phi) \ge Q(\phi') - Q(\phi), where LL is the log likelihood. It follows from Jensen's inequality applied to ln⁡∑ap(a∣f,e;ϕ)⋅p(f,a∣e;ϕ′)/p(f,a∣e;ϕ)\ln \sum_a p(a \mid f, e; \phi) \cdot p(f, a \mid e; \phi') / p(f, a \mid e; \phi). So it is enough that Q(ϕ′)≥Q(ϕ)Q(\phi') \ge Q(\phi).

QQ splits into a part in θ′\theta' and a part in λ′\lambda' (p0p_0 is fixed).

Lemma 5. Line L7 maximizes the θ′\theta' part.

Proof. For each target word ee, the θ′\theta' part is ∑fc(f,e)ln⁡θ′(f∣e)\sum_f c(f, e) \ln \theta'(f \mid e) with ∑fθ′(f∣e)=1\sum_f \theta'(f \mid e) = 1. By Gibbs' inequality (the Kullback-Leibler divergence is non-negative) the maximum is at θ′(f∣e)=c(f,e)/∑f′c(f′,e)\theta'(f \mid e) = c(f, e) / \sum_{f'} c(f', e). □\square

Lemma 6. The λ′\lambda' part is G(λ′)=λ′S−∑(j,m,l)Njmlln⁡Z(j,m,l,λ′)+constG(\lambda') = \lambda' S - \sum_{(j, m, l)} N_{j m l} \ln Z(j, m, l, \lambda') + \text{const}, with S=∑qj(i)h(i)S = \sum q_j(i) h(i) over the links with i≥1i \ge 1 and NjmlN_{jml} the posterior mass on i≥1i \ge 1 at the positions with these values. GG is concave, and its derivative S−∑NjmlEλ′[h]S - \sum N_{jml} E_{\lambda'}[h] is non-increasing.

Proof. ln⁡δ′(i)=ln⁡(1−p0)+λ′h(i)−ln⁡Z\ln \delta'(i) = \ln(1 - p_0) + \lambda' h(i) - \ln Z for i≥1i \ge 1, and ln⁡δ′(0)=ln⁡p0\ln \delta'(0) = \ln p_0. Sum with the weights qj(i)q_j(i). Concavity and the derivative follow from Lemma 3 and Njml≥0N_{jml} \ge 0. □\square

So line L8 can find the maximum of GG on [0,Λ][0, \Lambda] by bisection on the sign of the derivative: if the derivative is ≤0\le 0 at 0 the maximum is at 0, if it is ≥0\ge 0 at Λ\Lambda the maximum is at Λ\Lambda, and otherwise bisection converges to the root. The implementation keeps the new λ′\lambda' only if G(λ′)≥G(λ)G(\lambda') \ge G(\lambda), 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 θ′\theta' part of QQ does not decrease, and by the test after line L8 the λ′\lambda' part does not decrease. So Q(ϕ′)≥Q(ϕ)Q(\phi') \ge Q(\phi), and L(ϕ′)≥L(ϕ)L(\phi') \ge L(\phi) by the EM inequality. □\square

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 (θ,λ)(\theta, \lambda). On data that is exactly diagonal, GG grows without bound and the best λ\lambda is Λ\Lambda, the cap of the implementation.

Complexity

In the real RAM model, with exe^x at unit cost: line L4 is O(1)O(1) by line L11, and lines L5 and L6 cost O(l)O(l) per source position. So the E step costs Θ(lm)\Theta(l m) per pair and Θ(nml)\Theta(n m l) per iteration in the worst case. Line L7 costs one pass over the counts. Line L8 does BB bisection steps (60 in the code), each of which evaluates Eλ[h]E_\lambda[h] once per distinct triple (j,m,l)(j, m, l), at most nmn m triples and in practice far fewer. A direct sum for ZZ and for Eλ[h]E_\lambda[h] would cost O(l)O(l) each time instead of O(1)O(1). Dyer et al. report that computing the partition values for 0<i,m,n<1500 < i, m, n < 150 took 0.62 s with the closed form against 6.49 s with the direct sum (a measurement). The working memory is Θ(l)\Theta(l) for the weights of one position plus the tables of counts and of θ\theta.

Properties

  • Few parameters. The distortion has one parameter, λ\lambda, against the table a(i∣j,l,m)a(i \mid j, l, m) of Model 2, so it does not overfit rare lengths.
  • Model 1 inside. At λ=0\lambda = 0 the distortion is uniform over the real words.
  • Exact decoding. The best alignment is found per position in O(lm)O(l m) per pair.
  • Not concave. The likelihood is not concave in (θ,λ)(\theta, \lambda), 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 θ\theta makes the translation distributions sparse, which lowers the alignment error in their experiments.
  • The reverse direction. Run the model with ff and ee swapped, then combine the two alignments with grow-diag-final or the intersection.
  • Fixed tension. Without the optimization of line L8, λ\lambda 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 O(l2m)O(l^2 m) 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 l−u−1l - u - 1 in the upper series, the farthest target i=li = l is lost and δ\delta does not sum to 1. Use l−ul - u.
  • Cancellation near λ=0\lambda = 0. The form (1−rn)/(1−r)(1 - r^n)/(1 - r) loses digits when rr 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 λ\lambda, or keep it fixed.
  • The wrong direction. δ\delta normalizes over the target positions ii for each source position jj. If line L10 or L11 sums over jj instead, the weights of the choices of aja_j do not sum to 1−p01 - p_0, 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.

fast_align.pyI0RawGitHub
# 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 θ\theta 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

  1. 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)
  2. Brown et al. 1993, Section 4.2 (Model 2)
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
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)
WritingW2 basic
  • a scene preset for the example