Algorithm Search⌘K

Algorithmcore

Grow-diag-final symmetrization

Also called alignment symmetrization.

Combine the alignments of the two directions by starting from their intersection and adding neighbouring links from their union.

Time
O(m l (m + l)) worst
Space
O(m l) extra
Where
l = the target sentence length; m = the source sentence length
Properties
deterministicnot exactofflineiterative
Origin
Franz Josef Och, Hermann Ney, Philipp Koehn, Daniel Marcu, 2003

Grow-diag-final is a heuristic that combines two one-directional word alignments of a sentence pair into one set of links. It starts from the links that both directions agree on, then adds links from either direction that touch an already aligned word through one of the 8 neighbouring cells (the grow-diag step), and at the end adds the remaining links whose words are still unaligned (the final step). It goes back to the refined method of Och and Ney (2003), and in the form of the Moses toolkit it is the usual input to phrase pair extraction. It optimizes no objective. Its result depends on the order of its loops, so this page follows the Moses pseudocode exactly.

In plain words

Word alignment models such as IBM Model 1 or the HMM model link words in one direction only. Each word of one side gets at most one partner on the other side, so the model cannot link one word to two words. Run the model in both directions and you get two different sets of links.

The links that both sets share are very likely right, but there are too few of them. All links of both sets together cover more, but many are wrong. Grow-diag-final starts from the shared links and adds more. A link from either set is added if it sits right next to a link already kept, also on a diagonal, and if one of its two words still has no partner. When nothing more can be added this way, any link that gives a partner to a word that still has none is added too.

The problem

The input is a sentence pair with the source f1…fmf_1 \ldots f_m and the target e1…ele_1 \ldots e_l, and two link sets A1,A2⊆{1,…,m}×{1,…,l}A_1, A_2 \subseteq \{1, \ldots, m\} \times \{1, \ldots, l\} of pairs (j,i)(j, i). Usually A1={(j,aj):aj>0}A_1 = \{(j, a_j) : a_j > 0\} comes from a model of p(f∣e)p(f \mid e), where each source word has at most one link, and A2={(bi,i):bi>0}A_2 = \{(b_i, i) : b_i > 0\} from a model of p(e∣f)p(e \mid f), where each target word has at most one link. The output is one link set AA that can be many to many. The intersection A1∩A2A_1 \cap A_2 has high precision and the union A1∪A2A_1 \cup A_2 has high recall, in the measurements of Och and Ney (2003). A good AA lies between them.

There is no objective function here. The task is a design choice, and the quality of the result is measured with the alignment error rate against hand alignments, or by the translation quality of a system trained on it.

The algorithm

Moses writes the neighbours as offsets (Δi,Δj)(\Delta i, \Delta j) of the target and the source position, in the order (−1,0),(0,−1),(1,0),(0,1),(−1,−1),(−1,1),(1,−1),(1,1)(-1,0), (0,-1), (1,0), (0,1), (-1,-1), (-1,1), (1,-1), (1,1): first the four direct neighbours, then the four diagonal ones. A word is aligned if it has a link in the current set AA.

  1. GROW-DIAG-FINAL(A_1, A_2, m, l) ▷ links (j, i); Moses calls A_1 e2f and A_2 f2e
  2. 1A ← A_1 ∩ A_2; U ← A_1 ∪ A_2
  3. 2repeat
  4. 3added ← false
  5. 4for i ← 1 to l do for j ← 1 to m do ▷ target outer, source inner
  6. 5if (j, i) ∈ A then
  7. 6for each (Δi, Δj) in the 8 neighbour offsets, in the order above do
  8. 7p ← (j + Δj, i + Δi)
  9. 8if p ∈ U and (the source word of p or the target word of p is unaligned) then A ← A ∪ {p}; added ← true
  10. 9until not added
  11. 10for each B in (A_1, A_2) do ▷ FINAL(e2f), then FINAL(f2e)
  12. 11for i ← 1 to l do for j ← 1 to m do
  13. 12if (j, i) ∈ B and (j or i is unaligned) then A ← A ∪ {(j, i)}
  14. 13return A

Line L1 starts from the intersection. Lines L2 to L9 are the grow-diag step: each pass walks over all cells, and for each kept link it tries the 8 neighbours. A neighbour is added only if it is a link of one of the two directions and it brings a new word into the alignment. A link added in a pass is visible at once, to the rest of the same pass. The passes repeat until one adds nothing. Lines L10 to L12 are the final step: for links that are not next to anything, the only test is that one of their words is still unaligned.

The other heuristics of Moses. The same documentation lists intersection (line L1 only), union, grow (only the four direct neighbours), grow-diag (no final step) and the two single directions. Grow-diag-final is the default there.

Grow-diag-final-and. A common variant asks at line L12 that both words are unaligned. It adds fewer isolated links. It is not on the Moses documentation page that this page follows; it is an option of the Moses training scripts.

Example

Take ff = ich gehe nicht nach hause and ee = i do not go home (m=l=5m = l = 5). The direction p(f∣e)p(f \mid e) gives a=(1,4,3,5,5)a = (1, 4, 3, 5, 5): ich to i, gehe to go, nicht to not, nach to home and hause to home. The direction p(e∣f)p(e \mid f) gives b=(1,2,3,2,5)b = (1, 2, 3, 2, 5): i to ich, do to gehe, not to nicht, go to gehe and home to hause. So

A1={(1,1),(2,4),(3,3),(4,5),(5,5)}A_1 = \{(1,1), (2,4), (3,3), (4,5), (5,5)\}, A2={(1,1),(2,2),(3,3),(2,4),(5,5)}A_2 = \{(1,1), (2,2), (3,3), (2,4), (5,5)\}, A1∩A2={(1,1),(2,4),(3,3),(5,5)}A_1 \cap A_2 = \{(1,1), (2,4), (3,3), (5,5)\}, and U∖(A1∩A2)={(2,2),(4,5)}U \setminus (A_1 \cap A_2) = \{(2,2), (4,5)\}.

In the intersection, the target word do (i=2i = 2) and the source word nach (j=4j = 4) are unaligned. The first pass of lines L4 to L8 goes like this.

visit (j,i)(j, i) neighbour tried in UU? unaligned word action
(1, 1) ich, i (1, 2), (2, 1) no
(1, 1) (Δi,Δj)=(1,1)(\Delta i, \Delta j) = (1, 1): (2, 2) gehe, do yes do add (2, 2)
(2, 2) gehe, do all 8 (1, 1), (3, 3) are in AA none
(3, 3) nicht, not (2, 2), (2, 4) in AA none
(2, 4) gehe, go all 8 only (3, 3), which is in AA none
(5, 5) hause, home (0,−1)(0, -1): (4, 5) nach, home yes nach add (4, 5)

The second pass adds nothing, and the final step finds no link of A1A_1 or A2A_2 with an unaligned word. The result is {(1,1),(2,2),(2,4),(3,3),(4,5),(5,5)}\{(1,1), (2,2), (2,4), (3,3), (4,5), (5,5)\}, which here is the whole union: gehe is linked to both do and go, and home to both nach and hause. Without the diagonal neighbours (the grow heuristic), (2, 2) would not be added, because none of its four direct neighbours is a link; it would come back only in a final step.

On other inputs the result is strictly between the intersection and the union. For a=(2,4,3,1,4)a = (2, 4, 3, 1, 4) and b=(5,1,1,2,1)b = (5, 1, 1, 2, 1), the union has 8 links, the intersection 2, grow-diag keeps 5, grow-diag-final 7 and grow-diag-final-and 6. The link (5, 1) of A2A_2 is never added, because by then both of its words are aligned.

Correctness

The procedure is a heuristic, so "correct" means it does what it states. Four facts hold, and the proofs file proves them. The working set always lies between the intersection and the union, because every added link is in the union and nothing is removed. The loop of lines L2 to L9 ends after at most ∣U∖I∣+1|U \setminus I| + 1 passes, because each pass that goes on adds a new link of UU. When it ends, no link of UU next to a kept link has an unaligned word. After the final step, every word that has a link in A1A_1 or in A2A_2 is aligned. The last fact fails for the variant with "and".

Proof: Grow-diag-final terminates, stays between the intersection and the union, and aligns every word that either direction alignsfull

Let A1,A2⊆{1,…,m}×{1,…,l}A_1, A_2 \subseteq \{1, \ldots, m\} \times \{1, \ldots, l\} be the two link sets, with links (j,i)(j, i), and let I=A1∩A2I = A_1 \cap A_2 and U=A1∪A2U = A_1 \cup A_2. Let AA be the working set of GROW-DIAG-FINAL. A source word jj is aligned in AA if some (j,i)∈A(j, i) \in A, and a target word ii likewise. The procedure only adds links; it never removes one.

Lemma 1 (bounds). At every moment, I⊆A⊆UI \subseteq A \subseteq U.

Proof. Line L1 sets A=I⊆UA = I \subseteq U. Line L8 adds a link only if it is in UU. Line L12 adds a link only if it is in A1A_1 or in A2A_2, so in UU. Nothing is removed, so I⊆AI \subseteq A stays true. □\square

Lemma 2 (termination). The loop of lines L2 to L9 runs at most ∣U∖I∣+1|U \setminus I| + 1 times, and the whole procedure ends.

Proof. Every pass of the loop that does not stop sets added, so it adds at least one new link (line L8 tests p∈Up \in U and that one of its words is unaligned, so p∉Ap \notin A: if pp were in AA, both of its words would be aligned). By Lemma 1, AA can grow at most ∣U∖I∣|U \setminus I| times. The final pass adds nothing and stops. Lines L10 to L12 are two finite loops. □\square

If A1A_1 and A2A_2 come from two one-directional alignments (each source word has at most one link in A1A_1, and each target word at most one in A2A_2), then ∣U∣≤m+l|U| \le m + l, so there are at most m+l+1m + l + 1 passes.

Lemma 3 (the grown set is closed). When the loop of lines L2 to L9 stops, there is no link (j,i)∈A(j, i) \in A and neighbour offset (Δi,Δj)(\Delta i, \Delta j) in the list of line L6 such that p=(j+Δj,i+Δi)∈Up = (j + \Delta j, i + \Delta i) \in U and pp has an unaligned word in AA.

Proof. The last pass adds nothing, so AA does not change during it. That pass visits every cell (j,i)(j, i) at lines L4 and L5, and for each (j,i)∈A(j, i) \in A it tests every neighbour at line L8. If some neighbour pp were in UU with an unaligned word, line L8 would add it, a contradiction. □\square

Lemma 4 (coverage). After line L12 has run for B=A1B = A_1, every word that has a link in A1A_1 is aligned in AA. After it has run for B=A2B = A_2 too, every word that has a link in UU is aligned in AA.

Proof. Let (j,i)∈A1(j, i) \in A_1. When lines L11 and L12 reach (j,i)(j, i) in the pass for A1A_1, either jj or ii is unaligned, and line L12 adds (j,i)(j, i), so both are aligned; or both are aligned already. In both cases jj and ii are aligned after that step, and they stay aligned because links are never removed. The same holds for A2A_2 in the second pass, and the words aligned after the first pass stay aligned. □\square

Theorem. GROW-DIAG-FINAL ends and returns AA with I⊆A⊆UI \subseteq A \subseteq U, such that the set after line L9 is closed in the sense of Lemma 3, and every word with a link in A1∪A2A_1 \cup A_2 is aligned in AA.

Proof. Lemmas 1 to 4. □\square

Remarks.

  1. The result depends on the order. Lemma 3 says the grown set is closed, but there can be several closed sets between II and UU, and the order in which lines L4 to L8 visit cells and neighbours picks one of them. For m=4m = 4, l=3l = 3, A1A_1 from a=(3,2,1,1)a = (3, 2, 1, 1) and A2A_2 from b=(4,4,1)b = (4, 4, 1), the target-outer order of line L4 adds (4,2)(4, 2), and the source-outer order does not. So the procedure is a function of the stated order, not of the two sets alone; this page follows the Moses pseudocode. The same holds for the final step: lines L10 to L12 use A1A_1 before A2A_2.
  2. The variant with "and". If line L12 asks for both words to be unaligned (grow-diag-final-and), Lemma 1 still holds but Lemma 4 does not: a link whose source word is aligned and whose target word is not is never added in the final step, so its target word can stay unaligned. The result is also not always a subset of the grow-diag-final result, because a link added by the final step of grow-diag-final can block another one.
  3. No objective. None of these statements says that the result is a good alignment. The procedure is a heuristic, and its value is measured.
  4. Cost. Each pass of the loop costs O(8ml)O(8 m l) with the alignment status of each word kept in arrays, and the final step costs O(ml)O(m l). With Lemma 2, the total time is O(ml(∣U∖I∣+1))O(m l (|U \setminus I| + 1)), which is O(ml(m+l))O(m l (m + l)) for one-directional inputs.

Complexity

Count in the word RAM model, with the link sets as hash sets or as m×lm \times l bit tables, and with a count of links per word so that "aligned" is an O(1)O(1) test. One pass of lines L4 to L8 costs O(ml)O(m l): mlm l cells and at most 8 neighbours each. The final step costs O(ml)O(m l). By the termination bound there are at most ∣U∣−∣I∣+1|U| - |I| + 1 passes. For two one-directional alignments, ∣U∣≤m+l|U| \le m + l, so the time is O(ml(m+l))O(m l (m + l)) in the worst case. In practice two or three passes are enough, so the cost is close to O(ml)O(m l). The space is O(ml)O(m l) for the tables, or O(m+l)O(m + l) for the counts plus the size of the sets.

Properties

  • Between intersection and union. A1∩A2⊆A⊆A1∪A2A_1 \cap A_2 \subseteq A \subseteq A_1 \cup A_2.
  • Covers what the union covers. Every word linked by either direction is linked in the result, so no word that a model aligned is left out.
  • Many to many. The result can link one word to several words on both sides, which neither direction can do alone.
  • Order dependent. The loops of line L4 and the neighbour order of line L6 decide which link wins when two compete for the same unaligned word. For a=(3,2,1,1)a = (3, 2, 1, 1) and b=(4,4,1)b = (4, 4, 1) with m=4m = 4 and l=3l = 3, the target-outer order of line L4 adds (4, 2), and a source-outer order does not.
  • No objective. It maximizes nothing, so there is no guarantee on the alignment error rate.

Variants and improvements

  • Intersection and union. The two extremes. Och and Ney (2003) measured higher precision for the intersection and higher recall for the union.
  • Grow, grow-diag. Without the diagonal neighbours, or without the final step.
  • Grow-diag-final-and. The final step needs both words unaligned, so it adds fewer isolated links. Its result is not always a subset of the grow-diag-final result: on a=(4,1,3,2)a = (4, 1, 3, 2), b=(2,1,4,4)b = (2, 1, 4, 4) it adds (4, 4), which grow-diag-final does not.
  • The refined method of Och and Ney. It adds a link of UU if neither word is aligned, or if it has a horizontal or vertical neighbour in AA and the new set has no link with both a horizontal and a vertical neighbour. Grow-diag-final relaxes these tests.
  • Joint training. Agreement-based training of the two directions and supervised or discriminative alignment models replace the heuristic by an objective.

When to use it

Use grow-diag-final, or its "and" variant, to turn two directional alignments from IBM models, the HMM model or fast align into the input of phrase pair extraction for a phrase-based model. Phrase extraction needs many to many links with good recall, and the intersection alone gives too few. Use the intersection when precision matters most, for example to build a bilingual dictionary. Use the union when recall matters most. The choice is a measurement on the final task: Koehn, Och and Marcu (2003) compared heuristics of this kind by the BLEU of the phrase-based system.

Pitfalls

  • Another loop order. If line L4 puts the source positions in the outer loop, or line L6 uses another neighbour order, the result can change, and it no longer matches Moses. Keep the stated order, or say which one you use.
  • Snapshot passes. If a pass reads a copy of AA made at its start, links added at line L8 are not visible until the next pass, and the result can differ. In the Moses pseudocode they are visible at once.
  • The final step with "and". If line L12 tests "j and i unaligned" but you expect every word of the union to be covered, the coverage property fails. Pick the variant knowingly.
  • Null links. Links to the null word (aj=0a_j = 0) are not links. Drop them before line L1; otherwise a word linked to null in both directions counts as aligned.
  • Mixed up directions. A1A_1 and A2A_2 must use the same coordinates (j,i)(j, i). The output of a model of p(e∣f)p(e \mid f) is a list indexed by ii, and it must be turned into pairs (bi,i)(b_i, i).

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.

grow_diag_final_symmetrization.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/grow-diag-final-symmetrization/. The authors are listed in prov/00FY52.jsonl.

"""Grow-diag-final symmetrization of two word alignments, as in the Moses documentation.

A link is a pair (j, i): source position j in 1 .. m and target position i in
1 .. l (1-based, null links are not links). a1 and a2 are the link sets of the
two directions. The procedure follows the GROW-DIAG-FINAL pseudocode of the
Moses training documentation: the outer loop runs over the target (English)
positions i, the inner loop over the source (foreign) positions j, a new link
is visible at once, the neighbours are tried in the listed order, and FINAL is
applied to a1 and then to a2 (Moses: FINAL(e2f), then FINAL(f2e)). The order
matters: another loop order can give another result.

Options: diag=False uses only the four direct neighbours (grow-final);
final=False stops after the growing step (grow-diag); final_and=True adds a
link in the final step only if both of its words are unaligned
(grow-diag-final-and).
"""

from typing import FrozenSet, Iterable, Set, Tuple

Link = Tuple[int, int]  # (j, i)

# (delta i, delta j), the order of the Moses pseudocode, which lists (e, f) offsets.
NEIGHBOURS_DIAG = ((-1, 0), (0, -1), (1, 0), (0, 1), (-1, -1), (-1, 1), (1, -1), (1, 1))
NEIGHBOURS_GROW = NEIGHBOURS_DIAG[:4]


class _State:
    """The current link set with the alignment status of each word, O(1) per query."""

    def __init__(self, links: Iterable[Link], m: int, l: int) -> None:
        self.links: Set[Link] = set()
        self.src = [0] * (m + 2)
        self.tgt = [0] * (l + 2)
        for p in links:
            self.add(p)

    def add(self, p: Link) -> None:
        if p not in self.links:
            self.links.add(p)
            self.src[p[0]] += 1
            self.tgt[p[1]] += 1

    def either_unaligned(self, p: Link) -> bool:
        return self.src[p[0]] == 0 or self.tgt[p[1]] == 0

    def both_unaligned(self, p: Link) -> bool:
        return self.src[p[0]] == 0 and self.tgt[p[1]] == 0


def _check(links: Iterable[Link], m: int, l: int) -> FrozenSet[Link]:
    s = frozenset(links)
    for j, i in s:
        if not (1 <= j <= m and 1 <= i <= l):
            raise ValueError(f"link {(j, i)} is outside 1..{m} x 1..{l}")
    return s


def grow_diag_final(a1: Iterable[Link], a2: Iterable[Link], m: int, l: int,
                    diag: bool = True, final: bool = True, final_and: bool = False) -> Set[Link]:
    """Return the symmetrized link set. Cost O((m l)^2) in the worst case, see the page."""
    a1, a2 = _check(a1, m, l), _check(a2, m, l)
    union = a1 | a2
    state = _State(a1 & a2, m, l)  # @line L1
    neighbours = NEIGHBOURS_DIAG if diag else NEIGHBOURS_GROW
    while True:  # @line L2
        added = False  # @line L3
        for i in range(1, l + 1):  # @line L4
            for j in range(1, m + 1):
                if (j, i) in state.links:  # @line L5
                    for di, dj in neighbours:  # @line L6
                        p = (j + dj, i + di)  # @line L7
                        if p in union and state.either_unaligned(p):  # @line L8
                            state.add(p)
                            added = True
        if not added:  # @line L9
            break
    if final:
        for b in (a1, a2):  # @line L10
            for i in range(1, l + 1):  # @line L11
                for j in range(1, m + 1):
                    p = (j, i)
                    ok = state.both_unaligned(p) if final_and else state.either_unaligned(p)
                    if p in b and ok:  # @line L12
                        state.add(p)
    return set(state.links)  # @line L13


def grow_diag_final_and(a1: Iterable[Link], a2: Iterable[Link], m: int, l: int) -> Set[Link]:
    """The variant whose final step needs both words unaligned."""
    return grow_diag_final(a1, a2, m, l, final_and=True)


def links_from_alignment(a: Iterable[int]) -> Set[Link]:
    """Links of a one-directional alignment a_1 .. a_m of p(f | e); a_j = 0 is the null word."""
    return {(j, i) for j, i in enumerate(a, start=1) if i > 0}


def links_from_reverse(b: Iterable[int]) -> Set[Link]:
    """Links of an alignment b_1 .. b_l of the other direction p(e | f), turned into (j, i) pairs."""
    return {(j, i) for i, j in enumerate(b, start=1) if j > 0}
test_grow_diag_final_symmetrization.py 149 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/grow-diag-final-symmetrization/. The authors are listed in prov/00FY52.jsonl.

import random

import pytest

from grow_diag_final_symmetrization import (
    NEIGHBOURS_DIAG,
    grow_diag_final,
    grow_diag_final_and,
    links_from_alignment,
    links_from_reverse,
)


def reference(a1, a2, m, l, diag=True, final=True, final_and=False, outer_j=False):
    """A second, plain version of the Moses pseudocode: sets only, and the
    alignment status of a word is found by a scan of the current set."""
    union = a1 | a2
    A = set(a1 & a2)

    def src_free(j):
        return all(p[0] != j for p in A)

    def tgt_free(i):
        return all(p[1] != i for p in A)

    def cells():
        if outer_j:
            return [(j, i) for j in range(1, m + 1) for i in range(1, l + 1)]
        return [(j, i) for i in range(1, l + 1) for j in range(1, m + 1)]

    nb = NEIGHBOURS_DIAG if diag else NEIGHBOURS_DIAG[:4]
    changed = True
    while changed:
        changed = False
        for j, i in cells():
            if (j, i) in A:
                for di, dj in nb:
                    p = (j + dj, i + di)
                    if p in union and (src_free(p[0]) or tgt_free(p[1])):
                        A.add(p)
                        changed = True
    if final:
        for b in (a1, a2):
            for j, i in cells():
                if (j, i) in b:
                    if final_and:
                        ok = src_free(j) and tgt_free(i)
                    else:
                        ok = src_free(j) or tgt_free(i)
                    if ok:
                        A.add((j, i))
    return A


def random_pair(rng, m, l, null=0.2):
    a = [0 if rng.random() < null else rng.randint(1, l) for _ in range(m)]
    b = [0 if rng.random() < null else rng.randint(1, m) for _ in range(l)]
    return links_from_alignment(a), links_from_reverse(b)


def test_worked_example() -> None:
    # f = ich gehe nicht nach hause, e = i do not go home
    a1 = links_from_alignment([1, 4, 3, 5, 5])
    a2 = links_from_reverse([1, 2, 3, 2, 5])
    assert a1 & a2 == {(1, 1), (2, 4), (3, 3), (5, 5)}
    assert grow_diag_final(a1, a2, 5, 5, diag=False, final=False) == a1 & a2 | {(4, 5)}
    assert grow_diag_final(a1, a2, 5, 5, final=False) == a1 & a2 | {(2, 2), (4, 5)}
    assert grow_diag_final(a1, a2, 5, 5) == a1 | a2


def test_variants_differ() -> None:
    a1 = links_from_alignment([2, 4, 3, 1, 4])
    a2 = links_from_reverse([5, 1, 1, 2, 1])
    inter = {(1, 2), (2, 4)}
    assert a1 & a2 == inter
    assert grow_diag_final(a1, a2, 5, 5, diag=False, final=False) == inter | {(1, 3)}
    gd = grow_diag_final(a1, a2, 5, 5, final=False)
    assert gd == inter | {(1, 3), (1, 5), (3, 3)}
    assert grow_diag_final_and(a1, a2, 5, 5) == gd | {(4, 1)}
    assert grow_diag_final(a1, a2, 5, 5) == gd | {(4, 1), (5, 4)}
    assert (a1 | a2) - grow_diag_final(a1, a2, 5, 5) == {(5, 1)}


def test_loop_order_matters() -> None:
    a1 = links_from_alignment([3, 2, 1, 1])
    a2 = links_from_reverse([4, 4, 1])
    out = grow_diag_final(a1, a2, 4, 3, final=False)
    assert out == {(1, 3), (2, 2), (3, 1), (4, 1), (4, 2)}
    assert out == reference(a1, a2, 4, 3, final=False)
    # with the source positions in the outer loop, (4, 2) is not added
    assert reference(a1, a2, 4, 3, final=False, outer_j=True) == out - {(4, 2)}


def test_against_reference() -> None:
    rng = random.Random(17)
    for _ in range(400):
        m, l = rng.randint(1, 7), rng.randint(1, 7)
        a1, a2 = random_pair(rng, m, l)
        for kw in ({}, {"diag": False}, {"final": False}, {"final_and": True}):
            assert grow_diag_final(a1, a2, m, l, **kw) == reference(a1, a2, m, l, **kw)


def test_bounds_and_coverage() -> None:
    rng = random.Random(23)
    for _ in range(400):
        m, l = rng.randint(1, 8), rng.randint(1, 8)
        a1, a2 = random_pair(rng, m, l)
        union = a1 | a2
        out = grow_diag_final(a1, a2, m, l)
        assert a1 & a2 <= out <= union
        # every word with a link in either direction is aligned at the end
        assert {j for j, _ in union} == {j for j, _ in out}
        assert {i for _, i in union} == {i for _, i in out}
        # grow-diag-final-and starts from the same grown set; it is not always a subset of
        # grow-diag-final, because a link that one final step adds can block another
        gd = grow_diag_final(a1, a2, m, l, final=False)
        gdfa = grow_diag_final_and(a1, a2, m, l)
        assert gd <= gdfa <= union
        assert gd <= out


def test_fixed_point_of_growing() -> None:
    rng = random.Random(29)
    for _ in range(300):
        m, l = rng.randint(1, 8), rng.randint(1, 8)
        a1, a2 = random_pair(rng, m, l)
        out = grow_diag_final(a1, a2, m, l, final=False)
        src = {j for j, _ in out}
        tgt = {i for _, i in out}
        for j, i in out:
            for di, dj in NEIGHBOURS_DIAG:
                p = (j + dj, i + di)
                if p in a1 | a2:
                    assert p[0] in src and p[1] in tgt


def test_edges() -> None:
    assert grow_diag_final(set(), set(), 3, 3) == set()
    a = {(1, 1), (2, 2)}
    assert grow_diag_final(a, a, 2, 2) == a
    # one direction only: the final step adds all of it here
    assert grow_diag_final({(1, 2), (2, 1)}, set(), 2, 2) == {(1, 2), (2, 1)}
    with pytest.raises(ValueError):
        grow_diag_final({(0, 1)}, set(), 2, 2)
    assert links_from_alignment([0, 2, 1]) == {(2, 2), (3, 1)}
    assert links_from_reverse([3, 0]) == {(3, 1)}

History

Och and Ney (2003) noted that a one-directional model cannot link one word to several words and proposed to combine the two directions: by intersection, by union, or by a refined method that grows the intersection with links of the union. Koehn, Och and Marcu (2003) used such heuristics to build the alignments for phrase-based translation and compared them by translation quality. The Moses toolkit, released in 2007, wrote the grow-diag-final heuristic in the pseudocode that most later work follows and made it the default of its training pipeline.

References

  1. Och and Ney 2003, Section 4 (symmetrization: intersection, union and the refined method)
  2. Koehn, Och and Marcu 2003, the comparison of alignment heuristics for phrase extraction
  3. Moses documentation, the GROW-DIAG-FINAL pseudocode and the list of the other heuristics
  4. Philipp Koehn, Statistical Machine Translation, Cambridge University Press, 2010, Section 4.5 (word alignment)

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