Algorithm Search⌘K

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.

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
Properties
deterministicexactofflineiterative
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 f=f1…fmf = f_1 \ldots f_m, a target sentence e=e1…ele = e_1 \ldots e_l, a set AA of links (j,i)(j, i) between source position jj and target position ii, and a length limit pp. Spans are fencepost: the span (s,t)(s, t) covers the words s+1,…,ts + 1, \ldots, t, so it has t−st - s words. A phrase pair is ((s,t),(u,v))((s, t), (u, v)), a source span and a target span. It is consistent with AA if

  1. some link (j,i)∈A(j, i) \in A has s<j≤ts < j \le t and u<i≤vu < i \le v, and
  2. no link (j,i)∈A(j, i) \in A has exactly one of s<j≤ts < j \le t and u<i≤vu < i \le v.

The output is the set of all consistent pairs with t−s≤pt - s \le p and v−u≤pv - u \le p. Moses uses p=7p = 7. 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.

  1. EXTRACT(m, l, A, p) ▷ spans are fencepost: (s, t) covers s+1 .. t
  2. 1P ← ∅
  3. 2for s ← 0 to m − 1 do
  4. 3for t ← s + 1 to min(m, s + p) do
  5. 4T ← { i : (j, i) ∈ A and s < j ≤ t }
  6. 5if T = ∅ then continue
  7. 6u ← min T − 1; v ← max T
  8. 7if some (j, i) ∈ A has u < i ≤ v and not s < j ≤ t then continue
  9. 8u2 ← u
  10. 9repeat
  11. 10v2 ← v
  12. 11repeat
  13. 12if v2 − u2 ≤ p then P ← P ∪ {((s, t), (u2, v2))}
  14. 13v2 ← v2 + 1
  15. 14until v2 > l or e_{v2} is aligned
  16. 15u2 ← u2 − 1
  17. 16until u2 < 0 or e_{u2+1} is aligned
  18. 17return 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 ff = er geht ja nicht nach hause and the English ee = he does not go home, with m=6m = 6, l=5l = 5 and the links

A={(1,1),(2,4),(4,2),(4,3),(5,5),(6,5)}A = \{(1,1), (2,4), (4,2), (4,3), (5,5), (6,5)\}:

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 p=7p = 7 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 {1,4}\{1, 4\}, so (u,v)=(0,4)(u, v) = (0, 4), 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 ff = das haus ist klein and ee = the house is very small, with A={(1,1),(2,2),(3,3),(4,5)}A = \{(1,1), (2,2), (3,3), (4,5)\}, 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 A⊆{1,…,m}×{1,…,l}A \subseteq \{1, \ldots, m\} \times \{1, \ldots, l\} be the links (j,i)(j, i), with jj a source position and ii a target position. Spans are fencepost: the span (s,t)(s, t) covers the positions s+1,…,ts + 1, \ldots, t. A phrase pair ((s,t),(u,v))((s, t), (u, v)) is consistent if (a) some link (j,i)∈A(j, i) \in A has s<j≤ts < j \le t and u<i≤vu < i \le v, and (b) no link has exactly one of s<j≤ts < j \le t and u<i≤vu < i \le v. Let LL be the length limit. Let P∗P^* be the set of consistent pairs with t−s≤Lt - s \le L and v−u≤Lv - u \le L, and let PP be the set that EXTRACT returns. A target position ii is aligned if some link has target ii.

For a source span (s,t)(s, t) let T(s,t)={i:(j,i)∈A,s<j≤t}T(s, t) = \{i : (j, i) \in A, s < j \le t\}, the set that line L4 collects. When it is not empty, let u0=min⁡T(s,t)−1u_0 = \min T(s, t) - 1 and v0=max⁡T(s,t)v_0 = \max T(s, t), the values of line L6.

Lemma 1 (the tight target span). A pair ((s,t),(u,v))((s, t), (u, v)) is consistent if and only if T(s,t)≠∅T(s, t) \ne \emptyset, u≤u0u \le u_0, v≥v0v \ge v_0, every link (j,i)(j, i) with u0<i≤v0u_0 < i \le v_0 has s<j≤ts < j \le t, and every target position in u+1,…,u0u + 1, \ldots, u_0 and in v0+1,…,vv_0 + 1, \ldots, v is unaligned.

Proof. Suppose the pair is consistent. By (a), some link starts inside (s,t)(s, t), so T(s,t)≠∅T(s, t) \ne \emptyset. Every i∈T(s,t)i \in T(s, t) comes from a link with its source inside, so by (b) its target is inside: u<i≤vu < i \le v. So u<min⁡T=u0+1u < \min T = u_0 + 1, that is u≤u0u \le u_0, and v≥max⁡T=v0v \ge \max T = v_0. A link with u0<i≤v0u_0 < i \le v_0 has its target inside (u,v)(u, v), so by (b) its source is inside (s,t)(s, t). A target position ii in u+1,…,u0u + 1, \ldots, u_0 is inside (u,v)(u, v) but not in T(s,t)T(s, t). If it had a link (j,i)(j, i), then by (b) s<j≤ts < j \le t, so i∈T(s,t)i \in T(s, t), a contradiction. The same holds for v0+1,…,vv_0 + 1, \ldots, v.

Conversely, suppose the conditions hold. A link with source in (s,t)(s, t) has its target in T(s,t)⊆(u0,v0]⊆(u,v]T(s, t) \subseteq (u_0, v_0] \subseteq (u, v], and there is at least one such link, so (a) holds. A link with target in (u,v](u, v] has its target in (u0,v0](u_0, v_0], because the positions outside it are unaligned, so its source is in (s,t)(s, t). So no link has exactly one end inside, and (b) holds. □\square

Lemma 2 (lines L8 to L16). Let (s,t)(s, t) pass the tests of lines L5 and L7. Then the loops of lines L8 to L16 visit exactly the pairs (u2,v2)(u_2, v_2) with u2≤u0u_2 \le u_0, v2≥v0v_2 \ge v_0, u2≥0u_2 \ge 0, v2≤lv_2 \le l, and all target positions in u2+1,…,u0u_2 + 1, \ldots, u_0 and in v0+1,…,v2v_0 + 1, \ldots, v_2 unaligned. Line L12 adds those of them with v2−u2≤Lv_2 - u_2 \le L.

Proof. The outer loop starts at u2=u0u_2 = u_0 and, at line L15, lowers u2u_2 by one. Line L16 stops it when u2<0u_2 < 0 or when the newly added position u2+1u_2 + 1 is aligned. So the outer loop runs for u2=u0,u0−1,…u_2 = u_0, u_0 - 1, \ldots down to the last value such that u2≥0u_2 \ge 0 and all positions u2+1,…,u0u_2 + 1, \ldots, u_0 are unaligned. These are exactly the allowed values of u2u_2, because the condition "all of u2+1,…,u0u_2 + 1, \ldots, u_0 unaligned" stays false once it fails. The inner loop does the same for v2v_2 from v0v_0 upward with lines L13 and L14, and it does not depend on u2u_2. Line L12 tests the length. □\square

Theorem. P=P∗P = P^*.

Proof. Line L2 and L3 go over every source span with 1≤t−s≤L1 \le t - s \le L. Take one. If T(s,t)=∅T(s, t) = \emptyset, 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 uu or vv. 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 (u2,v2)(u_2, v_2) that meet the other conditions of Lemma 1 and have v2−u2≤Lv_2 - u_2 \le L. By Lemma 1 these are exactly the consistent pairs with this source span and both sides at most LL words. Each pair is added to a set, so none is counted twice. □\square

Termination and cost. There are at most mLm L source spans. For each, lines L4 and L7 read the ∣A∣|A| links once, and the loops of lines L8 to L16 run at most (u0+1)(l−v0+1)≤(l+1)2(u_0 + 1)(l - v_0 + 1) \le (l + 1)^2 times but add only pairs with v2−u2≤Lv_2 - u_2 \le L. With l′l' the length of the longest run of unaligned target words, the inner work is O((l′+1)2)O((l' + 1)^2) for each source span, and the total time is O(mL(∣A∣+(l′+1)2))O(m L (|A| + (l' + 1)^2)).

Complexity

Count in the word RAM model. There are at most mpm p source spans. For each, lines L4 and L7 read the aa links once, in O(a)O(a) 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 O(l2)O(l^2) times, and in practice a few times. The total time is O(mp(a+l2))O(m p (a + l^2)). Faster versions keep the minimum and the maximum of the targets as tt grows, so that line L4 costs O(1)O(1) amortized for each span. The extra space is O(a+l)O(a + l), not counting the output.

The output itself can be large. A sentence pair with a diagonal alignment of nn words has n(n+1)/2n(n + 1)/2 pairs without a length limit; for n=4n = 4 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 ff and ee 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 xx unaligned target words to its left and yy to its right can give up to (x+1)(y+1)(x + 1)(y + 1) 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 ss to tt" with "covers s+1s + 1 to tt" 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.

phrase_pair_extraction.pyI0RawGitHub
# 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

  1. Och, Tillmann and Ney 1999, the alignment template approach, with phrase pairs taken from a symmetrized word alignment
  2. Koehn, Och and Marcu 2003, the definition of phrase pairs consistent with a word alignment, and the comparison of phrase extraction methods
  3. 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)
  4. 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.

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