Algorithmadvanced
Cube pruning
Also called lazy k-best combination.
Approximate k-best combination of hypotheses at each chart cell with a language model, exploring a grid of sorted options lazily from a heap.
- Solves
- Machine translation
- Time
- O((g + k r) log(g + k r)) worst
- Space
- O(g + k r) extra
- Where
- g = the number of hyperedges into the cell; k = the number of items popped per cell; r = the largest number of children of a rule
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- David Chiang, Liang Huang, 2007
Cube pruning is a heuristic that builds the best few items of one cell of a chart decoder, for example in hierarchical phrase-based translation, without scoring every combination of a rule with the items of its children. Each rule with children gives an -dimensional grid of combinations, sorted along each axis, and cube pruning explores it from the best corner with a priority queue, stopping after items. Without a language model this is the exact lazy -best algorithm of Huang and Chiang (2005). With an n-gram language model the scores are no longer monotone along the axes, so cube pruning is approximate.
In plain words
A chart decoder builds translations of long pieces of a sentence from translations of shorter pieces. A rule says, for example, "put the translation of this part, then the word of, then the translation of that part". Each part has a list of candidates, best first. Trying every pair is too slow.
So the method starts with the best candidate of each part and computes that combination. Then it looks at the neighbours: the next candidate of the first part with the best of the second, and the best of the first with the next of the second. It always expands the best combination seen so far, up to a fixed number. If the score were just a sum, this would find the true best combinations. The language model also scores the words where the parts meet, so a worse candidate can join better, and the method can miss it.
The problem
Translation runs from a source to a target . A chart decoder for a synchronous grammar fills a cell for each source span (fencepost: it covers ). An item is a partial translation with a score and target words. A hyperedge into the cell is a rule that applies to the span, with a rule score, a target pattern of words and variables, and one child cell for each variable. The child cells are already filled, and each holds a list of items sorted best first.
For a hyperedge with child lists , a grid point chooses item of list . Its item has the target words of the pattern with each variable replaced by the words of its chosen child, and the score
where the new bigrams are those that cross a boundary between a rule word and a child or between two children, logs are natural, and is the language model weight. The task is to find the highest items over all grid points of all hyperedges into the cell. Exhaustive scoring costs , which is per rule when each child keeps items.
The algorithm
CUBE-PRUNE(hyperedges, k)- 1
Q ← empty max-heap; buffer ← empty list; seen ← ∅ - 2
for each hyperedge e with no empty child list do push (sc_e(0, .., 0), e, (0, .., 0)) on Q; add it to seen - 3
while Q is not empty and |buffer| < k do - 4
pop the best (score, e, j) from Q - 5
append its item to buffer - 6
for x ← 1 to r_e do - 7
j' ← j with j_x raised by one; if j' is in the grid and (e, j') ∉ seen then - 8
compute sc_e(j'); push it on Q; add (e, j') to seen - 9
sort buffer by score, best first - 10
return buffer
Line L2 puts the best corner of every hyperedge into one heap, so the hyperedges of the cell compete with each other. Lines L6 to L8 push the neighbours of the popped point. The set seen stops a point from being pushed twice, because a point with two raised coordinates has two predecessors. Line L9 is needed because the pops are not in order of score when the language model is used. In a full decoder the buffer then goes through recombination of items with the same language model state, and becomes the cell's sorted list.
Example
A rule joins a subject and a verb. The subject cell has he (), they (), she (), and the verb cell has go (), goes (), went (). The bigram scores at the junction, in natural log, are for "he go", "they goes" and "she go", for "he goes" and "she goes", for "they go", and for the three with went. The rule score is 0 and . The full grid of scores is
| go | goes | went | |
|---|---|---|---|
| he | |||
| they | |||
| she |
The scores are not sorted along the rows or columns, because of the junction bigram. Cube pruning with runs as follows.
| pop | point | item | score | pushed |
|---|---|---|---|---|
| 1 | (0, 0) | he go | they go (), he goes () | |
| 2 | (1, 0) | they go | she go (), they goes () | |
| 3 | (0, 1) | he goes | he went () |
The result is they go , he goes , he go . The true top three are they go , he goes and she goes . The point "she goes" is never pushed, because both of its predecessors, "they goes" and "she go", score badly. With , the fourth pop is he went (), and "she goes" is still missed.
Without the language model (), the scores are the sums , which decrease along every row and column. Cube pruning with then returns he go , he goes and they go , the exact top three.
Correctness
Two theorems are proved in the proofs file. If the score is monotone, that is, it never increases when one coordinate is raised, the first pops are exactly the best grid points, in order. The reason is that every unpopped point has an ancestor in the heap that scores at least as high, so the heap's best is the best unpopped point. For any scores, every returned item is a real grid point with its true score, the result is sorted, and with at least the grid size every point is returned. Cube pruning with a language model is a heuristic: the example shows a case where it misses a top item. The test file checks exactness against brute force without a language model on 400 random cells, and finds misses with one.
Proof: The lazy grid search of cube pruning is exact for monotone scores and a heuristic with a language modelfull
A chart cell gets hyperedges . Hyperedge has child lists , each sorted best first. A grid point of is a vector with , and it has a score . Write for with coordinate raised by one. CUBE-PRUNE pushes the corner of each hyperedge (line L2), then pops at most grid points from a max-heap (lines L3 to L5), and after each pop pushes the neighbours that exist and were never pushed (lines L6 to L8). A grid point is pushed at most once, because of the set of pushed points.
The score is monotone if for every , and with in the grid. Without a language model, is the rule score plus the sum of the child scores, and each child list is sorted, so the score is monotone.
Lemma 1 (every grid point has a pushed ancestor). At the start of each pass of line L3, every grid point of every hyperedge that was not popped yet has a point (coordinate by coordinate) that is in the heap.
Proof. Take the path from the corner to that raises the coordinates one at a time. The corner was pushed at line L2. Walk along the path to the first point that was not popped. If it is the corner, it is in the heap. Otherwise its predecessor on the path was popped, and when it was popped, line L8 pushed all its neighbours that were not pushed before. So the point was pushed at some time, and it was not popped, so it is still in the heap.
Theorem 1 (exact for monotone scores). If the score is monotone, the points popped by CUBE-PRUNE are, in order, a list of the highest grid points of all hyperedges, with the total number of grid points. Line L9 does not change their order.
Proof. Consider a pop at line L4, and let be any grid point that was not popped before it. By Lemma 1 the heap holds some , and by monotonicity along the path from to , . The popped point has the largest score in the heap, so its score is at least . So each pop takes a highest point among those not popped yet. By induction, the first pops are highest points in decreasing order of score. The loop runs until pops or until the heap is empty, and by Lemma 1 the heap is empty only when every point was popped.
This is the lazy enumeration of Huang and Chiang (2005) for one hyperedge, and its merge over the hyperedges of one cell.
Theorem 2 (always true). For any scores, (a) each popped item is a real grid point with its true score; (b) line L9 returns the popped items in decreasing order of score; (c) if , every grid point is popped, so the result is the full sorted list; (d) the -th best returned score is at most the -th best grid score.
Proof. (a) Line L8 pushes the point with the score that COMBINE computes for it. (b) Line L9 sorts. (c) By Lemma 1, while a point is not popped the heap is not empty, so with the loop stops only when all points are popped. (d) The returned items are distinct grid points, and the -th best of any set of distinct grid points is at most the -th best of all of them.
With a language model the score is not monotone. COMBINE adds the bigram scores at the junctions between the target words of a rule and of its children. A child item that is worse on its own can make a much better junction, so can happen. Then the proof of Theorem 1 breaks, because the ancestor in the heap can score lower than a point behind it. In the example of the page, the corner "he go" scores , and its neighbours score and . With , the point "she goes" () is never pushed, because it lies behind "they goes" () and "she go" (), and the result holds "he go" at in its place. So cube pruning with a language model is a heuristic. Theorem 2 still holds.
Cost. Each pop pushes at most points, with . So the heap holds at most items, and the first pushes, the pops and the other pushes cost heap work, plus calls of COMBINE. Without the lazy search, all points would be scored; with child lists of size , that is up to .
Complexity
Count in the word RAM model, with one language model lookup as one step. Let be the number of hyperedges into the cell and the largest number of children of a rule. Each pop pushes at most points, so the heap holds at most entries. The first pushes, the pops and the other pushes cost with a binary heap, plus computations of an item score, each costing for a bigram model and items of bounded length. Exhaustive scoring would cost item scores. For a whole chart with cells, the time is where is now the largest number of hyperedges per cell.
Properties
- Exact without a language model. It is then the lazy -best algorithm (a theorem).
- Approximate with a language model. The junction bigrams make the scores non-monotone, so it is a heuristic, and its search errors fall as grows.
- Sorted output. The buffer is sorted at the end, so the next cells see sorted lists, which the method needs.
- Shares one heap per cell. All hyperedges of a cell compete in one heap, so a cell with many rules spends its pops on the most promising rules.
- Not a beam on each rule. A rule whose corner is poor may get no pops at all.
Variants and improvements
- Cube growing. Huang and Chiang (2007) compute the child lists lazily too, on demand from the parent, which saves work on lists that are never read far.
- Phrase-based cube pruning. Moses applies the same grid search to phrase-based decoding, with the hypotheses of a stack on one axis and the translation options of a source span on the other.
- Diversity. Some decoders keep at least one pop per hyperedge, so that a rule is not shut out by a bad corner.
- Better estimates. Better language model estimates of the first and last words of an item make the scores closer to monotone, and fewer items are missed.
- Lazy k-best on a hypergraph. The same lazy enumeration, applied to a whole hypergraph without a language model, gives the best derivations of a CKY-style chart, like k shortest paths.
When to use it
Use cube pruning in a chart decoder for a synchronous grammar, such as Hiero or a syntax-based model with GHKM rules, to integrate an n-gram language model. A pop limit in the hundreds or around a thousand per cell is common. Without a language model, the same procedure is exact and is the lazy way to get k-best lists from a chart. For phrase-based decoding, the usual stack decoder is simpler; cube pruning there is a speed option.
Pitfalls
- Pushing a point twice. A point with two raised coordinates has two predecessors. Without the seen set it enters the heap twice and appears twice in the output.
- Unsorted child lists. The method assumes the child lists are sorted best first. Sort each cell's buffer before it is used as a child, as in line L9.
- Counting the bigrams twice. A child's score already includes the bigrams inside it. Add only the new bigrams at the junctions.
- The first words of an item. The first words of an item have no left context until a parent places them. Use a language model estimate for them, and correct it when the context is known; otherwise items that start with rare words are ranked too low or too high.
- Expecting exactness. With a language model, a larger reduces search errors but does not remove them.
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/cube-pruning/. The authors are listed in prov/6RZK3C.jsonl.
"""Cube pruning (Chiang 2007) for one cell of a chart decoder.
A cell receives hyperedges. A hyperedge is a rule with a score and a target
pattern, and a list of child cells; each child cell is a list of items sorted
by score, best first. An item is (score, words). Choosing item j_i in child
cell i gives a grid point j = (j_1, ..., j_r); its item has the words of the
target pattern with each variable replaced by the words of its child item,
and the score
rule score + sum of the child scores + lm_weight * (new bigram scores),
where the new bigrams are those of the result that are not inside a child item.
With lm_weight = 0 the score is monotone in each j_i, and cube pruning pops the
exact k best grid points (the lazy k-best enumeration of Huang and Chiang 2005).
With a language model the score is not monotone, and cube pruning is a heuristic.
"""
import heapq
import itertools
from dataclasses import dataclass, field
Item = tuple[float, tuple[str, ...]]
class BigramScores:
"""Bigram log probabilities (natural log) with a default for unseen pairs."""
def __init__(self, table: dict[tuple[str, str], float], default: float) -> None:
self.table, self.default = dict(table), default
def inside(self, words: tuple[str, ...]) -> float:
return sum(self.table.get(p, self.default) for p in zip(words, words[1:]))
@dataclass
class Edge:
rule_score: float
pattern: tuple # words (str) and variables (int index into children)
children: list[list[Item]] = field(default_factory=list)
def combine(edge: Edge, j: tuple[int, ...], lm: BigramScores, lm_weight: float) -> Item:
"""The item of grid point j of the edge."""
words: list[str] = []
score = edge.rule_score
lm_old = 0.0
for sym in edge.pattern:
if isinstance(sym, int):
s, w = edge.children[sym][j[sym]]
score += s
lm_old += lm.inside(w)
words.extend(w)
else:
words.append(sym)
out = tuple(words)
return score + lm_weight * (lm.inside(out) - lm_old), out
def cube_prune(edges: list[Edge], k: int, lm: BigramScores, lm_weight: float = 1.0) -> list[Item]:
"""Pop at most k grid points in the order of a heap, starting from the corner
of each edge; return the popped items sorted by score, best first."""
heap: list = [] # @line L1
buf: list[Item] = []
seen: set = set()
for e, edge in enumerate(edges): # @line L2
if any(len(c) == 0 for c in edge.children):
continue
j = tuple(0 for _ in edge.children)
score, words = combine(edge, j, lm, lm_weight)
heapq.heappush(heap, (-score, e, j, words))
seen.add((e, j))
while heap and len(buf) < k: # @line L3
neg, e, j, words = heapq.heappop(heap) # @line L4
buf.append((-neg, words)) # @line L5
edge = edges[e]
for i in range(len(j)): # @line L6
nj = j[:i] + (j[i] + 1,) + j[i + 1 :]
if nj[i] < len(edge.children[i]) and (e, nj) not in seen: # @line L7
seen.add((e, nj))
score, w = combine(edge, nj, lm, lm_weight)
heapq.heappush(heap, (-score, e, nj, w)) # @line L8
buf.sort(key=lambda it: -it[0]) # @line L9
return buf # @line L10
def pop_order(edges: list[Edge], k: int, lm: BigramScores, lm_weight: float = 1.0) -> list[tuple[int, tuple[int, ...], float]]:
"""The grid points in the order cube pruning pops them (for traces)."""
heap: list = []
seen: set = set()
out = []
for e, edge in enumerate(edges):
if any(len(c) == 0 for c in edge.children):
continue
j = tuple(0 for _ in edge.children)
heapq.heappush(heap, (-combine(edge, j, lm, lm_weight)[0], e, j))
seen.add((e, j))
while heap and len(out) < k:
neg, e, j = heapq.heappop(heap)
out.append((e, j, -neg))
for i in range(len(j)):
nj = j[:i] + (j[i] + 1,) + j[i + 1 :]
if nj[i] < len(edges[e].children[i]) and (e, nj) not in seen:
seen.add((e, nj))
heapq.heappush(heap, (-combine(edges[e], nj, lm, lm_weight)[0], e, nj))
return out
def exhaustive_k_best(edges: list[Edge], k: int, lm: BigramScores, lm_weight: float = 1.0) -> list[Item]:
"""Score every grid point of every edge and keep the k best."""
allitems = []
for edge in edges:
for j in itertools.product(*[range(len(c)) for c in edge.children]):
allitems.append(combine(edge, j, lm, lm_weight))
allitems.sort(key=lambda it: -it[0])
return allitems[:k]
test_cube_pruning.py 102 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cube-pruning/. The authors are listed in prov/6RZK3C.jsonl.
import math
import random
from cube_pruning import BigramScores, Edge, combine, cube_prune, exhaustive_k_best, pop_order
def example() -> tuple[list[Edge], BigramScores]:
subj = [(-1.0, ("he",)), (-1.2, ("they",)), (-1.5, ("she",))]
verb = [(-0.8, ("go",)), (-1.0, ("goes",)), (-1.6, ("went",))]
lm = BigramScores(
{
("he", "go"): -3.0, ("he", "goes"): -0.4, ("he", "went"): -0.6,
("they", "go"): -0.3, ("they", "goes"): -3.0, ("they", "went"): -0.6,
("she", "go"): -3.0, ("she", "goes"): -0.4, ("she", "went"): -0.6,
},
default=-5.0,
)
return [Edge(0.0, (0, 1), [subj, verb])], lm
def rounded(items: list) -> list:
return [(round(s, 9), w) for s, w in items]
def test_example() -> None:
edges, lm = example()
order = pop_order(edges, 4, lm)
assert [(j, round(s, 9)) for _, j, s in order] == [((0, 0), -4.8), ((1, 0), -2.3), ((0, 1), -2.4), ((0, 2), -3.2)]
got = rounded(cube_prune(edges, 3, lm))
assert got == [(-2.3, ("they", "go")), (-2.4, ("he", "goes")), (-4.8, ("he", "go"))]
want = rounded(exhaustive_k_best(edges, 3, lm))
assert want == [(-2.3, ("they", "go")), (-2.4, ("he", "goes")), (-2.9, ("she", "goes"))]
got4 = [s for s, _ in rounded(cube_prune(edges, 4, lm))]
assert got4 == [-2.3, -2.4, -3.2, -4.8]
# without the language model the grid is monotone and the result is exact
assert rounded(cube_prune(edges, 3, lm, lm_weight=0.0)) == [(-1.8, ("he", "go")), (-2.0, ("he", "goes")), (-2.0, ("they", "go"))]
def random_edges(rng: random.Random, vocab: list[str]) -> list[Edge]:
edges = []
for _ in range(rng.randint(1, 3)):
arity = rng.randint(0, 3)
children = []
for _ in range(arity):
items = [(-rng.uniform(0, 4), tuple(rng.choice(vocab) for _ in range(rng.randint(1, 2)))) for _ in range(rng.randint(1, 4))]
items.sort(key=lambda it: -it[0])
children.append(items)
pattern = list(range(arity))
rng.shuffle(pattern)
for _ in range(rng.randint(0, 2)):
pattern.insert(rng.randint(0, len(pattern)), rng.choice(vocab))
edges.append(Edge(-rng.uniform(0, 2), tuple(pattern), children))
return edges
def random_lm(rng: random.Random, vocab: list[str]) -> BigramScores:
return BigramScores({(a, b): -rng.uniform(0.1, 5.0) for a in vocab for b in vocab}, default=-5.0)
def test_exact_without_language_model() -> None:
rng = random.Random(2005)
vocab = ["p", "q", "r", "s"]
for _ in range(400):
edges, lm = random_edges(rng, vocab), random_lm(rng, vocab)
k = rng.randint(1, 12)
got = [round(s, 9) for s, _ in cube_prune(edges, k, lm, lm_weight=0.0)]
want = [round(s, 9) for s, _ in exhaustive_k_best(edges, k, lm, lm_weight=0.0)]
assert got == want
order = [s for _, _, s in pop_order(edges, k, lm, lm_weight=0.0)]
assert all(a >= b - 1e-12 for a, b in zip(order, order[1:]))
def test_with_language_model_is_a_heuristic() -> None:
rng = random.Random(2007)
vocab = ["p", "q", "r", "s"]
misses = 0
for _ in range(400):
edges, lm = random_edges(rng, vocab), random_lm(rng, vocab)
k = rng.randint(1, 6)
got = cube_prune(edges, k, lm)
want = exhaustive_k_best(edges, k, lm)
assert len(got) == len(want)
# every popped item is a real grid item with its true score
assert all(a[0] >= b[0] - 1e-12 for a, b in zip(got, got[1:]))
assert all(g[0] <= w[0] + 1e-12 for g, w in zip(got, want))
if got[0][0] < want[0][0] - 1e-12:
misses += 1
# with k at least the grid size, every point is popped
total = sum(math.prod(len(c) for c in e.children) for e in edges)
assert [round(s, 9) for s, _ in cube_prune(edges, total, lm)] == [round(s, 9) for s, _ in exhaustive_k_best(edges, total, lm)]
assert misses > 0
def test_combine_counts_only_new_bigrams() -> None:
lm = BigramScores({("a", "b"): -1.0, ("b", "c"): -2.0, ("c", "d"): -3.0}, default=-7.0)
edge = Edge(-0.5, (0, "c", 1), [[(-1.0, ("a", "b"))], [(-2.0, ("d",))]])
score, words = combine(edge, (0, 0), lm, 1.0)
assert words == ("a", "b", "c", "d")
assert math.isclose(score, -0.5 - 1.0 - 2.0 - 2.0 - 3.0)
History
Huang and Chiang (2005) gave lazy algorithms to find the best derivations of a hypergraph, by exploring for each hyperedge the grid of the children's sorted derivations from its corner. Chiang (2007) used the same exploration with a language model in the Hiero decoder and called it cube pruning, after the three-dimensional grid of a rule with two nonterminals and its translation options. Huang and Chiang (2007) described it for general hypergraphs, explained that the language model makes the scores non-monotone, and added cube growing. It became the standard search of hierarchical and syntax-based decoders such as Joshua, Moses and cdec.
References
- Chiang 2007, the decoder with a language model and the cube pruning method that it introduces
- Huang and Chiang 2007, cube pruning on a hypergraph, why the language model makes it approximate, and cube growing
- Huang and Chiang 2005, the lazy k-best algorithm on a hypergraph, exact for monotone combination functions
- Philipp Koehn, Statistical Machine Translation, Cambridge University Press, 2010, Chapter 11 (tree-based models: decoding with a language model, cube pruning)
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 6RZK3C Edit this page History Report an error Markdown