Algorithm Search⌘K

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.

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
Properties
deterministicofflineiterative
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 G=(N,Σ,R,S)G = (N, \Sigma, R, S) in Chomsky normal form, with a probability q(r)>0q(r) > 0 on each rule, and a sentence w=w1⋯wnw = w_1 \cdots w_n. The output is a parse tree of ww with root SS 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, +, −∞-\infty, 0), so the score of a tree is the sum of log⁡q\log q over its rules.

A chart item is e=[X,i,j]e = [X, i, j] over the fencepost span (i,j)(i, j), which covers the words wi+1,…,wjw_{i+1}, \ldots, w_j. Its inside score β(X,i,j)\beta(X, i, j) is the best score of a subtree with root XX over those words. Its outside score α(X,i,j)\alpha(X, i, j) 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 β(S,0,n)\beta(S, 0, n), and for every item β(e)+α(e)\beta(e) + \alpha(e) is the best score of a full parse that contains ee.

An estimate a(e)a(e) of α(e)\alpha(e) is admissible if a(e)≥α(e)a(e) \ge \alpha(e) for every item: in log space, it never underestimates. It is consistent, which Klein and Manning call monotonic, if for every rule Z→X YZ \to X\,Y and items e=[X,i,j]e = [X, i, j], f=[Y,j,k]f = [Y, j, k], g=[Z,i,k]g = [Z, i, k],

a(e)≥log⁡q(Z→X Y)+β(f)+a(g),a(e) \ge \log q(Z \to X\,Y) + \beta(f) + a(g),

and the mirror inequality holds for the right child. In words, building a larger item never raises the priority b+ab + a. These are the conditions of admissible heuristics and consistent heuristics in graph search, with the costs replaced by negated log probabilities.

The algorithm

b(e)b(e) is the best inside score found so far for item ee, initially −∞-\infty. The agenda holds copies of items with the priority b(e)+a(e)b(e) + a(e). An item is finished when it leaves the agenda for the first time.

  1. A-STAR-PARSE(G, q, w, a) ▷ a: a consistent estimate of the outside score
  2. 1for 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})
  3. 2while the agenda is not empty do
  4. 3pop a copy of an item e = [X, i, j] with the largest priority b + a(e)
  5. 4if e is finished then continue ▷ a stale copy
  6. 5mark e finished
  7. 6if e = [S, 0, n] then return b(e) and the tree from the back pointers of e
  8. 7for 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))
  9. 8for 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))
  10. 9return no parse
  11. RELAX(e, s, bp)
  12. 10if 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 a=0a = 0 (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 in(Y,k)\mathrm{in}(Y, k), the best inside score of YY over any kk words,

out(S,0,0)=0,out(X,l,r)=max⁡(max⁡Z→XY, kout(Z,l,r−k)+log⁡q+in(Y,k), max⁡Z→YX, kout(Z,l−k,r)+log⁡q+in(Y,k)),\mathrm{out}(S, 0, 0) = 0, \qquad \mathrm{out}(X, l, r) = \max\Big(\max_{Z \to X Y,\ k} \mathrm{out}(Z, l, r - k) + \log q + \mathrm{in}(Y, k),\ \max_{Z \to Y X,\ k} \mathrm{out}(Z, l - k, r) + \log q + \mathrm{in}(Y, k)\Big),

and a([X,i,j])=out(X,i,n−j)a([X, i, j]) = \mathrm{out}(X, i, n - j). 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 a(goal)=0a(\text{goal}) = 0, both are admissible.

Example

Take the grammar of Manning and Schütze from the probabilistic CKY page,

S→NP VP [1.0],PP→P NP [1.0],VP→V NP [0.7]∣VP PP [0.3],NP→NP PP [0.4],S \to NP\ VP\ [1.0], \quad PP \to P\ NP\ [1.0], \quad VP \to V\ NP\ [0.7] \mid VP\ PP\ [0.3], \quad NP \to NP\ PP\ [0.4],
P→with [1.0],V→saw [1.0],NP→astronomers [0.1]∣ears [0.18]∣saw [0.04]∣stars [0.18]∣telescopes [0.1],P \to \text{with}\ [1.0], \quad V \to \text{saw}\ [1.0], \quad NP \to \text{astronomers}\ [0.1] \mid \text{ears}\ [0.18] \mid \text{saw}\ [0.04] \mid \text{stars}\ [0.18] \mid \text{telescopes}\ [0.1],

and ww = astronomers saw stars with ears, with n=5n = 5. Exhaustive CKY builds 12 items with a nonzero score. The tables list the items in the order they are finished, with ebe^{b}, eae^{a} and the priority eb+ae^{b + a} shown as probabilities. The numbers come from the implementation, with ties broken first in, first out.

With the NULL estimate, a=0a = 0:

pop item ebe^b priority
1 [V,1,2][V, 1, 2] 1 1
2 [P,3,4][P, 3, 4] 1 1
3 [NP,2,3][NP, 2, 3] 0.18 0.18
4 [NP,4,5][NP, 4, 5] 0.18 0.18
5 [PP,3,5][PP, 3, 5] 0.18 0.18
6 [VP,1,3][VP, 1, 3] 0.126 0.126
7 [NP,0,1][NP, 0, 1] 0.1 0.1
8 [NP,1,2][NP, 1, 2] 0.04 0.04
9 [NP,2,5][NP, 2, 5] 0.01296 0.01296
10 [S,0,3][S, 0, 3] 0.0126 0.0126
11 [VP,1,5][VP, 1, 5] 0.009072 0.009072
12 [S,0,5][S, 0, 5] 0.0009072 0.0009072

Between pops 11 and 12 the parser pops the stale copy of [VP,1,5][VP, 1, 5] with the score 0.006804, from the reading VP→VP PPVP \to VP\ PP, 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 ebe^b eae^a priority
1 [V,1,2][V, 1, 2] 1 0.00163296 0.00163296
2 [NP,2,3][NP, 2, 3] 0.18 0.009072 0.00163296
3 [P,3,4][P, 3, 4] 1 0.00163296 0.00163296
4 [NP,4,5][NP, 4, 5] 0.18 0.009072 0.00163296
5 [PP,3,5][PP, 3, 5] 0.18 0.009072 0.00163296
6 [NP,2,5][NP, 2, 5] 0.01296 0.126 0.00163296
7 [VP,1,5][VP, 1, 5] 0.009072 0.18 0.00163296
8 [VP,1,3][VP, 1, 3] 0.126 0.00972 0.00122472
9 [NP,0,1][NP, 0, 1] 0.1 0.009072 0.0009072
10 [S,0,5][S, 0, 5] 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 VV over its second word. The items of the best tree share it until pop 7. The noun reading [NP,1,2][NP, 1, 2] of saw and the item [S,0,3][S, 0, 3] are never finished. [VP,1,5][VP, 1, 5] is finished at pop 7 by the reading VP→V NPVP \to V\ NP, so when [VP,1,3][VP, 1, 3] is finished at pop 8, its offer of 0.006804 to [VP,1,5][VP, 1, 5] 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 β(S,0,n)\beta(S, 0, n) of a parse of ww 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 ee is popped too early, with b(e)<β(e)b(e) < \beta(e). Take a best derivation of ee and its lowest node ff that is not finished. The children of ff are finished with exact scores, so ff already has b(f)=β(f)b(f) = \beta(f) and a copy in the agenda. Consistency, applied step by step from ff up to ee, gives β(f)+a(f)≥β(e)+a(e)>b(e)+a(e)\beta(f) + a(f) \ge \beta(e) + a(e) > b(e) + a(e), so that copy of ff 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 G=(N,Σ,R,S)G = (N, \Sigma, R, S) is in Chomsky normal form, and each rule rr has a probability q(r)>0q(r) > 0; rules with q=0q = 0 are dropped first. All scores are natural logs, combined in the Viterbi semiring (max, +). The input is w=w1⋯wnw = w_1 \cdots w_n with n≥1n \ge 1. An item [X,i,j][X, i, j] with 0≤i<j≤n0 \le i < j \le n stands for the fencepost span (i,j)(i, j), which covers the words wi+1,…,wjw_{i+1}, \ldots, w_j. The goal is [S,0,n][S, 0, n].

Definitions

A derivation of an item e=[X,i,j]e = [X, i, j] is a parse tree with root XX and yield wi+1⋯wjw_{i+1} \cdots w_j. Its score is the sum of log⁡q\log q over its rules. The inside score β(e)\beta(e) is the largest score of a derivation of ee, and −∞-\infty when there is none. The outside score α(e)\alpha(e) is the largest score of a tree with root SS and yield ww in which the subtree of ee is cut out and its own rules are not counted, and −∞-\infty when there is none.

Since all scores are finite sums, a derivation of largest score has optimal parts: if a derivation of ee uses the rule Z→X YZ \to X\,Y at its root over the items c1c_1 and c2c_2 and has score β(e)\beta(e), then its subtrees have the scores β(c1)\beta(c_1) and β(c2)\beta(c_2), or replacing a subtree by a better one would beat β(e)\beta(e). We call a derivation optimal when every subtree in it has the inside score of its item. Every item with β(e)>−∞\beta(e) > -\infty has an optimal derivation, by induction on the span length.

The estimate is a function aa from items to R∪{−∞}\mathbb{R} \cup \{-\infty\}. It is consistent when a(goal)a(\text{goal}) is finite and, for every rule Z→X YZ \to X\,Y and every three items e=[X,i,j]e = [X, i, j], f=[Y,j,k]f = [Y, j, k] and g=[Z,i,k]g = [Z, i, k],

a(e)≥log⁡q(Z→X Y)+β(f)+a(g)anda(f)≥log⁡q(Z→X Y)+β(e)+a(g).a(e) \ge \log q(Z \to X\,Y) + \beta(f) + a(g) \quad \text{and} \quad a(f) \ge \log q(Z \to X\,Y) + \beta(e) + a(g).

It is admissible when a(e)≥α(e)a(e) \ge \alpha(e) for every item. Consistency with a(goal)≥0a(\text{goal}) \ge 0 implies admissibility: apply the two inequalities along the path from ee to the root of a tree that gives α(e)\alpha(e).

The value b(e)b(e) is the stored score of ee, with b(e)=−∞b(e) = -\infty before the first update. An item is finished when line L5 has marked it. A copy of ee in the agenda has the priority b+a(e)b + a(e), where bb is the value of b(e)b(e) when that copy was pushed.

Lemma 1: stored scores are scores of derivations

At every moment, b(e)≤β(e)b(e) \le \beta(e) for every item, and if b(e)>−∞b(e) > -\infty then the back pointers of ee give a derivation of ee whose score, computed from the current values of bb at its children, is b(e)b(e).

Proof. Line L1 sets b([X,i,i+1])=log⁡q(X→wi+1)b([X, i, i + 1]) = \log q(X \to w_{i+1}), the score of a one-rule derivation. Line L7 or L8 offers log⁡q(Z→X Y)+b(c1)+b(c2)\log q(Z \to X\,Y) + b(c_1) + b(c_2) for two items with stored scores, and by induction this is the score of the derivation that puts Z→X YZ \to X\,Y over derivations of c1c_1 and c2c_2. So every stored value is the score of a derivation, and it is at most β(e)\beta(e). □\square

Lemma 2: a finished item has its inside score

When line L5 marks an item ee as finished, b(e)=β(e)b(e) = \beta(e).

Proof. Suppose not, and let ee be the first item finished with b(e)<β(e)b(e) < \beta(e). By Lemma 1 it is not more, and β(e)>−∞\beta(e) > -\infty. Every item finished before ee has its inside score, by the choice of ee. Fix an optimal derivation DD of ee.

Let ff be a lowest node of DD that is not finished at the moment ee is popped. Such a node exists, because ee itself is not finished yet. All children of ff in DD are finished, with their inside scores. If ff is a preterminal item [X,i,i+1][X, i, i + 1], line L1 has set b(f)=log⁡q(X→wi+1)=β(f)b(f) = \log q(X \to w_{i+1}) = \beta(f), since DD is optimal. Otherwise, ff has the children c1c_1 and c2c_2 in DD with the rule Z→X YZ \to X\,Y, and when the later of the two was finished, line L7 or L8 offered log⁡q(Z→X Y)+β(c1)+β(c2)=β(f)\log q(Z \to X\,Y) + \beta(c_1) + \beta(c_2) = \beta(f) to ff, which was not finished then. In both cases, line L10 has made b(f)=β(f)b(f) = \beta(f), the largest possible value by Lemma 1.

If f=ef = e, then b(e)=β(e)b(e) = \beta(e), a contradiction. So ff is a proper descendant of ee in DD. Walk up DD from ff to ee. For a node gg of DD with a child cc and the other child c′c', both in DD, consistency gives

β(c)+a(c)≥β(c)+log⁡q+β(c′)+a(g)=β(g)+a(g),\beta(c) + a(c) \ge \beta(c) + \log q + \beta(c') + a(g) = \beta(g) + a(g),

where the last step is the optimality of DD. Chaining these inequalities from ff to ee gives

β(f)+a(f)≥β(e)+a(e)>b(e)+a(e).\beta(f) + a(f) \ge \beta(e) + a(e) > b(e) + a(e).

The copy of ee just popped has the priority b(e)+a(e)b(e) + a(e), and a(e)>−∞a(e) > -\infty because line L10 pushes no copy with a=−∞a = -\infty. So the left side is above −∞-\infty, which means a(f)>−∞a(f) > -\infty, and line L10 pushed a copy of ff with the priority β(f)+a(f)\beta(f) + a(f) when it set b(f)=β(f)b(f) = \beta(f). That copy is still in the agenda, because popping it would have finished ff. The agenda pops a copy of largest priority, and this copy of ff has a strictly larger priority than the copy of ee. This contradicts the choice of the copy of ee at line L3. □\square

Theorem

Let the estimate be consistent. If ww has a parse, A-STAR-PARSE returns β(goal)\beta(\text{goal}), the largest log probability of a parse of ww, and a parse tree with that score. If ww 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 b(e)b(e) strictly increases, and b(e)b(e) 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 ww has no parse, β(goal)=−∞\beta(\text{goal}) = -\infty, and by Lemma 1 b(goal)b(\text{goal}) stays −∞-\infty, so line L10 never pushes the goal. Line L6 never fires, and the loop ends at line L9.

A parse exists. Then β(goal)>−∞\beta(\text{goal}) > -\infty. Fix an optimal derivation D∗D^* of the goal. All items of D∗D^* have a>−∞a > -\infty: a(goal)a(\text{goal}) is finite, and for a child cc of a node gg of D∗D^*, consistency gives a(c)≥log⁡q+β(c′)+a(g)>−∞a(c) \ge \log q + \beta(c') + a(g) > -\infty. Suppose the loop ended without popping the goal. Let ff be a lowest unfinished node of D∗D^*. As in the proof of Lemma 2, b(f)=β(f)b(f) = \beta(f) was set and a copy of ff was pushed, since a(f)>−∞a(f) > -\infty. That copy was never popped, because ff 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 b(goal)=β(goal)b(\text{goal}) = \beta(\text{goal}) by Lemma 2.

The tree. The back pointers of a finished item point to finished items, because lines L7 and L8 combine ee only with finished items, and a finished item never changes its bb or its back pointer again (line L10 tests that ee 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 b(goal)=β(goal)b(\text{goal}) = \beta(\text{goal}). ■\blacksquare

The estimates of the page are consistent

The null estimate a=0a = 0 is consistent because log⁡q+β(f)≤0\log q + \beta(f) \le 0 for probabilities.

For the SX estimate, let in(Y,k)\mathrm{in}(Y, k) be the largest inside score of YY over kk words when every word may be any terminal. Then in(Y,k)≥β([Y,j,j+k])\mathrm{in}(Y, k) \ge \beta([Y, j, j + k]) for every sentence, since the actual words are one choice. The estimate a([X,i,j])=out(X,i,n−j)a([X, i, j]) = \mathrm{out}(X, i, n - j) satisfies, by its defining recurrence, out(X,l,r)≥out(Z,l,r−k)+log⁡q(Z→X Y)+in(Y,k)\mathrm{out}(X, l, r) \ge \mathrm{out}(Z, l, r - k) + \log q(Z \to X\,Y) + \mathrm{in}(Y, k) for every rule Z→X YZ \to X\,Y and every kk with 1≤k≤r1 \le k \le r, and the mirror inequality for Z→Y XZ \to Y\,X. With e=[X,i,j]e = [X, i, j], f=[Y,j,j+k]f = [Y, j, j + k] and g=[Z,i,j+k]g = [Z, i, j + k] this reads a(e)≥a(g)+log⁡q+in(Y,k)≥a(g)+log⁡q+β(f)a(e) \ge a(g) + \log q + \mathrm{in}(Y, k) \ge a(g) + \log q + \beta(f), which is the first consistency inequality. The second is the mirror case. Finally a(goal)=out(S,0,0)=0a(\text{goal}) = \mathrm{out}(S, 0, 0) = 0. So the SX estimate is consistent, and hence admissible.

Complexity

Time. An offer at line L7 or L8 is made once for each rule Z→X YZ \to X\,Y and each pair of adjacent finished items [X,i,j][X, i, j] and [Y,j,k][Y, j, k], so there are at most O(n3g)O(n^3 g) offers. Each offer pushes at most one copy, so the agenda holds at most O(n3g+ng)O(n^3 g + n g) copies, and each push or pop costs O(log⁡(ng))O(\log(n g)) with a binary heap. Scanning the lists of finished neighbours costs O(nm)O(n m) per finished item, and there are at most n2mn^2 m of them, which adds O(n3m2)O(n^3 m^2). The worst case is therefore O(n3glog⁡(ng)+n3m2)O(n^3 g \log(n g) + n^3 m^2) 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 O(n3g)O(n^3 g) time and O(n2m)O(n^2 m) space, and they depend only on the sentence length, so they are computed once and reused.

Space. The chart has O(n2m)O(n^2 m) items and back pointers. With lazy deletion the agenda can hold O(n3g)O(n^3 g) copies in the worst case. A queue with a decrease-key operation keeps it at O(n2m)O(n^2 m).

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 a=0a = 0 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 [NP,2,5][NP, 2, 5] by a large amount, and the parser returns the reading VP→VP PPVP \to VP\ PP 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 nn words is a bound only for sentences of nn words. Looking up out(X,i,n−j)\mathrm{out}(X, i, n - j) with the wrong nn breaks admissibility.
  • Underflow. Products of probabilities underflow for long sentences. The page works in log space; the tests parse 12 words with lexical probability 10−3010^{-30}, where the plain product is 0.0 and the log score is exact.
  • Unary rules. The page assumes Chomsky normal form. With unary rules X→YX \to Y, the parser must also offer [X,i,j][X, i, j] from [Y,i,j][Y, i, j] next to lines L7 and L8, and the SX recurrence needs the same unary step. Since log⁡q≤0\log q \le 0, 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.

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

  1. 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
  2. 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)
  3. 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.

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