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.
- Solves
- Word alignment
- Time
- O(m l (m + l)) worst
- Space
- O(m l) extra
- Where
- l = the target sentence length; m = the source sentence length
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 and the target , and two link sets of pairs . Usually comes from a model of , where each source word has at most one link, and from a model of , where each target word has at most one link. The output is one link set that can be many to many. The intersection has high precision and the union has high recall, in the measurements of Och and Ney (2003). A good 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 of the target and the source position, in the order : first the four direct neighbours, then the four diagonal ones. A word is aligned if it has a link in the current set .
GROW-DIAG-FINAL(A_1, A_2, m, l) ▷ links (j, i); Moses calls A_1 e2f and A_2 f2e- 1
A ← A_1 ∩ A_2; U ← A_1 ∪ A_2 - 2
repeat - 3
added ← false - 4
for i ← 1 to l do for j ← 1 to m do ▷ target outer, source inner - 5
if (j, i) ∈ A then - 6
for each (Δi, Δj) in the 8 neighbour offsets, in the order above do - 7
p ← (j + Δj, i + Δi) - 8
if p ∈ U and (the source word of p or the target word of p is unaligned) then A ← A ∪ {p}; added ← true - 9
until not added - 10
for each B in (A_1, A_2) do ▷ FINAL(e2f), then FINAL(f2e) - 11
for i ← 1 to l do for j ← 1 to m do - 12
if (j, i) ∈ B and (j or i is unaligned) then A ← A ∪ {(j, i)} - 13
return 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 = ich gehe nicht nach hause and = i do not go home (). The direction gives : ich to i, gehe to go, nicht to not, nach to home and hause to home. The direction gives : i to ich, do to gehe, not to nicht, go to gehe and home to hause. So
, , , and .
In the intersection, the target word do () and the source word nach () are unaligned. The first pass of lines L4 to L8 goes like this.
| visit | neighbour tried | in ? | unaligned word | action |
|---|---|---|---|---|
| (1, 1) ich, i | (1, 2), (2, 1) | no | ||
| (1, 1) | : (2, 2) gehe, do | yes | do | add (2, 2) |
| (2, 2) gehe, do | all 8 | (1, 1), (3, 3) are in | none | |
| (3, 3) nicht, not | (2, 2), (2, 4) | in | none | |
| (2, 4) gehe, go | all 8 | only (3, 3), which is in | none | |
| (5, 5) hause, home | : (4, 5) nach, home | yes | nach | add (4, 5) |
The second pass adds nothing, and the final step finds no link of or with an unaligned word. The result is , 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 and , 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 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 passes, because each pass that goes on adds a new link of . When it ends, no link of next to a kept link has an unaligned word. After the final step, every word that has a link in or in 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 be the two link sets, with links , and let and . Let be the working set of GROW-DIAG-FINAL. A source word is aligned in if some , and a target word likewise. The procedure only adds links; it never removes one.
Lemma 1 (bounds). At every moment, .
Proof. Line L1 sets . Line L8 adds a link only if it is in . Line L12 adds a link only if it is in or in , so in . Nothing is removed, so stays true.
Lemma 2 (termination). The loop of lines L2 to L9 runs at most 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 and that one of its words is unaligned, so : if were in , both of its words would be aligned). By Lemma 1, can grow at most times. The final pass adds nothing and stops. Lines L10 to L12 are two finite loops.
If and come from two one-directional alignments (each source word has at most one link in , and each target word at most one in ), then , so there are at most passes.
Lemma 3 (the grown set is closed). When the loop of lines L2 to L9 stops, there is no link and neighbour offset in the list of line L6 such that and has an unaligned word in .
Proof. The last pass adds nothing, so does not change during it. That pass visits every cell at lines L4 and L5, and for each it tests every neighbour at line L8. If some neighbour were in with an unaligned word, line L8 would add it, a contradiction.
Lemma 4 (coverage). After line L12 has run for , every word that has a link in is aligned in . After it has run for too, every word that has a link in is aligned in .
Proof. Let . When lines L11 and L12 reach in the pass for , either or is unaligned, and line L12 adds , so both are aligned; or both are aligned already. In both cases and are aligned after that step, and they stay aligned because links are never removed. The same holds for in the second pass, and the words aligned after the first pass stay aligned.
Theorem. GROW-DIAG-FINAL ends and returns with , such that the set after line L9 is closed in the sense of Lemma 3, and every word with a link in is aligned in .
Proof. Lemmas 1 to 4.
Remarks.
- The result depends on the order. Lemma 3 says the grown set is closed, but there can be several closed sets between and , and the order in which lines L4 to L8 visit cells and neighbours picks one of them. For , , from and from , the target-outer order of line L4 adds , 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 before .
- 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.
- No objective. None of these statements says that the result is a good alignment. The procedure is a heuristic, and its value is measured.
- Cost. Each pass of the loop costs with the alignment status of each word kept in arrays, and the final step costs . With Lemma 2, the total time is , which is for one-directional inputs.
Complexity
Count in the word RAM model, with the link sets as hash sets or as bit tables, and with a count of links per word so that "aligned" is an test. One pass of lines L4 to L8 costs : cells and at most 8 neighbours each. The final step costs . By the termination bound there are at most passes. For two one-directional alignments, , so the time is in the worst case. In practice two or three passes are enough, so the cost is close to . The space is for the tables, or for the counts plus the size of the sets.
Properties
- Between intersection and union. .
- 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 and with and , 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 , it adds (4, 4), which grow-diag-final does not.
- The refined method of Och and Ney. It adds a link of if neither word is aligned, or if it has a horizontal or vertical neighbour in 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 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 () are not links. Drop them before line L1; otherwise a word linked to null in both directions counts as aligned.
- Mixed up directions. and must use the same coordinates . The output of a model of is a list indexed by , and it must be turned into pairs .
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/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
- Och and Ney 2003, Section 4 (symmetrization: intersection, union and the refined method)
- Koehn, Och and Marcu 2003, the comparison of alignment heuristics for phrase extraction
- Moses documentation, the GROW-DIAG-FINAL pseudocode and the list of the other heuristics
- 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.
| 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 00FY52 Edit this page History Report an error Markdown