Algorithmadvanced
A* parsing
Also called A* PCFG parsing.
Agenda-based exact Viterbi parsing that pops chart items by inside score plus an admissible and monotonic estimate of the outside score.
- Solves
- Most probable parse
- Time
- O(n^3 g log(n g) + n^3 m^2) worst
- Space
- O(n^3 g) extra
- Where
- g = the number of rules of the grammar in Chomsky normal form; m = the number of nonterminals; n = the number of words
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Dan Klein, Christopher D. Manning, 2003
A* parsing finds the most probable parse of a sentence under a probabilistic context-free grammar, the same tree that probabilistic CKY finds, but it does not fill the whole chart. It keeps an agenda, a priority queue of chart items, and always takes next the item whose inside score plus an estimate of its outside score is largest. When the estimate never underestimates the true outside score and never lets the priority rise along a derivation, the first complete parse taken from the agenda is optimal, exactly as in A* search. Klein and Manning introduced it in 2003. Their estimates are precomputed from the grammar alone, and in their measurements the parser processed a small fraction of the items that exhaustive parsing builds. The worst case stays cubic in the sentence length, with an extra log factor for the queue.
In plain words
A chart parser builds small pieces of a parse, such as a noun phrase over two words, and combines them into larger pieces until one piece covers the whole sentence. Exhaustive parsing builds every piece. Many of them are useless, because no good parse of the whole sentence uses them.
A* parsing builds the pieces in order of promise. The promise of a piece is its own score times a guess of the best score that the rest of the sentence can add around it. The guess is computed in advance and is always optimistic. A piece with a high score in a hopeless context waits, and a piece that the best parse needs comes out early.
Because the guess is optimistic in the right way, the first full parse that comes out is the best one. A weak guess still gives the right answer, only more slowly.
The problem
The input is a grammar in Chomsky normal form, with a probability on each rule, and a sentence . The output is a parse tree of with root and the largest probability, or the answer that there is none. This is the problem of most probable parse, and the page works with natural logs in the Viterbi semiring (max, +, , 0), so the score of a tree is the sum of over its rules.
A chart item is over the fencepost span , which covers the words . Its inside score is the best score of a subtree with root over those words. Its outside score is the best score of the rest of a full parse around it, as on the inside-outside algorithm page, with max in place of sum. The best parse has the score , and for every item is the best score of a full parse that contains .
An estimate of is admissible if for every item: in log space, it never underestimates. It is consistent, which Klein and Manning call monotonic, if for every rule and items , , ,
and the mirror inequality holds for the right child. In words, building a larger item never raises the priority . These are the conditions of admissible heuristics and consistent heuristics in graph search, with the costs replaced by negated log probabilities.
The algorithm
is the best inside score found so far for item , initially . The agenda holds copies of items with the priority . An item is finished when it leaves the agenda for the first time.
A-STAR-PARSE(G, q, w, a) ▷ a: a consistent estimate of the outside score- 1
for i ← 0 to n-1 do for each rule X → w_{i+1} do RELAX([X, i, i+1], log q(X → w_{i+1}), w_{i+1}) - 2
while the agenda is not empty do - 3
pop a copy of an item e = [X, i, j] with the largest priority b + a(e) - 4
if e is finished then continue ▷ a stale copy - 5
mark e finished - 6
if e = [S, 0, n] then return b(e) and the tree from the back pointers of e - 7
for each finished [Y, j, k] and each rule Z → X Y do RELAX([Z, i, k], log q(Z → X Y) + b(e) + b([Y, j, k]), (j, X, Y)) - 8
for each finished [Y, h, i] and each rule Z → Y X do RELAX([Z, h, j], log q(Z → Y X) + b([Y, h, i]) + b(e), (i, Y, X)) - 9
return no parse RELAX(e, s, bp)- 10
if e is not finished and s > b(e) then b(e) ← s; back(e) ← bp; push a copy of e with priority s + a(e) unless a(e) = -∞
Lines L7 and L8 combine the item just finished with finished neighbours on its right and on its left. Each item is finished once, so each pair of adjacent finished items is combined once, when the later of the two is finished. Line L10 pushes a new copy when a score improves, instead of a decrease-key on the queue, and line L4 drops the copies that are out of date. The goal test is at line L6, when the goal is popped, not when it is first reached at line L10.
With (the NULL estimate) the priority is the inside score alone, and the parser is uniform cost search, the parsing form of Dijkstra's algorithm on the hypergraph of items. The implementation also provides the SX estimate of Klein and Manning. It summarizes the context of an item by its label and the number of words to its left and to its right, and takes the best outside score over all sentences with that context summary. With , the best inside score of over any words,
and . The tables depend only on the grammar and the sentence length, so they can be computed once for all sentences up to a maximum length. Both NULL and SX are consistent, and since , both are admissible.
Example
Take the grammar of Manning and Schütze from the probabilistic CKY page,
and = astronomers saw stars with ears, with . Exhaustive CKY builds 12 items with a nonzero score. The tables list the items in the order they are finished, with , and the priority shown as probabilities. The numbers come from the implementation, with ties broken first in, first out.
With the NULL estimate, :
| pop | item | priority | |
|---|---|---|---|
| 1 | 1 | 1 | |
| 2 | 1 | 1 | |
| 3 | 0.18 | 0.18 | |
| 4 | 0.18 | 0.18 | |
| 5 | 0.18 | 0.18 | |
| 6 | 0.126 | 0.126 | |
| 7 | 0.1 | 0.1 | |
| 8 | 0.04 | 0.04 | |
| 9 | 0.01296 | 0.01296 | |
| 10 | 0.0126 | 0.0126 | |
| 11 | 0.009072 | 0.009072 | |
| 12 | 0.0009072 | 0.0009072 |
Between pops 11 and 12 the parser pops the stale copy of with the score 0.006804, from the reading , and line L4 drops it. All 12 items are finished, because the goal has the smallest score of all.
With the SX estimate:
| pop | item | priority | ||
|---|---|---|---|---|
| 1 | 1 | 0.00163296 | 0.00163296 | |
| 2 | 0.18 | 0.009072 | 0.00163296 | |
| 3 | 1 | 0.00163296 | 0.00163296 | |
| 4 | 0.18 | 0.009072 | 0.00163296 | |
| 5 | 0.18 | 0.009072 | 0.00163296 | |
| 6 | 0.01296 | 0.126 | 0.00163296 | |
| 7 | 0.009072 | 0.18 | 0.00163296 | |
| 8 | 0.126 | 0.00972 | 0.00122472 | |
| 9 | 0.1 | 0.009072 | 0.0009072 | |
| 10 | 0.0009072 | 1 | 0.0009072 |
The value 0.00163296 is the SX bound for the best parse of any 5-word sentence that has a over its second word. The items of the best tree share it until pop 7. The noun reading of saw and the item are never finished. is finished at pop 7 by the reading , so when is finished at pop 8, its offer of 0.006804 to is ignored at line L10. The result in both runs is the tree in which with ears modifies stars, with probability 0.0009072.
Correctness
The claim is: with a consistent estimate, line L6 returns the largest log probability of a parse of and a tree with that score; if there is no parse, line L9 is reached; and the parser stops. This is a theorem.
The key step is that every item has its exact inside score when it is finished. Suppose an item is popped too early, with . Take a best derivation of and its lowest node that is not finished. The children of are finished with exact scores, so already has and a copy in the agenda. Consistency, applied step by step from up to , gives , so that copy of had a larger priority and would have been popped first. The goal is then popped with its exact score, and the back pointers of finished items never change. The argument is the hypergraph form of the proof on the A* optimality page. The full proof, with termination and the case without a parse, is in the correctness proof. It also proves that NULL and SX are consistent.
Admissibility alone is not enough for this version, which never reopens a finished item. An admissible but inconsistent estimate can finish an item with a score below its inside score.
Proof: With a consistent outside estimate, A* parsing returns a Viterbi parse, and it stopsfull
We use the pseudocode A-STAR-PARSE and RELAX of the page. The grammar is in Chomsky normal form, and each rule has a probability ; rules with are dropped first. All scores are natural logs, combined in the Viterbi semiring (max, +). The input is with . An item with stands for the fencepost span , which covers the words . The goal is .
Definitions
A derivation of an item is a parse tree with root and yield . Its score is the sum of over its rules. The inside score is the largest score of a derivation of , and when there is none. The outside score is the largest score of a tree with root and yield in which the subtree of is cut out and its own rules are not counted, and when there is none.
Since all scores are finite sums, a derivation of largest score has optimal parts: if a derivation of uses the rule at its root over the items and and has score , then its subtrees have the scores and , or replacing a subtree by a better one would beat . We call a derivation optimal when every subtree in it has the inside score of its item. Every item with has an optimal derivation, by induction on the span length.
The estimate is a function from items to . It is consistent when is finite and, for every rule and every three items , and ,
It is admissible when for every item. Consistency with implies admissibility: apply the two inequalities along the path from to the root of a tree that gives .
The value is the stored score of , with before the first update. An item is finished when line L5 has marked it. A copy of in the agenda has the priority , where is the value of when that copy was pushed.
Lemma 1: stored scores are scores of derivations
At every moment, for every item, and if then the back pointers of give a derivation of whose score, computed from the current values of at its children, is .
Proof. Line L1 sets , the score of a one-rule derivation. Line L7 or L8 offers for two items with stored scores, and by induction this is the score of the derivation that puts over derivations of and . So every stored value is the score of a derivation, and it is at most .
Lemma 2: a finished item has its inside score
When line L5 marks an item as finished, .
Proof. Suppose not, and let be the first item finished with . By Lemma 1 it is not more, and . Every item finished before has its inside score, by the choice of . Fix an optimal derivation of .
Let be a lowest node of that is not finished at the moment is popped. Such a node exists, because itself is not finished yet. All children of in are finished, with their inside scores. If is a preterminal item , line L1 has set , since is optimal. Otherwise, has the children and in with the rule , and when the later of the two was finished, line L7 or L8 offered to , which was not finished then. In both cases, line L10 has made , the largest possible value by Lemma 1.
If , then , a contradiction. So is a proper descendant of in . Walk up from to . For a node of with a child and the other child , both in , consistency gives
where the last step is the optimality of . Chaining these inequalities from to gives
The copy of just popped has the priority , and because line L10 pushes no copy with . So the left side is above , which means , and line L10 pushed a copy of with the priority when it set . That copy is still in the agenda, because popping it would have finished . The agenda pops a copy of largest priority, and this copy of has a strictly larger priority than the copy of . This contradicts the choice of the copy of at line L3.
Theorem
Let the estimate be consistent. If has a parse, A-STAR-PARSE returns , the largest log probability of a parse of , and a parse tree with that score. If has no parse, it returns "no parse". In both cases it stops.
Proof. Termination. There are finitely many items. An item is finished at most once, because line L4 skips copies of finished items. Line L10 pushes a copy only when strictly increases, and only takes the scores of the combinations offered at lines L1, L7 and L8. Each finished item makes finitely many offers at lines L7 and L8, once, when it is finished. So the number of pushes is finite, and every iteration of line L2 pops one copy, so the loop ends.
No parse. If has no parse, , and by Lemma 1 stays , so line L10 never pushes the goal. Line L6 never fires, and the loop ends at line L9.
A parse exists. Then . Fix an optimal derivation of the goal. All items of have : is finite, and for a child of a node of , consistency gives . Suppose the loop ended without popping the goal. Let be a lowest unfinished node of . As in the proof of Lemma 2, was set and a copy of was pushed, since . That copy was never popped, because is not finished, so the agenda was not empty at the end. This is a contradiction, so the goal is popped, and at that moment line L6 returns by Lemma 2.
The tree. The back pointers of a finished item point to finished items, because lines L7 and L8 combine only with finished items, and a finished item never changes its or its back pointer again (line L10 tests that is not finished). So the tree built from the back pointers of the goal is a derivation of the goal, and by Lemma 1 its score is .
The estimates of the page are consistent
The null estimate is consistent because for probabilities.
For the SX estimate, let be the largest inside score of over words when every word may be any terminal. Then for every sentence, since the actual words are one choice. The estimate satisfies, by its defining recurrence, for every rule and every with , and the mirror inequality for . With , and this reads , which is the first consistency inequality. The second is the mirror case. Finally . So the SX estimate is consistent, and hence admissible.
Complexity
Time. An offer at line L7 or L8 is made once for each rule and each pair of adjacent finished items and , so there are at most offers. Each offer pushes at most one copy, so the agenda holds at most copies, and each push or pop costs with a binary heap. Scanning the lists of finished neighbours costs per finished item, and there are at most of them, which adds . The worst case is therefore on the word RAM, plus the cost of the estimate. A* does not beat the cubic bound of CKY in the worst case. Its gain is in the number of items actually built, which depends on the grammar, the sentence and the estimate.
The estimate. The SX tables take time and space, and they depend only on the sentence length, so they are computed once and reused.
Space. The chart has items and back pointers. With lazy deletion the agenda can hold copies in the worst case. A queue with a decrease-key operation keeps it at .
Measurement. Klein and Manning report on Penn Treebank sentences that their most detailed context summary estimate cut the number of edges processed to under 3% of what exhaustive parsing processes, and that a cheaper estimate, precomputed in under a minute, cut it to under 5%.
Properties
- Exact. With a consistent estimate it returns a parse of maximum probability, the same score as probabilistic CKY. Ties between parses of equal score are broken by the order of the queue.
- Monotone pops. With a consistent estimate the priorities of the finished items never increase from one pop to the next.
- Estimate quality trades work for precomputation. NULL needs nothing and finishes every item whose inside score is above the score of the best parse. SX and richer summaries finish fewer items but need larger tables. The TRUE estimate, the exact outside score, finishes the fewest but costs a full parse to compute.
- Not online. The estimate depends on the sentence length, and the goal covers the whole sentence.
Variants and improvements
- Richer context summaries. Klein and Manning also give SXL, SXLR and TRUE, which keep more of the context of the span in the summary, up to the whole sentence for TRUE. More detail gives a tighter bound and fewer items, at the cost of larger tables.
- Estimates from a coarser grammar. Map the nonterminals to fewer classes and give each coarse rule the largest probability of the rules mapped to it. Every fine parse maps to a coarse one with at least its probability, so the exact outside scores of the coarse grammar are an admissible bound for the fine grammar. They are consistent too, since they are exact outside scores of a grammar that bounds every fine rule.
- Uniform cost and Knuth's algorithm. With the parser is an agenda version of Dijkstra's algorithm on the item hypergraph.
- Inexact best-first parsing. Using a figure of merit that is not an admissible bound, as earlier best-first parsers did, finds a good parse faster but loses the guarantee.
- Beam search. Keeping only the best items of each cell of the CKY chart, as in beam search, is also inexact, but has a fixed cost.
When to use it
Use A* parsing when the exact Viterbi parse is required and the grammar is large, so that exhaustive CKY is slow but most items are hopeless. A good estimate can be precomputed for the grammar, as SX can. For short sentences or small grammars, plain probabilistic CKY is simpler and vectorizes better, since its loops do not depend on the scores. When an approximate parse is good enough, beam or coarse-to-fine pruning is usually faster, and neural span-based parsers such as span-based neural constituency parsing use exhaustive CKY over learned scores instead.
Pitfalls
- Goal test at the push. Returning when the goal first gets a score at line L10 gives the first parse found, not the best one. Test at line L6, when the goal is popped.
- Inconsistent estimate. If the estimate underestimates the outside score of an item of the best tree, another parse can be popped first. The tests use an estimate that lowers the outside score of by a large amount, and the parser returns the reading with probability 0.0006804 instead of 0.0009072.
- Stale copies. Without the test of line L4, a finished item is processed again when an old copy is popped, and lines L7 and L8 make duplicate offers.
- Wrong sentence length. The SX table for words is a bound only for sentences of words. Looking up with the wrong breaks admissibility.
- Underflow. Products of probabilities underflow for long sentences. The page works in log space; the tests parse 12 words with lexical probability , where the plain product is 0.0 and the log score is exact.
- Unary rules. The page assumes Chomsky normal form. With unary rules , the parser must also offer from next to lines L7 and L8, and the SX recurrence needs the same unary step. Since , a unary cycle never improves a score in the Viterbi semiring, so the agenda handles it without a closure.
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/a-star-parsing/. The authors are listed in prov/MZTBB1.jsonl.
"""A* parsing: exact Viterbi parsing of a PCFG with an agenda ordered by b + a.
A grammar is a list of rules (A, rhs, q): A -> B C with B and C nonterminals, or
A -> w with w a terminal, and q > 0 the rule probability. A rule with q = 0 is
ignored. The scores are natural logs. A chart item is (X, i, j) over the
fencepost span (i, j), which covers the words w[i], ..., w[j - 1] (0-based), so
the words i + 1 to j in 1-based numbering.
b(e) is the best inside log score found so far for item e. An estimate a(X, i, j)
must return an upper bound on the best outside log score of the item (it is
admissible) and must not decrease b + a along a derivation (it is consistent).
null_estimate (a = 0) and sx_estimate have both properties. With such an
estimate, the first goal item popped has the Viterbi score.
A parse tree is (A, children), where each child is a tree or a word, as on the
probabilistic CKY page.
Cost: O(n^3 g log(n g)) time in the worst case for n words and g rules, plus
the estimate; space O(n^2 m) for the chart of m nonterminals and O(n^3 g) for
the agenda with lazy deletion.
"""
import heapq
from typing import Callable, Dict, List, Optional, Sequence, Tuple
from nlslog import NEG_INF, safe_log
Rule = Tuple[str, Tuple[str, ...], float]
Item = Tuple[str, int, int]
Estimate = Callable[[str, int, int], float]
def _index(rules: Sequence[Rule]):
"""Split the rules into lexical, by-left-child and by-right-child indexes."""
nts = {a for a, _, _ in rules}
lexical: Dict[str, List[Tuple[str, float]]] = {}
by_left: Dict[str, Dict[str, List[Tuple[str, float]]]] = {}
by_right: Dict[str, Dict[str, List[Tuple[str, float]]]] = {}
binary: List[Tuple[str, str, str, float]] = []
for a, rhs, q in rules:
if q < 0:
raise ValueError(f"negative probability for {a} -> {rhs}")
if q == 0:
continue
lq = safe_log(q)
if len(rhs) == 1 and rhs[0] not in nts:
lexical.setdefault(rhs[0], []).append((a, lq))
elif len(rhs) == 2 and rhs[0] in nts and rhs[1] in nts:
b, c = rhs
by_left.setdefault(b, {}).setdefault(c, []).append((a, lq))
by_right.setdefault(c, {}).setdefault(b, []).append((a, lq))
binary.append((a, b, c, lq))
else:
raise ValueError(f"not in Chomsky normal form: {a} -> {rhs}")
return nts, lexical, by_left, by_right, binary
def null_estimate(x: str, i: int, j: int) -> float:
"""The trivial estimate a = 0: admissible and consistent, A* becomes uniform cost search."""
return 0.0
def sx_estimate(rules: Sequence[Rule], start: str, n: int) -> Estimate:
"""Return the SX estimate for sentences of n words.
in_any(X, k) is the best inside log score of X over any k words, and
out_sx(X, l, r) the best outside log score of X with l words to its left
and r to its right, the words inside the context being free. Both are
computed bottom up in O(n^3 g) time. The estimate is admissible and
consistent for every sentence of n words.
"""
nts, lexical, _, _, binary = _index(rules)
best_lex: Dict[str, float] = {}
for _, entries in lexical.items():
for a, lq in entries:
if lq > best_lex.get(a, NEG_INF):
best_lex[a] = lq
in_any: Dict[Tuple[str, int], float] = {}
for x in nts:
in_any[(x, 1)] = best_lex.get(x, NEG_INF)
for k in range(2, n + 1):
for x in nts:
in_any[(x, k)] = NEG_INF
for a, b, c, lq in binary:
for m in range(1, k):
s = lq + in_any[(b, m)] + in_any[(c, k - m)]
if s > in_any[(a, k)]:
in_any[(a, k)] = s
out: Dict[Tuple[str, int, int], float] = {}
for x in nts:
out[(x, 0, 0)] = 0.0 if x == start else NEG_INF
for t in range(1, n): # t = l + r words outside the span
for l in range(t + 1):
r = t - l
for x in nts:
out[(x, l, r)] = NEG_INF
for a, b, c, lq in binary:
# parent a -> b c, the item is b, the sibling c on the right takes k words
for k in range(1, r + 1):
s = out[(a, l, r - k)] + lq + in_any[(c, k)]
if s > out[(b, l, r)]:
out[(b, l, r)] = s
# the item is c, the sibling b on the left takes k words
for k in range(1, l + 1):
s = out[(a, l - k, r)] + lq + in_any[(b, k)]
if s > out[(c, l, r)]:
out[(c, l, r)] = s
def estimate(x: str, i: int, j: int) -> float:
return out.get((x, i, n - j), NEG_INF)
return estimate
def a_star_parse(rules: Sequence[Rule], start: str, w: Sequence[str],
estimate: Optional[Estimate] = None):
"""Return (best log score, a best tree, number of items finished).
The best log score is NEG_INF and the tree None when w has no parse. The
estimate defaults to null_estimate. Ties in b + a are broken first in,
first out, so the result is deterministic.
"""
if estimate is None:
estimate = null_estimate
_, lexical, by_left, by_right, _ = _index(rules)
n = len(w)
if n == 0:
return NEG_INF, None, 0
b: Dict[Item, float] = {}
back: Dict[Item, object] = {}
finished = set()
starts: List[List[Tuple[str, int]]] = [[] for _ in range(n + 1)] # finished items by left end
ends: List[List[Tuple[str, int]]] = [[] for _ in range(n + 1)] # finished items by right end
agenda: List[Tuple[float, int, str, int, int]] = []
counter = 0
def relax(e: Item, s: float, bp: object) -> None:
nonlocal counter
if e in finished or s <= b.get(e, NEG_INF): # @line L10
return
a = estimate(*e)
b[e] = s
back[e] = bp
if a == NEG_INF:
return # the item is in no complete parse
heapq.heappush(agenda, (-(s + a), counter, e[0], e[1], e[2]))
counter += 1
for i in range(n): # @line L1
for x, lq in lexical.get(w[i], ()):
relax((x, i, i + 1), lq, w[i])
pops = 0
while agenda: # @line L2
_, _, x, i, j = heapq.heappop(agenda) # @line L3
e = (x, i, j)
if e in finished: # @line L4
continue
finished.add(e) # @line L5
pops += 1
starts[i].append((x, j))
ends[j].append((x, i))
be = b[e]
if e == (start, 0, n): # @line L6
return be, _tree(back, e), pops
right = by_left.get(x, {})
for y, k in starts[j]: # @line L7
for z, lq in right.get(y, ()):
relax((z, i, k), lq + be + b[(y, j, k)], (j, x, y))
left = by_right.get(x, {})
for y, h in ends[i]: # @line L8
for z, lq in left.get(y, ()):
relax((z, h, j), lq + b[(y, h, i)] + be, (i, y, x))
return NEG_INF, None, pops # @line L9
def _tree(back: Dict[Item, object], goal: Item):
"""Build the tree of goal from the back pointers, with an explicit stack."""
done: Dict[Item, object] = {}
stack = [(goal, False)]
while stack:
e, expanded = stack.pop()
bp = back[e]
if isinstance(bp, str):
done[e] = (e[0], (bp,))
continue
k, y, z = bp
left, right = (y, e[1], k), (z, k, e[2])
if expanded:
done[e] = (e[0], (done[left], done[right]))
else:
stack.append((e, True))
stack.append((right, False))
stack.append((left, False))
return done[goal]
def tree_log_score(rules: Sequence[Rule], t) -> float:
"""Return the log probability of a tree: the sum of the log rule probabilities."""
q: Dict[Tuple[str, Tuple[str, ...]], float] = {}
for a, rhs, p in rules:
q[(a, tuple(rhs))] = q.get((a, tuple(rhs)), 0) + p
total = 0.0
stack = [t]
while stack:
a, kids = stack.pop()
rhs = tuple(k if isinstance(k, str) else k[0] for k in kids)
total += safe_log(q.get((a, rhs), 0))
stack.extend(k for k in kids if not isinstance(k, str))
return total
nlslog.py 152 lines
# SPDX-License-Identifier: MIT
# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Log-space arithmetic and semirings for the natural-language-and-speech pages.
Every log is the natural log. A probability of 0 is NEG_INF (float("-inf")),
never a large negative number. A cost is -log p, so a probability of 0 is a
cost of POS_INF.
The semirings are (K, plus, times, zero, one) as on the weighted-automaton page:
PROB probabilities plus = + times = * zero = 0 one = 1
LOG log probabilities plus = log_add times = + zero = -inf one = 0
VITERBI log probabilities plus = max times = + zero = -inf one = 0
TROPICAL costs -log p plus = min times = + zero = +inf one = 0
LOG_COST costs -log p plus = -log_add(-a, -b), times = +, zero = +inf, one = 0
BOOLEAN truth values plus = or times = and zero = False one = True
COUNTING path counts plus = + times = * zero = 0 one = 1
This module holds no algorithm of any page: no forward, Viterbi, CKY, Eisner,
CTC or DTW recursion. The pages build their dynamic programs on top of it.
"""
import math
from dataclasses import dataclass
from typing import Any, Callable, Iterable, List, Sequence
NEG_INF = float("-inf")
POS_INF = float("inf")
def safe_log(p) -> float:
"""Return log p, and NEG_INF for p = 0. Raise ValueError for p < 0."""
if p < 0:
raise ValueError("log of a negative number")
if p == 0:
return NEG_INF
return math.log(p)
def log_add(a: float, b: float) -> float:
"""Return log(exp(a) + exp(b)) = max(a, b) + log(1 + exp(-|a - b|)).
log_add(NEG_INF, NEG_INF) is NEG_INF. No exp of a large number is taken.
"""
if a < b:
a, b = b, a
if b == NEG_INF or a == POS_INF:
return a
return a + math.log1p(math.exp(b - a))
def log_sum(xs: Iterable[float]) -> float:
"""Return log(sum of exp(x)) over xs. An empty input gives NEG_INF."""
xs = list(xs)
if not xs:
return NEG_INF
m = max(xs)
if m == NEG_INF or m == POS_INF:
return m
return m + math.log(math.fsum(math.exp(x - m) for x in xs))
def log_normalize(xs: Sequence[float]) -> List[float]:
"""Return the list x - log_sum(xs): log values whose exps sum to 1.
Raise ValueError if every value is NEG_INF (nothing to normalize).
"""
z = log_sum(xs)
if z == NEG_INF:
raise ValueError("every weight is zero")
return [x - z for x in xs]
def log_softmax(xs: Sequence[float]) -> List[float]:
"""Return log softmax(xs): the logits xs turned into log probabilities."""
return log_normalize(xs)
def softmax(xs: Sequence[float], temperature: float = 1.0) -> List[float]:
"""Return the probabilities exp(x / temperature) / sum, computed stably.
The temperature must be positive. Logits of NEG_INF get probability 0.
"""
if not temperature > 0:
raise ValueError("the temperature must be positive")
m = max(xs)
if m == NEG_INF:
raise ValueError("every logit is -inf")
es = [math.exp((x - m) / temperature) for x in xs]
s = math.fsum(es)
return [e / s for e in es]
def argmax(xs: Sequence[Any]) -> int:
"""Return the first index of a largest value. Raise ValueError if xs is empty."""
if len(xs) == 0:
raise ValueError("argmax of an empty sequence")
best = 0
for i in range(1, len(xs)):
if xs[i] > xs[best]:
best = i
return best
@dataclass(frozen=True)
class Semiring:
"""A semiring (K, plus, times, zero, one). idempotent is True when a plus a = a."""
name: str
plus: Callable[[Any, Any], Any]
times: Callable[[Any, Any], Any]
zero: Any
one: Any
idempotent: bool
def _add(a, b):
return a + b
def _mul(a, b):
return a * b
def _log_add_cost(a: float, b: float) -> float:
return -log_add(-a, -b)
PROB = Semiring("probability", _add, _mul, 0, 1, False)
LOG = Semiring("log", log_add, _add, NEG_INF, 0.0, False)
VITERBI = Semiring("viterbi", max, _add, NEG_INF, 0.0, True)
TROPICAL = Semiring("tropical", min, _add, POS_INF, 0.0, True)
LOG_COST = Semiring("log-cost", _log_add_cost, _add, POS_INF, 0.0, False)
BOOLEAN = Semiring("boolean", lambda a, b: a or b, lambda a, b: a and b, False, True, True)
COUNTING = Semiring("counting", _add, _mul, 0, 1, False)
def sr_sum(sr: Semiring, xs: Iterable[Any]) -> Any:
"""Return the semiring sum of xs, and sr.zero for an empty input."""
acc = sr.zero
for x in xs:
acc = sr.plus(acc, x)
return acc
def sr_prod(sr: Semiring, xs: Iterable[Any]) -> Any:
"""Return the semiring product of xs, and sr.one for an empty input."""
acc = sr.one
for x in xs:
acc = sr.times(acc, x)
return acc
test_a_star_parsing.py 244 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/a-star-parsing/. The authors are listed in prov/MZTBB1.jsonl.
import math
import random
from a_star_parsing import a_star_parse, null_estimate, sx_estimate, tree_log_score
from nlslog import NEG_INF
MS = [
("S", ("NP", "VP"), 1.0),
("PP", ("P", "NP"), 1.0),
("VP", ("V", "NP"), 0.7),
("VP", ("VP", "PP"), 0.3),
("NP", ("NP", "PP"), 0.4),
("P", ("with",), 1.0),
("V", ("saw",), 1.0),
("NP", ("astronomers",), 0.1),
("NP", ("ears",), 0.18),
("NP", ("saw",), 0.04),
("NP", ("stars",), 0.18),
("NP", ("telescopes",), 0.1),
]
SENT = "astronomers saw stars with ears".split()
def leaves(t):
out, stack = [], [t]
while stack:
u = stack.pop()
if isinstance(u, str):
out.append(u)
else:
stack.extend(reversed(u[1]))
return out
def binary_trees(i, j):
"""All binary bracketings of the span (i, j), as nested pairs; a leaf is its index."""
if j - i == 1:
return [i]
out = []
for k in range(i + 1, j):
for left in binary_trees(i, k):
for right in binary_trees(k, j):
out.append((left, right))
return out
def brute_force(rules, start, w):
"""The best log score over all binary trees of w: enumerate every bracketing
and find its best labeling by a max over the labels at each node."""
lex, binr = {}, []
for a, rhs, q in rules:
if q <= 0:
continue
if len(rhs) == 1:
lex.setdefault(rhs[0], []).append((a, math.log(q)))
else:
binr.append((a, rhs[0], rhs[1], math.log(q)))
def label(shape):
if isinstance(shape, int):
d = {}
for a, lq in lex.get(w[shape], ()):
d[a] = max(d.get(a, NEG_INF), lq)
return d
left, right = label(shape[0]), label(shape[1])
d = {}
for a, b, c, lq in binr:
if b in left and c in right:
d[a] = max(d.get(a, NEG_INF), lq + left[b] + right[c])
return d
best, count = NEG_INF, 0
for shape in binary_trees(0, len(w)):
count += 1
best = max(best, label(shape).get(start, NEG_INF))
return best, count
def cky(rules, start, w):
"""Exhaustive Viterbi CKY over fencepost spans, in log space."""
n = len(w)
lex, binr = {}, []
for a, rhs, q in rules:
if q <= 0:
continue
if len(rhs) == 1:
lex.setdefault(rhs[0], []).append((a, math.log(q)))
else:
binr.append((a, rhs[0], rhs[1], math.log(q)))
ch = {}
for i in range(n):
for a, lq in lex.get(w[i], ()):
ch[(a, i, i + 1)] = max(ch.get((a, i, i + 1), NEG_INF), lq)
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length
for k in range(i + 1, j):
for a, b, c, lq in binr:
if (b, i, k) in ch and (c, k, j) in ch:
s = lq + ch[(b, i, k)] + ch[(c, k, j)]
if s > ch.get((a, i, j), NEG_INF):
ch[(a, i, j)] = s
return ch.get((start, 0, n), NEG_INF), ch
def test_example() -> None:
s, t, pops_null = a_star_parse(MS, "S", SENT)
assert math.isclose(s, math.log(0.0009072), rel_tol=1e-12)
pp = ("PP", (("P", ("with",)), ("NP", ("ears",))))
obj = ("NP", (("NP", ("stars",)), pp))
vp = ("VP", (("V", ("saw",)), obj))
assert t == ("S", (("NP", ("astronomers",)), vp))
s2, t2, pops_sx = a_star_parse(MS, "S", SENT, sx_estimate(MS, "S", len(SENT)))
assert t2 == t and math.isclose(s2, s, rel_tol=1e-12)
assert pops_sx < pops_null
assert (pops_null, pops_sx) == (12, 10)
def test_inadmissible_estimate_fails() -> None:
# An estimate that underestimates the outside score of (NP, 2, 5) is not
# admissible. The parser then pops the goal by the other reading first.
def bad(x, i, j):
return -100.0 if (x, i, j) == ("NP", 2, 5) else 0.0
s, t, _ = a_star_parse(MS, "S", SENT, bad)
assert math.isclose(s, math.log(0.0006804), rel_tol=1e-12)
assert t[1][1][1][0][0] == "VP" # VP -> VP PP: the PP attaches to the verb
def test_no_parse_and_edges() -> None:
assert a_star_parse(MS, "S", [])[:2] == (NEG_INF, None)
assert a_star_parse(MS, "S", ["stars", "with"])[:2] == (NEG_INF, None)
assert a_star_parse(MS, "S", ["unknown"])[:2] == (NEG_INF, None)
s, t, _ = a_star_parse(MS, "NP", ["stars"])
assert math.isclose(s, math.log(0.18)) and t == ("NP", ("stars",))
for bad in ([("S", ("A", "B", "C"), 1.0), ("A", ("a",), 1.0)],
[("S", ("x",), -0.5)]):
try:
a_star_parse(bad, "S", ["a"])
except ValueError:
continue
raise AssertionError("bad grammar accepted")
def test_catalan_counts() -> None:
# The grammar X -> X X, X -> a has one tree per binary bracketing.
g = [("X", ("X", "X"), 0.5), ("X", ("a",), 0.5)]
counts = [brute_force(g, "X", ["a"] * n)[1] for n in range(1, 8)]
assert counts == [1, 1, 2, 5, 14, 42, 132]
for n in range(1, 8):
s, t, _ = a_star_parse(g, "X", ["a"] * n, sx_estimate(g, "X", n))
assert math.isclose(s, (2 * n - 1) * math.log(0.5), rel_tol=1e-12)
assert leaves(t) == ["a"] * n
def random_grammar(rng):
nts = ["S", "A", "B"][: rng.randint(1, 3)]
terms = ["x", "y", "z"]
rules = []
for a in nts:
for b in nts:
for c in nts:
if rng.random() < 0.6:
rules.append((a, (b, c), rng.choice([0.1, 0.2, 0.3, 0.5, 0.9])))
for t in terms:
if rng.random() < 0.6:
rules.append((a, (t,), rng.choice([0.05, 0.2, 0.4, 0.7])))
return rules, terms
def test_random_against_brute_force_and_cky() -> None:
rng = random.Random(2003)
for trial in range(600):
rules, terms = random_grammar(rng)
n = rng.randint(1, 7 if trial % 10 == 0 else 5)
w = [rng.choice(terms) for _ in range(n)]
ref, ch = cky(rules, "S", w)
if n <= 5 or trial % 30 == 0:
bf, _ = brute_force(rules, "S", w)
assert bf == ref or math.isclose(bf, ref, rel_tol=1e-12)
s0, t0, p0 = a_star_parse(rules, "S", w)
s1, t1, p1 = a_star_parse(rules, "S", w, sx_estimate(rules, "S", n))
for s, t in ((s0, t0), (s1, t1)):
if ref == NEG_INF:
assert s == NEG_INF and t is None
else:
assert math.isclose(s, ref, rel_tol=1e-9, abs_tol=1e-12)
assert leaves(t) == w and t[0] == "S"
assert math.isclose(tree_log_score(rules, t), ref, rel_tol=1e-9, abs_tol=1e-12)
def test_sx_is_admissible() -> None:
# The SX estimate is at least the true Viterbi outside score of every item.
rng = random.Random(11)
for _ in range(150):
rules, terms = random_grammar(rng)
n = rng.randint(1, 5)
w = [rng.choice(terms) for _ in range(n)]
_, inside = cky(rules, "S", w)
est = sx_estimate(rules, "S", n)
# Viterbi outside scores, top down
out = {("S", 0, n): 0.0}
binr = [(a, r[0], r[1], math.log(q)) for a, r, q in rules if len(r) == 2]
for length in range(n, 1, -1):
for i in range(n - length + 1):
j = i + length
for a, b, c, lq in binr:
if (a, i, j) not in out:
continue
for k in range(i + 1, j):
if (b, i, k) in inside and (c, k, j) in inside:
sb = out[(a, i, j)] + lq + inside[(c, k, j)]
sc = out[(a, i, j)] + lq + inside[(b, i, k)]
out[(b, i, k)] = max(out.get((b, i, k), NEG_INF), sb)
out[(c, k, j)] = max(out.get((c, k, j), NEG_INF), sc)
for (x, i, j), o in out.items():
assert est(x, i, j) >= o - 1e-9
assert null_estimate("S", 0, n) == 0.0
def test_log_space_underflow() -> None:
# 12 words with lexical probability 1e-30: the plain product underflows.
n = 12
g = [("X", ("X", "X"), 1.0), ("X", ("a",), 1e-30)]
plain = 1.0
for _ in range(n):
plain *= 1e-30
assert plain == 0.0
s, t, _ = a_star_parse(g, "X", ["a"] * n, sx_estimate(g, "X", n))
assert math.isclose(s, n * math.log(1e-30), rel_tol=1e-12)
assert leaves(t) == ["a"] * n
def test_long_input_iterative() -> None:
# A right-branching grammar on 300 words: the tree is built without recursion.
n = 300
g = [("X", ("A", "X"), 0.9), ("X", ("b",), 1.0), ("A", ("a",), 1.0)]
w = ["a"] * (n - 1) + ["b"]
s, t, pops = a_star_parse(g, "X", w)
assert math.isclose(s, (n - 1) * math.log(0.9), rel_tol=1e-12)
assert leaves(t) == w
History
Agenda-based chart parsing was standard in the 1980s, and best-first parsers of the 1990s ordered the agenda by figures of merit that sped up parsing but gave up exactness. Klein and Manning (2003) showed that an agenda ordered by inside score plus an admissible and monotonic outside estimate keeps the Viterbi parse exact while it processes far fewer items. They built on their earlier description of parsing as search on a hypergraph and gave a family of estimates, from NULL to TRUE, precomputed from the grammar by context summaries such as SX. Later work used A* with estimates from coarser grammars and for k-best parsing.
References
- Dan Klein and Christopher D. Manning, A* Parsing, Fast Exact Viterbi Parse Selection, the agenda parser, the admissible and monotonic conditions on the estimate, the context summary estimates NULL, SX, SXL, SXLR and TRUE, and the measurements of edges processed
- Christopher D. Manning and Hinrich Schütze, Foundations of Statistical Natural Language Processing, MIT Press, 1999, Chapter 11, Probabilistic Context Free Grammars (the grammar of the example)
- Daniel Jurafsky and James H. Martin, Speech and Language Processing, third edition draft, Appendix E, Statistical Constituency Parsing
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 MZTBB1 Edit this page History Report an error Markdown