Algorithm Search⌘K

Algorithmadvanced

GHKM rule extraction

Also called string-to-tree rule extraction.

Extract minimal rules that pair a fragment of the target parse tree with a source string, cutting the word-aligned tree at its frontier nodes.

Time
O(n m) worst
Space
O(n m) extra
Where
m = the source sentence length; n = the number of nodes of the target tree
Properties
deterministicexactofflinerecursive
Origin
Michel Galley, Mark Hopkins, Kevin Knight, Daniel Marcu, 2004

GHKM rule extraction reads a sentence pair with a parse tree of the target sentence and a word alignment, and cuts the tree into translation rules. Each rule pairs a fragment of the target tree with a string of source words and variables, and the cuts are made only at frontier nodes, the nodes whose aligned source words form a block that no outside link reaches into. The rules found this way are the minimal rules; together they derive exactly the given tree and source sentence. They are the training step of string-to-tree syntax-based translation, where the decoder parses the source and builds a target tree.

In plain words

Take a sentence, its translation, a parse tree of the translation, and lines between words that mean the same thing. Look at one node of the tree and the source words that are joined to the words under it. If those source words form one block, and no source word inside the block is joined to a word outside the node, the node is a good place to cut. It is a frontier node.

Now cut the tree at all frontier nodes. Each piece reaches from one frontier node down to the next ones, and becomes a rule: on one side the piece of tree, with the lower frontier nodes as holes, and on the other side the block of source words, with the blocks of the holes as holes too. Put all the pieces back together and you get the whole tree and the whole sentence again.

The problem

Translation in the final system runs from a source sentence f=f1…fmf = f_1 \ldots f_m to a target sentence e=e1…ele = e_1 \ldots e_l with its parse tree. The extraction input is ff, a parse tree TT of ee whose leaves are the target positions 1,…,l1, \ldots, l, and a set AA of links (j,i)(j, i) from source position jj to target position ii. For an internal node nn of TT with leaf set Y(n)Y(n):

  • span(n)={j:(j,i)∈A,i∈Y(n)}\mathrm{span}(n) = \{j : (j, i) \in A, i \in Y(n)\}, the source positions aligned to the words under nn;
  • comp(n)={j:(j,i)∈A,i∉Y(n)}\mathrm{comp}(n) = \{j : (j, i) \in A, i \notin Y(n)\}, the complement span, the source positions aligned to the words outside nn;
  • nn is a frontier node if span(n)≠∅\mathrm{span}(n) \ne \emptyset and the closure [min⁡span(n),max⁡span(n)][\min \mathrm{span}(n), \max \mathrm{span}(n)] holds no position of comp(n)\mathrm{comp}(n).

The output is the set of minimal rules, one for each frontier node nn. Its left side is the tree fragment from nn down to the next frontier nodes, which become variables x0,x1,…x_0, x_1, \ldots, or down to words. Its right side is the source positions of the closure of span(n)\mathrm{span}(n) in order, with the closure of each variable node replaced by its variable. This page gives the root the whole range 1,…,m1, \ldots, m, and lets an unaligned source word be taken by the lowest frontier node whose range holds it.

The rules pair a target tree fragment with a source string. Galley et al. (2004) read them in the direction of the noisy channel, from the English tree to the foreign string, which is why they are often called tree-to-string rules. A string-to-tree decoder uses them the other way: it parses the source string and builds the target tree.

The algorithm

  1. GHKM(T, f, A)
  2. 1for each node n, children first: span(n) ← union of the spans of its children and the positions aligned to its leaf children
  3. 2comp(root) ← ∅; for each node n, parents first, and each child k of n: comp(k) ← comp(n) ∪ the spans of the other children of n
  4. 3F ← { n : span(n) ≠ ∅ and no position of comp(n) lies in [min span(n), max span(n)] }
  5. 4for each n in F, in tree order do
  6. 5lhs ← the fragment below n: a child in F becomes a new variable x_q, a leaf stays a word, any other child is expanded
  7. 6R ← [1, m] if n is the root, else [min span(n), max span(n)]
  8. 7rhs ← the positions of R from left to right, where the closure of the span of variable x_q is written once as x_q and every other position j as f_j
  9. 8output the rule lhs → rhs
  10. 9return the rules

Line L2 works because the leaves outside a child kk of nn are the leaves outside nn plus the leaves under the siblings of kk. Line L7 is well defined because the closures of the variables of one rule are disjoint and lie inside RR, which the proofs file shows.

Example

Take the French source ff = il ne va pas and the English tree S(NP(PRP he) VP(AUX does, RB not, VB go)), with the links il to he, ne to not, va to go and pas to not. The word does is not aligned. The spans and complement spans are

node span closure complement span frontier?
S 1, 2, 3, 4 1 to 4 none yes
NP, PRP 1 1 2, 3, 4 yes
VP 2, 3, 4 2 to 4 1 yes
AUX none 1, 2, 3, 4 no (empty span)
RB 2, 4 2 to 4 1, 3 no (3 is inside)
VB 3 3 1, 2, 4 yes

RB is not a frontier node, because not is linked to both ne and pas, and va lies between them but belongs to go. The five minimal rules are

node left side (target tree fragment) right side (source)
S S(x0x_0:NP x1x_1:VP) x0x_0 x1x_1
NP NP(x0x_0:PRP) x0x_0
PRP PRP(he) il
VP VP(AUX(does) RB(not) x0x_0:VB) ne x0x_0 pas
VB VB(go) va

The VP rule is the interesting one: it learns that "ne ... pas" around a verb becomes "does not" before it, with an English word, does, that has no source counterpart. A phrase-based model could not state this with a gap. Substituting the rules into each other gives back the tree and "il ne va pas".

Unaligned source words. With the tree S(NP(DT the, NN house) VP(VBZ is, JJ small)), the source das haus ist ja klein, and the links das to the, haus to house, ist to is and klein to small, the word ja is not aligned. It lies in the closure 3 to 5 of the VP, so the VP rule is VP(x0x_0:VBZ x1x_1:JJ) → x0x_0 ja x1x_1.

Correctness

The proofs file shows three facts. Lines L1 to L3 compute the spans, the complement spans and the frontier set as defined. In each rule, the closures of the variable nodes are disjoint and lie in the range of the rule, so the right side has each variable once. And applying the rules from the root down gives back the target tree and the whole source sentence. The extraction is exact for its definition; whether the rules translate well depends on the parse and the alignment. The test file compares the frontier set with a direct form of the definition on 500 random trees and alignments, and checks that the rules derive the input.

Proof: GHKM finds the frontier nodes, and its minimal rules derive the given tree and source sentencefull

The input is a parse tree TT of the target sentence e=e1…ele = e_1 \ldots e_l, whose leaves in order are the positions 1,…,l1, \ldots, l, a source sentence f=f1…fmf = f_1 \ldots f_m, and a set AA of links (j,i)(j, i) between source position jj and target position ii. Only internal nodes of TT are considered as nodes below. For a node nn, let Y(n)Y(n) be the set of leaf positions under nn, and

span(n)={j:(j,i)∈A,i∈Y(n)},comp(n)={j:(j,i)∈A,i∉Y(n)}.\mathrm{span}(n) = \{j : (j, i) \in A, i \in Y(n)\}, \qquad \mathrm{comp}(n) = \{j : (j, i) \in A, i \notin Y(n)\}.

Write cl(S)={min⁡S,…,max⁡S}\mathrm{cl}(S) = \{\min S, \ldots, \max S\} for the closure of a non-empty set of positions. The node nn is a frontier node if span(n)≠∅\mathrm{span}(n) \ne \emptyset and cl(span(n))∩comp(n)=∅\mathrm{cl}(\mathrm{span}(n)) \cap \mathrm{comp}(n) = \emptyset.

Lemma 1 (lines L1 to L3 compute these sets). After line L1, span[n]=span(n)\mathrm{span}[n] = \mathrm{span}(n); after line L2, comp[n]=comp(n)\mathrm{comp}[n] = \mathrm{comp}(n); line L3 marks exactly the frontier nodes.

Proof. Line L1 goes over the nodes children first, and sets the span of a node to the union of the spans of its children and of its leaf children, so by induction it is the set of positions aligned to Y(n)Y(n). Line L2 goes over the nodes parents first. The root has Y={1,…,l}Y = \{1, \ldots, l\}, so comp=∅\mathrm{comp} = \emptyset. For a child kk of nn, the leaves outside Y(k)Y(k) are the leaves outside Y(n)Y(n) and the leaves under the other children of nn, so comp(k)\mathrm{comp}(k) is comp(n)\mathrm{comp}(n) together with the spans of the siblings, which is what line L2 sets. Line L3 tests the definition. □\square

The test file checks Lemma 1 against a second form of the definition: nn is a frontier node if and only if it has an aligned leaf, and every link whose source lies in cl(span(n))\mathrm{cl}(\mathrm{span}(n)) has its target in Y(n)Y(n). The two forms agree, because a position of cl(span(n))\mathrm{cl}(\mathrm{span}(n)) is in comp(n)\mathrm{comp}(n) exactly when it has a link to a target outside Y(n)Y(n).

For a frontier node nn, line L5 builds the fragment: it walks down from nn and stops at frontier nodes (which become the variables x0,x1,…x_0, x_1, \ldots in tree order) and at leaves (which become words). Let V(n)V(n) be its variable nodes. Line L6 sets the range R(n)=cl(span(n))R(n) = \mathrm{cl}(\mathrm{span}(n)), or {1,…,m}\{1, \ldots, m\} for the root.

Lemma 2 (the variables have disjoint closures inside the range). For v∈V(n)v \in V(n), cl(span(v))⊆R(n)\mathrm{cl}(\mathrm{span}(v)) \subseteq R(n). For distinct v,v′∈V(n)v, v' \in V(n), cl(span(v))∩cl(span(v′))=∅\mathrm{cl}(\mathrm{span}(v)) \cap \mathrm{cl}(\mathrm{span}(v')) = \emptyset. Every aligned position in R(n)R(n) that is not in a closure of a variable is aligned to a leaf of the fragment.

Proof. span(v)⊆span(n)\mathrm{span}(v) \subseteq \mathrm{span}(n) because Y(v)⊆Y(n)Y(v) \subseteq Y(n), so its closure lies in the closure of span(n)\mathrm{span}(n), which is in R(n)R(n). Neither of v,v′v, v' is below the other (the fragment stops at the first frontier node), so Y(v′)∩Y(v)=∅Y(v') \cap Y(v) = \emptyset and span(v′)⊆comp(v)\mathrm{span}(v') \subseteq \mathrm{comp}(v). Since vv is a frontier node, cl(span(v))\mathrm{cl}(\mathrm{span}(v)) holds no point of span(v′)\mathrm{span}(v'), in particular neither end of cl(span(v′))\mathrm{cl}(\mathrm{span}(v')); by symmetry the converse holds too. Two intervals that do not contain an end of each other are disjoint. For the last claim, let j∈R(n)j \in R(n) be aligned to some target ii. If nn is not the root, j∉comp(n)j \notin \mathrm{comp}(n) because nn is a frontier node, so every link of jj has its target in Y(n)Y(n). If nn is the root, every target is in Y(n)Y(n). A leaf in Y(n)Y(n) is under some v∈V(n)v \in V(n) or is a leaf of the fragment. If i∈Y(v)i \in Y(v), then j∈span(v)j \in \mathrm{span}(v). □\square

So line L7 is well defined: it walks over R(n)R(n) from left to right, writes xqx_q once for the closure of the variable vqv_q and jumps over it, and writes the source word fjf_j for every other position. Each variable occurs exactly once on each side.

Theorem. Let ρ(n)\rho(n) be the rule of the frontier node nn. If A≠∅A \ne \emptyset, the root is a frontier node, and substituting, for each variable xqx_q of ρ(n)\rho(n), the result of the rule of vqv_q, recursively, gives from ρ(root)\rho(\mathrm{root}) the tree TT on the target side and the sentence ff on the source side. If A=∅A = \emptyset, no node is a frontier node and there are no rules.

Proof. The root has comp=∅\mathrm{comp} = \emptyset and a non-empty span if A≠∅A \ne \emptyset, so it is a frontier node; with A=∅A = \emptyset every span is empty. Target side: by induction from the bottom, substituting the subtree of vqv_q at the variable xqx_q in the fragment of nn gives the subtree of nn, because the fragment is the subtree of nn cut at the variables. Source side: by induction from the bottom, the rule of a frontier node vv derives the words fjf_j for j∈R(v)j \in R(v) in order: the rule writes the positions of R(v)R(v) from left to right, with the closure of each variable replaced by that variable, and by induction the variable derives exactly the words of its closure, which is its range. For the root, R={1,…,m}R = \{1, \ldots, m\}, so the result is ff. □\square

Unaligned words. A source position that is not aligned lies in the range of the root. It is written by the rule of the lowest frontier node whose range holds it, because a node writes a position of its range unless the position is inside the closure of one of its variables, where the variable's rule takes it. This is one fixed choice. Galley et al. (2006) keep every possible attachment instead.

Cost. Lines L1 to L3 cost O(∣T∣⋅m)O(|T| \cdot m) with sets of size up to mm. Each node is in at most one fragment as an inner node, and each range has at most mm positions, so lines L4 to L8 cost O(∣T∣+Fm)O(|T| + F m) with FF the number of frontier nodes.

Complexity

Count in the word RAM model, with the spans as bit sets or sorted lists of at most mm positions. Line L1 does O(n)O(n) unions of sets of size at most mm, and line L2 the same if each node keeps the union of its children's spans and subtracts, or combines prefix and suffix unions of its children. Line L3 costs O(m)O(m) for each node. Each node is inside one fragment, and each range has at most mm positions, so lines L4 to L8 cost O(n+∣F∣m)O(n + |F| m). The total is O(nm)O(n m) time and space for one sentence pair.

Properties

  • Unique minimal rules. Given the tree, the alignment and the convention for unaligned words, the set of minimal rules is fixed by the definition: there is one rule for each frontier node.
  • Derives the input. The rules form one derivation of the sentence pair.
  • Rules can be large. When the alignment crosses a lot, few nodes are frontier nodes, and a rule may cover a large part of the tree.
  • Many-to-many words. A rule can hold target words with no source word (does above) and source words with no target word (ja above).
  • Reordering in the rule. The order of the variables on the right side can differ from the left side, so the rules reorder whole constituents.

Variants and improvements

  • Composed rules. Galley et al. (2006) join adjacent minimal rules into larger rules, up to a size limit, which gives more context and better translations in their measurements.
  • All attachments of unaligned words. Instead of one fixed attachment, Galley et al. (2006) consider every frontier node that an unaligned source word can attach to, and weight the derivations by expectation maximization.
  • Tree-to-string and tree-to-tree. With a parse of the source instead of the target, the same frontier test gives rules for tree-to-string decoding, and with parses of both, for tree-to-tree models.
  • Binarization and relabeling. Restructuring the tree (for example binarizing flat nodes) creates more frontier nodes and smaller rules.
  • Hierarchical rules without syntax. Hiero extracts rules with gaps from any consistent phrase pair, with one nonterminal label, instead of only at tree nodes.

When to use it

Use GHKM to train a string-to-tree system, where target syntax should guide reordering and output grammar, for language pairs with very different word order such as Chinese to English or German to English. It needs a good target parser and a reasonably precise alignment, because one wrong link can remove frontier nodes. Without a parser, use Hiero or a phrase-based model.

Pitfalls

  • Testing the span instead of its closure. A node can have aligned positions with a gap that holds a word aligned elsewhere, as for RB above. Test the closure against the complement span.
  • Losing unaligned source words. If unaligned words outside every closure are not attached somewhere, the rules no longer derive the whole sentence. Give the root the whole range, or attach them to a neighbouring node.
  • Counting leaves as frontier nodes. Only internal nodes can be frontier nodes; the words are the terminals of the rules.
  • Variable order. Number the variables in the order of the tree, and write them on the source side in source order. Mixing the two scrambles the reordering.
  • Rule size. Composed rules grow fast. Limit their size, or the rule table becomes too large to store.

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.

ghkm_rule_extraction.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ghkm-rule-extraction/. The authors are listed in prov/6NN595.jsonl.

"""Minimal GHKM rule extraction (Galley, Hopkins, Knight and Marcu 2004).

Input: a parse tree of the target sentence e (its leaves are the target
positions 1..l), the source sentence f = f_1..f_m, and word alignment links
(j, i) that join source position j to target position i.

span(n) is the set of source positions aligned to the leaves under node n.
complement_span(n) is the set of source positions aligned to the leaves
outside the subtree of n. A node n is a frontier node if span(n) is not empty
and the closure [min span(n), max span(n)] holds no position of
complement_span(n). Each frontier node gives one minimal rule: its left side is
the tree fragment from n down to the next frontier nodes (which become
variables) or to the words; its right side is the source words of the closure,
with the closure of each variable node replaced by the variable.

An unaligned source word goes to the lowest frontier node whose closure holds
it. The root is given the whole source sentence [1, m].
"""

from dataclasses import dataclass, field
from typing import Union


@dataclass(eq=False)
class Node:
    label: str
    kids: list = field(default_factory=list)  # Node or int (target position)


@dataclass
class Rule:
    node: Node
    lhs: str
    rhs: tuple[str, ...]
    variables: list[Node]


def parse(text: str) -> tuple[Node, list[str]]:
    """Parse '(S (NP (PRP he)) (VP (VB go)))'. Leaves become positions 1..l."""
    tokens = text.replace("(", " ( ").replace(")", " ) ").split()
    words: list[str] = []
    pos = 0

    def node() -> Node:
        nonlocal pos
        assert tokens[pos] == "("
        n = Node(tokens[pos + 1])
        pos += 2
        while tokens[pos] != ")":
            if tokens[pos] == "(":
                n.kids.append(node())
            else:
                words.append(tokens[pos])
                n.kids.append(len(words))
                pos += 1
        pos += 1
        return n

    root = node()
    if pos != len(tokens):
        raise ValueError("text after the tree")
    return root, words


def tree_string(n: Node, words: list[str]) -> str:
    return n.label + "(" + " ".join(words[k - 1] if isinstance(k, int) else tree_string(k, words) for k in n.kids) + ")"


def preorder(n: Node) -> list[Node]:
    out = [n]
    for k in n.kids:
        if isinstance(k, Node):
            out.extend(preorder(k))
    return out


def frontier_nodes(root: Node, m: int, links: set[tuple[int, int]]) -> tuple[set[Node], dict, dict]:
    """Return (frontier set, span, complement_span)."""
    src: dict[int, set[int]] = {}
    for j, i in links:
        if not 1 <= j <= m:
            raise ValueError(f"source position {j} out of range")
        src.setdefault(i, set()).add(j)

    span: dict[Node, set[int]] = {}

    def kid_span(k: Union[Node, int]) -> set[int]:
        return src.get(k, set()) if isinstance(k, int) else span[k]

    for n in reversed(preorder(root)):  # @line L1
        span[n] = set().union(*[kid_span(k) for k in n.kids])
    comp: dict[Node, set[int]] = {root: set()}
    for n in preorder(root):  # @line L2
        for a, k in enumerate(n.kids):
            if isinstance(k, Node):
                comp[k] = comp[n].union(*[kid_span(b) for c, b in enumerate(n.kids) if c != a])
    frontier = set()
    for n in preorder(root):  # @line L3
        s = span[n]
        if s and not any(min(s) <= j <= max(s) for j in comp[n]):
            frontier.add(n)
    return frontier, span, comp


def extract_minimal_rules(root: Node, words: list[str], f: list[str], links: set[tuple[int, int]]) -> list[Rule]:
    m = len(f)
    for j, i in links:
        if not 1 <= i <= len(words):
            raise ValueError(f"target position {i} out of range")
    frontier, span, _ = frontier_nodes(root, m, links)
    rules = []
    for n in preorder(root):  # @line L4
        if n not in frontier:
            continue
        variables: list[Node] = []

        def fragment(x: Node) -> str:  # @line L5
            parts = []
            for k in x.kids:
                if isinstance(k, int):
                    parts.append(words[k - 1])
                elif k in frontier:
                    parts.append(f"x{len(variables)}:{k.label}")
                    variables.append(k)
                else:
                    parts.append(fragment(k))
            return x.label + "(" + " ".join(parts) + ")"

        lhs = fragment(n)
        lo, hi = (1, m) if n is root else (min(span[n]), max(span[n]))  # @line L6
        starts = {min(span[v]): (v_idx, max(span[v])) for v_idx, v in enumerate(variables)}
        rhs: list[str] = []
        j = lo
        while j <= hi:  # @line L7
            if j in starts:
                v_idx, end = starts[j]
                rhs.append(f"x{v_idx}")
                j = end + 1
            else:
                rhs.append(f[j - 1])
                j += 1
        rules.append(Rule(n, lhs, tuple(rhs), variables))  # @line L8
    return rules  # @line L9


def derive(rule_of: dict, n: Node, words: list[str]) -> tuple[str, list[str]]:
    """Apply the rules from node n down: return (tree string, source words)."""
    rule = rule_of[n]
    lhs, sub = rule.lhs, []
    for v_idx, v in enumerate(rule.variables):
        t, s = derive(rule_of, v, words)
        lhs = lhs.replace(f"x{v_idx}:{v.label}", t, 1)
        sub.append(s)
    out: list[str] = []
    for sym in rule.rhs:
        if sym.startswith("x") and sym[1:].isdigit():
            out.extend(sub[int(sym[1:])])
        else:
            out.append(sym)
    return lhs, out


def brute_force_frontier(root: Node, m: int, links: set[tuple[int, int]]) -> set[Node]:
    """A node is a frontier node if it covers at least one aligned word and every
    source word between its first and last aligned source words is aligned only
    to leaves under the node (or not aligned at all)."""
    out = set()
    for n in preorder(root):
        under = set()
        stack = [n]
        while stack:
            x = stack.pop()
            for k in x.kids:
                if isinstance(k, int):
                    under.add(k)
                else:
                    stack.append(k)
        js = {j for j, i in links if i in under}
        if not js:
            continue
        if all(i in under for j, i in links if min(js) <= j <= max(js)):
            out.add(n)
    return out
test_ghkm_rule_extraction.py 113 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ghkm-rule-extraction/. The authors are listed in prov/6NN595.jsonl.

import random

import pytest

from ghkm_rule_extraction import (
    Node,
    brute_force_frontier,
    derive,
    extract_minimal_rules,
    frontier_nodes,
    parse,
    preorder,
    tree_string,
)


def test_example() -> None:
    root, words = parse("(S (NP (PRP he)) (VP (AUX does) (RB not) (VB go)))")
    f = "il ne va pas".split()
    links = {(1, 1), (2, 3), (3, 4), (4, 3)}
    frontier, span, comp = frontier_nodes(root, len(f), links)
    by_label = {n.label: n for n in preorder(root)}
    assert span[by_label["RB"]] == {2, 4} and comp[by_label["RB"]] == {1, 3}
    assert span[by_label["AUX"]] == set()
    assert {n.label for n in frontier} == {"S", "NP", "PRP", "VP", "VB"}
    rules = [(r.lhs, " ".join(r.rhs)) for r in extract_minimal_rules(root, words, f, links)]
    assert rules == [
        ("S(x0:NP x1:VP)", "x0 x1"),
        ("NP(x0:PRP)", "x0"),
        ("PRP(he)", "il"),
        ("VP(AUX(does) RB(not) x0:VB)", "ne x0 pas"),
        ("VB(go)", "va"),
    ]


def test_unaligned_source_word() -> None:
    root, words = parse("(S (NP (DT the) (NN house)) (VP (VBZ is) (JJ small)))")
    f = "das haus ist ja klein".split()
    links = {(1, 1), (2, 2), (3, 3), (5, 4)}
    rules = {r.node.label: (r.lhs, " ".join(r.rhs)) for r in extract_minimal_rules(root, words, f, links)}
    # "ja" (position 4) lies inside the closure [3, 5] of the VP, so the VP rule takes it
    assert rules["VP"] == ("VP(x0:VBZ x1:JJ)", "x0 ja x1")
    assert rules["S"] == ("S(x0:NP x1:VP)", "x0 x1")
    # an unaligned word outside every closure goes to the root
    f2 = "also das haus ist klein".split()
    links2 = {(2, 1), (3, 2), (4, 3), (5, 4)}
    rules2 = {r.node.label: " ".join(r.rhs) for r in extract_minimal_rules(root, words, f2, links2)}
    assert rules2["S"] == "also x0 x1"


def test_crossing_alignment_blocks_frontier() -> None:
    root, words = parse("(S (A a) (B b) (C c))")
    f = ["p", "q", "r"]
    links = {(1, 1), (2, 3), (3, 2)}
    frontier, _, _ = frontier_nodes(root, 3, links)
    assert {n.label for n in frontier} == {"S", "A", "B", "C"}
    rules = {r.node.label: " ".join(r.rhs) for r in extract_minimal_rules(root, words, f, links)}
    assert rules["S"] == "x0 x2 x1"
    # a one-to-many link whose closure holds a word of a sibling removes A
    links = {(1, 1), (2, 2), (3, 1)}
    frontier, _, _ = frontier_nodes(root, 3, links)
    assert {n.label for n in frontier} == {"S", "B"}
    rules = [(r.lhs, " ".join(r.rhs)) for r in extract_minimal_rules(root, words, f, links)]
    assert rules == [("S(A(a) x0:B C(c))", "p x0 r"), ("B(b)", "q")]


def test_bad_input() -> None:
    root, words = parse("(S (A a))")
    with pytest.raises(ValueError):
        extract_minimal_rules(root, words, ["p"], {(2, 1)})
    with pytest.raises(ValueError):
        extract_minimal_rules(root, words, ["p"], {(1, 2)})
    assert extract_minimal_rules(root, words, ["p"], set()) == []


def random_tree(rng: random.Random, positions: list[int]) -> Node:
    if len(positions) == 1:
        n = Node(rng.choice("PQ"), [positions[0]])
        return Node(rng.choice("UV"), [n]) if rng.random() < 0.2 else n
    parts = rng.randint(2, min(3, len(positions)))
    cuts = sorted(rng.sample(range(1, len(positions)), parts - 1))
    groups = [positions[a:b] for a, b in zip([0] + cuts, cuts + [len(positions)])]
    return Node(rng.choice("XYZ"), [random_tree(rng, g) for g in groups])


def test_random_against_definition() -> None:
    rng = random.Random(2004)
    checked = 0
    for _ in range(500):
        n_e, m = rng.randint(1, 6), rng.randint(1, 6)
        root = random_tree(rng, list(range(1, n_e + 1)))
        words = [f"e{i}" for i in range(1, n_e + 1)]
        f = [f"f{j}" for j in range(1, m + 1)]
        links = {(j, i) for j in range(1, m + 1) for i in range(1, n_e + 1) if rng.random() < 0.3}
        frontier, _, _ = frontier_nodes(root, m, links)
        assert frontier == brute_force_frontier(root, m, links)
        rules = extract_minimal_rules(root, words, f, links)
        if not links:
            assert rules == []
            continue
        assert rules[0].node is root
        rule_of = {r.node: r for r in rules}
        for r in rules:
            names = [s for s in r.rhs if s.startswith("x")]
            assert sorted(names) == [f"x{k}" for k in range(len(r.variables))]
        tree, source = derive(rule_of, root, words)
        assert tree == tree_string(root, words)
        assert source == f
        checked += 1
    assert checked > 300

History

Yamada and Knight (2001) had proposed a syntax-based channel model with fixed node operations. Galley, Hopkins, Knight and Marcu (2004) asked which tree-to-string rules a word-aligned parse tree can explain, defined the frontier set, and showed how to extract the minimal rules. The name GHKM comes from the initials of these four authors. Galley et al. (2006) made the method practical with composed rules, the handling of unaligned words, and rule probabilities, and it became the rule extractor of string-to-tree systems such as the ISI system and the syntax mode of Moses.

References

  1. Galley, Hopkins, Knight and Marcu 2004, the span and complement span of a node, the frontier set, and the extraction of minimal rules from the frontier graph
  2. Galley et al. 2006, composed rules, the attachments of unaligned words, and the estimation of rule probabilities
  3. Philipp Koehn, Statistical Machine Translation, Cambridge University Press, 2010, Chapter 11 (tree-based models: learning syntactic translation rules)

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