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.
- Solves
- Machine translation
- 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
- Model
- Word RAM
- Properties
- deterministicexactofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
- 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 to a target sentence with its parse tree. The extraction input is , a parse tree of whose leaves are the target positions , and a set of links from source position to target position . For an internal node of with leaf set :
- , the source positions aligned to the words under ;
- , the complement span, the source positions aligned to the words outside ;
- is a frontier node if and the closure holds no position of .
The output is the set of minimal rules, one for each frontier node . Its left side is the tree fragment from down to the next frontier nodes, which become variables , or down to words. Its right side is the source positions of the closure of in order, with the closure of each variable node replaced by its variable. This page gives the root the whole range , 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
GHKM(T, f, A)- 1
for each node n, children first: span(n) ← union of the spans of its children and the positions aligned to its leaf children - 2
comp(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 - 3
F ← { n : span(n) ≠ ∅ and no position of comp(n) lies in [min span(n), max span(n)] } - 4
for each n in F, in tree order do - 5
lhs ← the fragment below n: a child in F becomes a new variable x_q, a leaf stays a word, any other child is expanded - 6
R ← [1, m] if n is the root, else [min span(n), max span(n)] - 7
rhs ← 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 - 8
output the rule lhs → rhs - 9
return the rules
Line L2 works because the leaves outside a child of are the leaves outside plus the leaves under the siblings of . Line L7 is well defined because the closures of the variables of one rule are disjoint and lie inside , which the proofs file shows.
Example
Take the French source = 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(:NP :VP) | |
| NP | NP(:PRP) | |
| PRP | PRP(he) | il |
| VP | VP(AUX(does) RB(not) :VB) | ne 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(:VBZ :JJ) → ja .
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 of the target sentence , whose leaves in order are the positions , a source sentence , and a set of links between source position and target position . Only internal nodes of are considered as nodes below. For a node , let be the set of leaf positions under , and
Write for the closure of a non-empty set of positions. The node is a frontier node if and .
Lemma 1 (lines L1 to L3 compute these sets). After line L1, ; after line L2, ; 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 . Line L2 goes over the nodes parents first. The root has , so . For a child of , the leaves outside are the leaves outside and the leaves under the other children of , so is together with the spans of the siblings, which is what line L2 sets. Line L3 tests the definition.
The test file checks Lemma 1 against a second form of the definition: is a frontier node if and only if it has an aligned leaf, and every link whose source lies in has its target in . The two forms agree, because a position of is in exactly when it has a link to a target outside .
For a frontier node , line L5 builds the fragment: it walks down from and stops at frontier nodes (which become the variables in tree order) and at leaves (which become words). Let be its variable nodes. Line L6 sets the range , or for the root.
Lemma 2 (the variables have disjoint closures inside the range). For , . For distinct , . Every aligned position in that is not in a closure of a variable is aligned to a leaf of the fragment.
Proof. because , so its closure lies in the closure of , which is in . Neither of is below the other (the fragment stops at the first frontier node), so and . Since is a frontier node, holds no point of , in particular neither end of ; by symmetry the converse holds too. Two intervals that do not contain an end of each other are disjoint. For the last claim, let be aligned to some target . If is not the root, because is a frontier node, so every link of has its target in . If is the root, every target is in . A leaf in is under some or is a leaf of the fragment. If , then .
So line L7 is well defined: it walks over from left to right, writes once for the closure of the variable and jumps over it, and writes the source word for every other position. Each variable occurs exactly once on each side.
Theorem. Let be the rule of the frontier node . If , the root is a frontier node, and substituting, for each variable of , the result of the rule of , recursively, gives from the tree on the target side and the sentence on the source side. If , no node is a frontier node and there are no rules.
Proof. The root has and a non-empty span if , so it is a frontier node; with every span is empty. Target side: by induction from the bottom, substituting the subtree of at the variable in the fragment of gives the subtree of , because the fragment is the subtree of cut at the variables. Source side: by induction from the bottom, the rule of a frontier node derives the words for in order: the rule writes the positions of 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, , so the result is .
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 with sets of size up to . Each node is in at most one fragment as an inner node, and each range has at most positions, so lines L4 to L8 cost with the number of frontier nodes.
Complexity
Count in the word RAM model, with the spans as bit sets or sorted lists of at most positions. Line L1 does unions of sets of size at most , 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 for each node. Each node is inside one fragment, and each range has at most positions, so lines L4 to L8 cost . The total is 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.
# 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
- 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
- Galley et al. 2006, composed rules, the attachments of unaligned words, and the estimation of rule probabilities
- 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.
| 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 6NN595 Edit this page History Report an error Markdown