Algorithmcore
Phrase pair extraction
Also called consistent phrase extraction.
Extract every pair of source and target spans consistent with a word alignment, that is with no link leaving the pair.
- Solves
- Machine translation
- Time
- O(m p (a + l^2)) worst
- Space
- O(a + l) extra
- Where
- a = the number of links; l = the target sentence length; m = the source sentence length; p = the maximum phrase length
- Model
- Word RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Franz Josef Och, Christoph Tillmann, Hermann Ney, Philipp Koehn, Daniel Marcu, 1999
Phrase pair extraction is the step of statistical machine translation that reads a word-aligned sentence pair and lists every pair of a source phrase and a target phrase that the word alignment allows. A pair is allowed, or consistent, when it holds at least one link and no link joins a word inside the pair to a word outside it. The pairs of a whole parallel corpus are counted to build the phrase table of a phrase-based translation model. The rule is exact with respect to its definition, but the definition itself is a heuristic: it trusts the alignment, and an alignment error removes or adds many pairs.
In plain words
Take a sentence and its translation, with lines drawn between words that mean the same thing. Now cut out a piece of the sentence and a piece of the translation. The two pieces form a good pair if no line leaves the box that they make together: every word in one piece is joined only to words in the other piece, and at least one line is inside. Short pieces give word translations, longer pieces give whole expressions with their word order.
A word with no line at all does not break any box, so it can be added at the edge of a piece. This gives several pairs that differ only by such loose words. The method tries every source piece up to a length limit, finds the smallest target piece that it needs, and then grows that piece over loose words on both sides.
The problem
The input is a source sentence , a target sentence , a set of links between source position and target position , and a length limit . Spans are fencepost: the span covers the words , so it has words. A phrase pair is , a source span and a target span. It is consistent with if
- some link has and , and
- no link has exactly one of and .
The output is the set of all consistent pairs with and . Moses uses . The direction of translation does not matter here, because the definition is symmetric in the two sides.
The algorithm
For a source span, the target words it is linked to fix the smallest target span it can pair with. If some link reaches into that target span from outside the source span, no pair with this source span is consistent. Otherwise every pair is the smallest target span grown by any number of unaligned target words on the left and on the right.
EXTRACT(m, l, A, p) ▷ spans are fencepost: (s, t) covers s+1 .. t- 1
P ← ∅ - 2
for s ← 0 to m − 1 do - 3
for t ← s + 1 to min(m, s + p) do - 4
T ← { i : (j, i) ∈ A and s < j ≤ t } - 5
if T = ∅ then continue - 6
u ← min T − 1; v ← max T - 7
if some (j, i) ∈ A has u < i ≤ v and not s < j ≤ t then continue - 8
u2 ← u - 9
repeat - 10
v2 ← v - 11
repeat - 12
if v2 − u2 ≤ p then P ← P ∪ {((s, t), (u2, v2))} - 13
v2 ← v2 + 1 - 14
until v2 > l or e_{v2} is aligned - 15
u2 ← u2 − 1 - 16
until u2 < 0 or e_{u2+1} is aligned - 17
return P
Lines L4 to L6 find the smallest target span. Line L7 tests the second condition from the target side. Lines L8 to L16 grow the target span: the outer loop moves the left end over unaligned words, the inner loop moves the right end. Each new word is checked when it enters the span, at line L14 or line L16.
Example
Take the German sentence = er geht ja nicht nach hause and the English = he does not go home, with , and the links
:
er to he, geht to go, nicht to both does and not, and nach and hause both to home. The word ja is not aligned. With the algorithm finds 10 pairs.
| source phrase | target phrase |
|---|---|
| er | he |
| er geht ja nicht | he does not go |
| er geht ja nicht nach hause | he does not go home |
| geht | go |
| geht ja | go |
| geht ja nicht | does not go |
| geht ja nicht nach hause | does not go home |
| ja nicht | does not |
| nicht | does not |
| nach hause | home |
Some spans give nothing. The source span "ja" has no links (line L5). The span "er geht" has targets , so , and the links of nicht reach into it from outside (line L7). The span "nach" alone has the target home, which is also linked to hause, so line L7 rejects it. Here no target word is unaligned, so lines L8 to L16 add exactly one pair for each source span that passes.
Unaligned target words give more pairs. For = das haus ist klein and = the house is very small, with , the target word very is not aligned. The source span "klein" gives both "small" and "very small", and "ist" gives "is" and "is very". In total there are 14 pairs.
Correctness
The proofs file shows that the set returned is exactly the set of consistent pairs within the length limit. The key fact is that a pair is consistent if and only if its target span contains the smallest span of line L6, no link reaches into that smallest span from outside the source span, and every target word between the smallest span and the ends of the pair is unaligned. Line L7 tests the middle condition, and the two loops enumerate the rest. The test file compares the result with a brute force search over all pairs of spans on 400 random alignments.
Proof: Phrase pair extraction returns exactly the consistent phrase pairs up to the length limitfull
Let be the links , with a source position and a target position. Spans are fencepost: the span covers the positions . A phrase pair is consistent if (a) some link has and , and (b) no link has exactly one of and . Let be the length limit. Let be the set of consistent pairs with and , and let be the set that EXTRACT returns. A target position is aligned if some link has target .
For a source span let , the set that line L4 collects. When it is not empty, let and , the values of line L6.
Lemma 1 (the tight target span). A pair is consistent if and only if , , , every link with has , and every target position in and in is unaligned.
Proof. Suppose the pair is consistent. By (a), some link starts inside , so . Every comes from a link with its source inside, so by (b) its target is inside: . So , that is , and . A link with has its target inside , so by (b) its source is inside . A target position in is inside but not in . If it had a link , then by (b) , so , a contradiction. The same holds for .
Conversely, suppose the conditions hold. A link with source in has its target in , and there is at least one such link, so (a) holds. A link with target in has its target in , because the positions outside it are unaligned, so its source is in . So no link has exactly one end inside, and (b) holds.
Lemma 2 (lines L8 to L16). Let pass the tests of lines L5 and L7. Then the loops of lines L8 to L16 visit exactly the pairs with , , , , and all target positions in and in unaligned. Line L12 adds those of them with .
Proof. The outer loop starts at and, at line L15, lowers by one. Line L16 stops it when or when the newly added position is aligned. So the outer loop runs for down to the last value such that and all positions are unaligned. These are exactly the allowed values of , because the condition "all of unaligned" stays false once it fails. The inner loop does the same for from upward with lines L13 and L14, and it does not depend on . Line L12 tests the length.
Theorem. .
Proof. Line L2 and L3 go over every source span with . Take one. If , no pair with this source span is consistent by (a), and line L5 skips it. Otherwise the test of line L7 is the third condition of Lemma 1 for this source span, which does not depend on or . If it fails, no pair with this source span is consistent, and the span is skipped. If it holds, Lemma 2 says that line L12 adds exactly the target spans that meet the other conditions of Lemma 1 and have . By Lemma 1 these are exactly the consistent pairs with this source span and both sides at most words. Each pair is added to a set, so none is counted twice.
Termination and cost. There are at most source spans. For each, lines L4 and L7 read the links once, and the loops of lines L8 to L16 run at most times but add only pairs with . With the length of the longest run of unaligned target words, the inner work is for each source span, and the total time is .
Complexity
Count in the word RAM model. There are at most source spans. For each, lines L4 and L7 read the links once, in time. The loops of lines L8 to L16 run once for each pair of a left end and a right end inside the runs of unaligned words around the smallest span, so at most times, and in practice a few times. The total time is . Faster versions keep the minimum and the maximum of the targets as grows, so that line L4 costs amortized for each span. The extra space is , not counting the output.
The output itself can be large. A sentence pair with a diagonal alignment of words has pairs without a length limit; for that is 10.
Properties
- Exact for its definition. It returns every consistent pair and nothing else (a theorem, proved in the proofs file).
- Symmetric. Swapping the roles of and gives the same pairs with the sides swapped.
- Needs at least one link. A pair of two unaligned words is not extracted, by condition 1. An empty alignment gives no pairs.
- Many pairs for one span. Unaligned words at the edges multiply the pairs: a source span with unaligned target words to its left and to its right can give up to pairs.
- Not a model. The pairs have no probabilities. The phrase-based model counts them over the corpus to estimate the phrase translation probabilities.
Variants and improvements
- Length limit. Moses uses at most 7 words on each side. Longer limits give more pairs that are seldom used again.
- Orientation counts. The lexicalized reordering model records, for each extracted pair, whether the previous and the next pair are monotone, swapped or discontinuous. The extraction is the same; only extra counts are kept.
- Hierarchical rules. Hierarchical phrase-based translation starts from these pairs (with a limit of 10 words) and cuts smaller consistent pairs out of them to make rules with gaps.
- Syntax-based rules. GHKM rule extraction uses the same idea of consistency, but only at nodes of a target parse tree, and it needs the closure of the span to be free of outside links.
- Weighted pairs. Instead of trusting one alignment, some systems count pairs from several alignments or weight them by alignment posteriors.
When to use it
Use it to build the phrase table of a phrase-based system from a symmetrized word alignment. The heuristic works best with alignments that have high recall, such as grow-diag-final, because a missing link can make a pair consistent that should not be, while an extra wrong link removes many good pairs. Koehn, Och and Marcu (2003) found in their measurements that this simple method was better than phrase pairs from syntactic constituents only, and that phrases longer than three words gave little extra gain.
Pitfalls
- Off-by-one spans. Use fencepost spans throughout. Mixing "covers to " with "covers to " moves every pair by one word.
- Testing condition 2 on one side only. It is not enough that the source words link only into the target span. Line L7 must also check that no target word inside the span links to a source word outside. "Er geht" fails only that test.
- Growing over aligned words. The loops must stop at the first aligned word on each side. Growing over it breaks condition 2.
- Forgetting the empty test. Without line L5, unaligned source words would pair with every unaligned target word.
- Memory. On a large corpus, write the pairs to disk and count them there. A table in memory of all pairs of a corpus is usually too big.
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/phrase-pair-extraction/. The authors are listed in prov/ZVR7MS.jsonl.
"""Phrase pair extraction from a word-aligned sentence pair (Koehn, Och and Marcu 2003).
The source sentence f has m words and the target sentence e has l words. A link
is a pair (j, i) with source position j in 1 .. m and target position i in
1 .. l. A span (s, t) is fencepost: it covers the words s + 1 .. t. A phrase
pair is ((s, t), (u, v)), a source span and a target span.
A pair is consistent with the alignment A when it holds at least one link and
no link joins a word inside the pair to a word outside it. extract_phrase_pairs
returns every consistent pair with both sides of at most max_len words (7 is
the Moses default).
"""
from typing import Iterable
Link = tuple[int, int]
Span = tuple[int, int]
Pair = tuple[Span, Span]
def extract_phrase_pairs(m: int, l: int, links: Iterable[Link], max_len: int = 7) -> set[Pair]:
"""All phrase pairs consistent with the links, each side at most max_len words."""
a = sorted(set(links))
for j, i in a:
if not (1 <= j <= m and 1 <= i <= l):
raise ValueError(f"link {(j, i)} is outside the sentences")
tgt_aligned = [False] * (l + 2)
for _, i in a:
tgt_aligned[i] = True
pairs: set[Pair] = set() # @line L1
for s in range(m): # @line L2
for t in range(s + 1, min(m, s + max_len) + 1): # @line L3
targets = [i for j, i in a if s < j <= t] # @line L4
if not targets: # @line L5
continue
u, v = min(targets) - 1, max(targets) # @line L6
if any(u < i <= v and not (s < j <= t) for j, i in a): # @line L7
continue
u2 = u # @line L8
while True: # @line L9
v2 = v # @line L10
while True: # @line L11
if v2 - u2 <= max_len: # @line L12
pairs.add(((s, t), (u2, v2)))
v2 += 1 # @line L13
if v2 > l or tgt_aligned[v2]: # @line L14
break
u2 -= 1 # @line L15
if u2 < 0 or tgt_aligned[u2 + 1]: # @line L16
break
return pairs # @line L17
def is_consistent(pair: Pair, links: Iterable[Link]) -> bool:
"""The definition: at least one link inside, and no link that leaves the pair."""
(s, t), (u, v) = pair
inside = False
for j, i in links:
js, it = s < j <= t, u < i <= v
if js and it:
inside = True
elif js or it:
return False
return inside
def brute_force_pairs(m: int, l: int, links: Iterable[Link], max_len: int = 7) -> set[Pair]:
"""Test every pair of a source span and a target span against the definition."""
a = list(links)
out = set()
for s in range(m):
for t in range(s + 1, min(m, s + max_len) + 1):
for u in range(l):
for v in range(u + 1, min(l, u + max_len) + 1):
if is_consistent(((s, t), (u, v)), a):
out.add(((s, t), (u, v)))
return out
def phrase_strings(f: list[str], e: list[str], pairs: Iterable[Pair]) -> list[tuple[str, str]]:
"""The pairs as strings, sorted by source span and then by target span."""
return [(" ".join(f[s:t]), " ".join(e[u:v])) for (s, t), (u, v) in sorted(pairs)]
test_phrase_pair_extraction.py 86 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/phrase-pair-extraction/. The authors are listed in prov/ZVR7MS.jsonl.
import random
import pytest
from phrase_pair_extraction import (
brute_force_pairs,
extract_phrase_pairs,
is_consistent,
phrase_strings,
)
def test_example_unaligned_source_word() -> None:
f = "er geht ja nicht nach hause".split()
e = "he does not go home".split()
a = {(1, 1), (2, 4), (4, 2), (4, 3), (5, 5), (6, 5)}
pairs = extract_phrase_pairs(len(f), len(e), a)
assert len(pairs) == 10
got = phrase_strings(f, e, pairs)
assert ("geht ja", "go") in got
assert ("ja nicht", "does not") in got
assert ("nach hause", "home") in got
assert ("nach", "home") not in got
assert ("er geht ja nicht nach hause", "he does not go home") in got
def test_example_unaligned_target_word() -> None:
f = "das haus ist klein".split()
e = "the house is very small".split()
a = {(1, 1), (2, 2), (3, 3), (4, 5)}
pairs = extract_phrase_pairs(len(f), len(e), a)
assert len(pairs) == 14
got = phrase_strings(f, e, pairs)
assert ("klein", "small") in got and ("klein", "very small") in got
assert ("ist", "is very") in got
def test_max_len() -> None:
f = "das haus ist klein".split()
e = "the house is very small".split()
a = {(1, 1), (2, 2), (3, 3), (4, 5)}
for k in range(1, 6):
pairs = extract_phrase_pairs(4, 5, a, max_len=k)
assert pairs == brute_force_pairs(4, 5, a, max_len=k)
assert all(t - s <= k and v - u <= k for (s, t), (u, v) in pairs)
assert len(extract_phrase_pairs(4, 5, a, max_len=1)) == 4
def test_edge_cases() -> None:
assert extract_phrase_pairs(3, 3, set()) == set()
full = {(j, i) for j in range(1, 4) for i in range(1, 3)}
assert extract_phrase_pairs(3, 2, full) == {((0, 3), (0, 2))}
diag = {(j, j) for j in range(1, 5)}
# a monotone one-to-one alignment gives one pair per pair of equal spans
assert len(extract_phrase_pairs(4, 4, diag)) == 10
with pytest.raises(ValueError):
extract_phrase_pairs(2, 2, {(3, 1)})
def test_inverted_alignment() -> None:
# a b c -> c' b' a': every span of the source pairs with the mirrored span
a = {(1, 3), (2, 2), (3, 1)}
pairs = extract_phrase_pairs(3, 3, a)
assert pairs == {((s, t), (3 - t, 3 - s)) for s in range(3) for t in range(s + 1, 4)}
def test_every_pair_is_consistent() -> None:
rng = random.Random(7)
for _ in range(200):
m, l = rng.randint(1, 7), rng.randint(1, 7)
a = {(j, i) for j in range(1, m + 1) for i in range(1, l + 1) if rng.random() < 0.25}
for p in extract_phrase_pairs(m, l, a):
assert is_consistent(p, a)
def test_random_against_brute_force() -> None:
rng = random.Random(2003)
for _ in range(400):
m, l = rng.randint(1, 9), rng.randint(1, 9)
dens = rng.choice([0.1, 0.2, 0.35, 0.6])
a = {(j, i) for j in range(1, m + 1) for i in range(1, l + 1) if rng.random() < dens}
k = rng.randint(1, 8)
assert extract_phrase_pairs(m, l, a, max_len=k) == brute_force_pairs(m, l, a, max_len=k)
History
Och, Tillmann and Ney (1999) introduced the alignment template approach, which took phrase pairs from symmetrized word alignments. Koehn, Och and Marcu (2003) wrote down the consistency rule in the form used since, and compared it with phrases from syntactic constituents and from a joint phrase model. The Pharaoh decoder and then the Moses toolkit made extraction from a grow-diag-final alignment, with up to 7 words on each side, the standard way to build a phrase table. The same rule is the base of the rule extraction for hierarchical and syntax-based models.
References
- Och, Tillmann and Ney 1999, the alignment template approach, with phrase pairs taken from a symmetrized word alignment
- Koehn, Och and Marcu 2003, the definition of phrase pairs consistent with a word alignment, and the comparison of phrase extraction methods
- Koehn et al. 2005, Section 2.4 (phrase extraction: a phrase pair must contain at least one alignment point and be consistent with the alignment)
- Philipp Koehn, Statistical Machine Translation, Cambridge University Press, 2010, Chapter 5 (phrase-based models: learning a phrase translation table)
Where this leads
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 ZVR7MS Edit this page History Report an error Markdown