Algorithm Search⌘K

Algorithmresearch

Span-based neural constituency parsing

Also called chart-based neural parser.

A neural network scores each labeled span of the sentence, and a CKY-style dynamic program over spans finds the binary tree with the largest total score.

Time
Θ(n^3 + n^2 L) worst · best
Space
Θ(n^2) extra
Where
L = the number of labels including the empty label; n = the number of words
Properties
deterministicofflineiterative
Origin
Mitchell Stern, Jacob Andreas, Dan Klein, 2017

A span-based constituency parser splits constituency parsing into two parts. A neural network reads the sentence and gives a score to every pair of a span and a label. A chart decoder then finds the binary tree whose spans have the largest total score. The decoder is a CKY-style dynamic program like probabilistic CKY, but it has no grammar: any label can go on any span, and the tree score is a plain sum over spans. Stern, Andreas and Klein introduced this minimal form in 2017. The decoder is exact for this score and runs in cubic time. With a better encoder, the self-attentive encoder of Kitaev and Klein, the same kind of decoder reached 95.13 F1 on the Penn Treebank. This page is about the decoder and its training loss. The code takes the network outputs as given.

In plain words

A parse tree of a sentence is a set of nested pieces, each piece a run of words with a name such as noun phrase or verb phrase. The parser first lets a neural network look at the whole sentence and give a number to every possible piece and every possible name. A high number means the network thinks that piece with that name belongs in the tree.

The parser then looks for the set of nested pieces with the largest sum of numbers. It does this from short pieces to long ones. For each piece it remembers the best way to cut it in two, so a long piece reuses the answers for its parts.

Some pieces get a special empty name. They exist only to keep the tree binary, and the parser removes them at the end. What remains is the final tree.

The problem

The input is a sentence of n≥1n \ge 1 words and a label set {0,1,…,L−1}\{0, 1, \ldots, L - 1\}, where label 0 is the empty label ∅\varnothing. For every fencepost span (i,j)(i, j) with 0≤i<j≤n0 \le i < j \le n, which covers the words i+1i + 1 to jj, the network gives a label score slabel(i,j,ℓ)s_{\text{label}}(i, j, \ell) for every label and a span score sspan(i,j)s_{\text{span}}(i, j). All scores are arbitrary reals.

A binary tree over the sentence is a set of 2n−12n - 1 spans: the root span (0,n)(0, n), the nn spans of one word, and for every span of more than one word a split kk with i<k<ji < k < j such that (i,k)(i, k) and (k,j)(k, j) are also in the set. Each span gets one label. The score of a labeled tree TT is

s(T)=∑(i,j,ℓ)∈T[slabel(i,j,ℓ)+sspan(i,j)].s(T) = \sum_{(i, j, \ell) \in T} \big[ s_{\text{label}}(i, j, \ell) + s_{\text{span}}(i, j) \big].

The task is to find a labeled binary tree of largest score. There are 1, 1, 2, 5, 14, 42, 132 binary trees over 1 to 7 words, the Catalan numbers, so trying them all is exponential.

The binary tree is a coding of an ordinary treebank tree. Stern et al. binarize the gold tree and give the new spans the label ∅\varnothing, and they turn a chain of unary nodes into one atomic label, such as S+VP. Words are not part of the label set: part-of-speech tags are not predicted. After decoding, the spans labeled ∅\varnothing are deleted, so the result can be n-ary, and the root can have more than one child.

In Stern et al. the span score enters through the two children at each split, so the root span has no span score. The code adds sspans_{\text{span}} for every span of the tree, root included. Every tree contains the root span, so the two scores differ by the constant sspan(0,n)s_{\text{span}}(0, n), and they have the same best tree.

The algorithm

  1. CHART-PARSE(n, s_label, s_span)
  2. 1for len ← 1 to n do
  3. 2for i ← 0 to n - len do
  4. 3j ← i + len
  5. 4lab ← a label ℓ of largest s_label(i, j, ℓ); v ← s_label(i, j, lab) + s_span(i, j)
  6. 5if len = 1 then best(i, j) ← v
  7. 6else split(i, j) ← the first k with i < k < j of largest best(i, k) + best(k, j)
  8. 7best(i, j) ← v + best(i, split(i, j)) + best(split(i, j), j)
  9. 8label(i, j) ← lab
  10. 9walk from (0, n): output (i, j, label(i, j)), and if j - i > 1 walk (i, split(i, j)) and (split(i, j), j)
  11. 10return best(0, n) and the 2n - 1 labeled spans of the walk

The label of a span does not depend on what is inside the span, and the split does not depend on the label. So line L4 picks the label once per span, in O(L)O(L) time, and line L6 picks the split once per span, in O(n)O(n) time. This is the main difference from probabilistic CKY, where the best split depends on the labels of the two children through the grammar rules.

The walk of line L9 uses an explicit stack, so a long sentence does not hit a recursion limit.

Training. Stern et al. train the network with a margin loss. For the binarized gold tree T∗T^*, the Hamming loss Δ(T,T∗)\Delta(T, T^*) counts the spans of TT whose label differs from the gold label, where a span that is not in T∗T^* has the gold label ∅\varnothing. The hinge loss is

max⁡(0, max⁡T[s(T)+Δ(T,T∗)]−s(T∗)).\max\Big(0,\ \max_T \big[s(T) + \Delta(T, T^*)\big] - s(T^*)\Big).

The inner maximum is computed by CHART-PARSE itself, after 1 is added to every label score slabel(i,j,ℓ)s_{\text{label}}(i, j, \ell) with ℓ\ell different from the gold label of (i,j)(i, j). The loss is a hinge loss for structured prediction, and its gradient flows into the network through the scores of the two trees.

Example

Take the sentence She enjoys playing tennis, with n=4n = 4 and the labels ∅\varnothing, S, NP, VP. The scores below are made up for the example; in a real parser they come from the network.

span words ∅\varnothing S NP VP sspans_{\text{span}}
(0,1)(0, 1) She 0 -2 2 -1 0
(1,2)(1, 2) enjoys 1 -2 -1 0 0
(2,3)(2, 3) playing 1 -1 -1 0 0
(3,4)(3, 4) tennis 0 -2 2 -1 0
(0,2)(0, 2) She enjoys 0 -1 -1 -1 0.8
(1,3)(1, 3) enjoys playing 0.5 -2 -2 0 0.5
(2,4)(2, 4) playing tennis 0 -1 0 1.5 0
(0,3)(0, 3) She enjoys playing 0 -1 -2 -2 0
(1,4)(1, 4) enjoys playing tennis 0 -1 -2 2 1
(0,4)(0, 4) the whole sentence -1 3 -1 0 0

The chart, in the order of lines L1 to L8. The column vv is the value of line L4, and the split column lists best(i,k)+best(k,j)\mathrm{best}(i, k) + \mathrm{best}(k, j) for each kk.

span label vv splits split best
(0,1)(0, 1) NP 2 2
(1,2)(1, 2) ∅\varnothing 1 1
(2,3)(2, 3) ∅\varnothing 1 1
(3,4)(3, 4) NP 2 2
(0,2)(0, 2) ∅\varnothing 0.8 k=1k = 1: 3 1 3.8
(1,3)(1, 3) ∅\varnothing 1 k=2k = 2: 2 2 3
(2,4)(2, 4) VP 1.5 k=3k = 3: 3 3 4.5
(0,3)(0, 3) ∅\varnothing 0 k=1k = 1: 5, k=2k = 2: 4.8 1 5
(1,4)(1, 4) VP 3 k=2k = 2: 5.5, k=3k = 3: 5 2 8.5
(0,4)(0, 4) S 3 k=1k = 1: 10.5, k=2k = 2: 8.3, k=3k = 3: 7 1 13.5

The walk of line L9 gives the seven spans (0,4)(0,4) S, (0,1)(0,1) NP, (1,4)(1,4) VP, (1,2)(1,2) ∅\varnothing, (2,4)(2,4) VP, (2,3)(2,3) ∅\varnothing, (3,4)(3,4) NP, with score 13.5. After the ∅\varnothing spans are deleted, the tree is (S (NP She) (VP enjoys (VP playing (NP tennis)))). The root has two children.

The greedy top-down decoder of Stern et al. picks the best label of a span and then the split kk with the largest sspan(i,k)+sspan(k,j)s_{\text{span}}(i, k) + s_{\text{span}}(k, j), from the root down. At the root the split values are 1, 0.8 and 0 for k=1,2,3k = 1, 2, 3, so it takes k=1k = 1, as the chart does. At (1,4)(1, 4) the values are 0 for k=2k = 2 and 0.5 for k=3k = 3, so it takes k=3k = 3 and keeps the span enjoys playing, with the label ∅\varnothing. Its tree is (S (NP She) (VP enjoys playing (NP tennis))) with score 13.0, and it misses the inner VP. The tests check both results and check the chart against all 5 binary trees and all labelings.

Correctness

The claim is: CHART-PARSE stops and returns a labeled binary tree of largest score s(T)s(T), together with that score. This is a theorem.

The proof has two steps. First, for a fixed set of spans the score is a sum with one term per span, and the term of a span depends only on its own label, so the best labeling takes the best label of each span. The problem becomes the choice of the spans, with the weight m(i,j)=max⁡ℓslabel(i,j,ℓ)+sspan(i,j)m(i, j) = \max_\ell s_{\text{label}}(i, j, \ell) + s_{\text{span}}(i, j) on each span. Second, a binary tree over (i,j)(i, j) with more than one word is the span (i,j)(i, j), a split kk, and two independent binary trees over (i,k)(i, k) and (k,j)(k, j). So the best weight satisfies

best(i,j)=m(i,j)+max⁡i<k<j[best(i,k)+best(k,j)],\mathrm{best}(i, j) = m(i, j) + \max_{i < k < j} \big[\mathrm{best}(i, k) + \mathrm{best}(k, j)\big],

which is what lines L4 to L7 compute, from short spans to long ones. Since the scores can be any reals, the same theorem applied to the augmented label scores shows that loss-augmented decoding maximizes s(T)+Δ(T,T∗)s(T) + \Delta(T, T^*) exactly. The full proof is in the correctness proof.

The exactness is with respect to the factored score only. Whether the best-scoring tree is the right tree depends on the network, and that is a measurement, not a theorem.

Proof: The span chart decoder returns a binary labeled tree of maximum score, and loss-augmented decoding maximizes score plus Hamming lossfull

We use the pseudocode CHART-PARSE of the page. The input is a sentence length n≥1n \ge 1, a finite label set {0,1,…,L−1}\{0, 1, \ldots, L - 1\} with L≥1L \ge 1, where 0 is the empty label ∅\varnothing, real label scores slabel(i,j,ℓ)s_{\text{label}}(i, j, \ell) and real span scores sspan(i,j)s_{\text{span}}(i, j) for every fencepost span (i,j)(i, j) with 0≤i<j≤n0 \le i < j \le n. The span (i,j)(i, j) covers the words i+1i + 1 to jj. The scores are arbitrary reals; nothing is assumed about their sign.

Definitions

A binary bracketing of (i,j)(i, j) is a set BB of spans defined by induction: for j=i+1j = i + 1 it is {(i,j)}\{(i, j)\}, and for j>i+1j > i + 1 it is {(i,j)}∪B1∪B2\{(i, j)\} \cup B_1 \cup B_2 for some split kk with i<k<ji < k < j, a bracketing B1B_1 of (i,k)(i, k) and a bracketing B2B_2 of (k,j)(k, j). Since B1B_1 and B2B_2 contain only spans inside (i,k)(i, k) and (k,j)(k, j), the union is disjoint and (i,j)(i, j) is in neither part, and the split kk is determined by BB, because (i,k)(i, k) is the longest span of BB other than (i,j)(i, j) that starts at ii. A bracketing of (i,j)(i, j) has exactly 2(j−i)−12(j - i) - 1 spans, by induction.

A labeled tree TT over (i,j)(i, j) is a bracketing BB with a label ℓ(u)∈{0,…,L−1}\ell(u) \in \{0, \ldots, L - 1\} for each span u∈Bu \in B. Its score is

s(T)=∑u∈B[slabel(u,ℓ(u))+sspan(u)].s(T) = \sum_{u \in B} \big[ s_{\text{label}}(u, \ell(u)) + s_{\text{span}}(u) \big].

Let opt(i,j)\mathrm{opt}(i, j) be the largest score of a labeled tree over (i,j)(i, j). The maximum exists because there are finitely many labeled trees.

Lemma 1: the labels separate from the bracketing

For every span uu, let m(u)=max⁡ℓslabel(u,ℓ)+sspan(u)m(u) = \max_\ell s_{\text{label}}(u, \ell) + s_{\text{span}}(u). Then

opt(i,j)=max⁡B∑u∈Bm(u),\mathrm{opt}(i, j) = \max_{B} \sum_{u \in B} m(u),

where BB ranges over the bracketings of (i,j)(i, j), and a labeled tree has score opt(i,j)\mathrm{opt}(i, j) exactly when its bracketing attains this maximum and every span has a label of largest slabels_{\text{label}}.

Proof. For a fixed bracketing BB, the score is a sum of terms, one per span, and the term of uu depends only on ℓ(u)\ell(u). The labels are chosen independently, so the sum is largest when each term is, and its largest value is ∑u∈Bm(u)\sum_{u \in B} m(u). Taking the maximum over BB gives the claim. □\square

Lemma 2: the recurrence

opt(i,i+1)=m(i,i+1)\mathrm{opt}(i, i + 1) = m(i, i + 1), and for j>i+1j > i + 1,

opt(i,j)=m(i,j)+max⁡i<k<j[opt(i,k)+opt(k,j)].\mathrm{opt}(i, j) = m(i, j) + \max_{i < k < j} \big[ \mathrm{opt}(i, k) + \mathrm{opt}(k, j) \big].

Proof. The first equation is Lemma 1 with the only bracketing {(i,i+1)}\{(i, i + 1)\}. For j>i+1j > i + 1, every bracketing of (i,j)(i, j) is {(i,j)}∪B1∪B2\{(i, j)\} \cup B_1 \cup B_2 for a split kk and bracketings B1B_1 of (i,k)(i, k) and B2B_2 of (k,j)(k, j), and every such choice gives a bracketing. The sum of mm over it is m(i,j)+∑B1m+∑B2mm(i, j) + \sum_{B_1} m + \sum_{B_2} m, because the union is disjoint. For a fixed kk, the two sums are chosen independently, so their largest total is opt(i,k)+opt(k,j)\mathrm{opt}(i, k) + \mathrm{opt}(k, j) by Lemma 1. Maximizing over kk gives the recurrence. □\square

Theorem

CHART-PARSE stops, returns best(0,n)=opt(0,n)\mathrm{best}(0, n) = \mathrm{opt}(0, n), and returns the spans of a labeled tree over (0,n)(0, n) with this score.

Proof. Termination. Lines L1 to L8 are three nested loops with fixed bounds: nn lengths, at most nn start positions, at most nn splits and LL labels. The walk of line L9 visits each span of the result once, and there are 2n−12n - 1 of them.

The table. We show best(i,j)=opt(i,j)\mathrm{best}(i, j) = \mathrm{opt}(i, j) by induction on the length j−ij - i. Line L4 takes a label ℓ(i,j)\ell(i, j) of largest slabel(i,j,⋅)s_{\text{label}}(i, j, \cdot), so slabel(i,j,ℓ(i,j))+sspan(i,j)=m(i,j)s_{\text{label}}(i, j, \ell(i, j)) + s_{\text{span}}(i, j) = m(i, j). For length 1, line L5 sets best(i,i+1)=m(i,i+1)\mathrm{best}(i, i + 1) = m(i, i + 1), which is the base case of Lemma 2. For a length ℓ≥2\ell \ge 2, the loop of line L1 has finished all shorter lengths, so by the induction hypothesis best(i,k)=opt(i,k)\mathrm{best}(i, k) = \mathrm{opt}(i, k) and best(k,j)=opt(k,j)\mathrm{best}(k, j) = \mathrm{opt}(k, j) for every i<k<ji < k < j. Line L6 picks a split k(i,j)k(i, j) that maximizes their sum, and line L7 stores m(i,j)m(i, j) plus that sum. By Lemma 2 this is opt(i,j)\mathrm{opt}(i, j).

The tree. Let T(i,j)T(i, j) be the labeled tree that the walk of line L9 produces from (i,j)(i, j): the span (i,j)(i, j) with the label ℓ(i,j)\ell(i, j), and, if j>i+1j > i + 1, the trees T(i,k)T(i, k) and T(k,j)T(k, j) for k=k(i,j)k = k(i, j). By induction on the length, T(i,j)T(i, j) is a labeled tree over (i,j)(i, j) with score best(i,j)\mathrm{best}(i, j): for length 1 its score is m(i,i+1)=best(i,i+1)m(i, i + 1) = \mathrm{best}(i, i + 1); for a longer span its score is m(i,j)+best(i,k)+best(k,j)=best(i,j)m(i, j) + \mathrm{best}(i, k) + \mathrm{best}(k, j) = \mathrm{best}(i, j) by line L7. Line L10 returns T(0,n)T(0, n) and best(0,n)=opt(0,n)\mathrm{best}(0, n) = \mathrm{opt}(0, n). □\square

Corollary: loss-augmented decoding

Let T∗T^* be a binarized gold tree, and for a span uu let ℓ∗(u)\ell^*(u) be its gold label if u∈T∗u \in T^* and ∅\varnothing otherwise. For a labeled tree TT with bracketing BB, let the Hamming loss be Δ(T,T∗)=∑u∈B[ℓ(u)≠ℓ∗(u)]\Delta(T, T^*) = \sum_{u \in B} [\ell(u) \ne \ell^*(u)]. Run CHART-PARSE with the label scores slabel′(u,ℓ)=slabel(u,ℓ)+[ℓ≠ℓ∗(u)]s'_{\text{label}}(u, \ell) = s_{\text{label}}(u, \ell) + [\ell \ne \ell^*(u)]. Then it returns a tree that maximizes s(T)+Δ(T,T∗)s(T) + \Delta(T, T^*) over all labeled trees.

Proof. The score of TT under s′s' is ∑u∈B[slabel(u,ℓ(u))+[ℓ(u)≠ℓ∗(u)]+sspan(u)]=s(T)+Δ(T,T∗)\sum_{u \in B} [s_{\text{label}}(u, \ell(u)) + [\ell(u) \ne \ell^*(u)] + s_{\text{span}}(u)] = s(T) + \Delta(T, T^*). The theorem applies to s′s', since it allows any real scores. ■\blacksquare

The page uses the corollary for the hinge loss max⁡(0,max⁡T[s(T)+Δ(T,T∗)]−s(T∗))\max(0, \max_T [s(T) + \Delta(T, T^*)] - s(T^*)), which is therefore computed exactly by one run of the decoder.

Complexity

Time. There are n(n+1)/2n(n + 1)/2 spans. Line L4 costs O(L)O(L) per span, and line L6 costs O(j−i)O(j - i) per span. The total is ∑len=1n(n−len+1)(len−1)=(n3−n)/6\sum_{\text{len}=1}^{n} (n - \text{len} + 1)(\text{len} - 1) = (n^3 - n)/6 split checks plus O(n2L)O(n^2 L) for the labels, so the decoder takes Θ(n3+n2L)\Theta(n^3 + n^2 L) time on the word RAM, on every input. The cost of the network that produces the O(n2L)O(n^2 L) scores is not included; for a BiLSTM or a transformer encoder it is often larger than the cost of the decoder.

Space. The tables best, split and label take Θ(n2)\Theta(n^2) space. The input scores themselves take Θ(n2L)\Theta(n^2 L).

Greedy decoding. The top-down decoder computes O(n)O(n) splits, each in O(n)O(n) time, so it takes O(n2+nL)O(n^2 + n L) time, but it is not exact.

Properties

  • Exact for the model. The decoder returns a tree of maximum score for any real scores. Ties are broken toward the first label and the smallest split.
  • No grammar. Every label can appear on every span, and every pair of labels can be parent and child. The decoder cannot produce a tree that is ungrammatical, because there is no grammar to break.
  • Label and split separate. The best label of a span and the best split below it are found independently. Probabilistic CKY with a grammar of mm nonterminals takes O(n3g)O(n^3 g) for gg binary rules, while this decoder takes O(n3+n2L)O(n^3 + n^2 L).
  • Fixed size. Every binary tree over nn words has 2n−12n - 1 spans, so trees of different shapes are compared over the same number of terms.
  • n-ary output. Deleting the ∅\varnothing spans turns the binary tree into an n-ary tree. The root span can also get the label ∅\varnothing; the code then puts a placeholder label on the root, and a parser can forbid ∅\varnothing at (0,n)(0, n) instead.
  • Measurement. Stern et al. report test F1 of 91.69 for the chart parser and 91.58 for the greedy top-down parser on the Penn Treebank. Kitaev and Klein report 93.55 with a self-attentive encoder and the same kind of chart decoder, and 95.13 with pre-trained word representations.

Variants and improvements

  • The span representation. Stern et al. represent the span (i,j)(i, j) by [fj−fi; bi−bj][f_j - f_i;\ b_i - b_j], the differences of forward and backward BiLSTM states at its two fenceposts, and compute the label scores by a feedforward network with one output per label. Kitaev and Klein keep the decoder and replace the BiLSTM by a self-attentive encoder built from multi-head attention.
  • Top-down greedy decoding. The decoder of the example picks splits by span scores alone, from the root down. It is faster and lost little accuracy in the measurements of Stern et al., but it is not exact.
  • Sum instead of max. Replacing max by a log-sum-exp in lines L4, L6 and L7 gives the log of the sum of exp⁡s(T)\exp s(T) over all labeled trees, the partition function of a tree-structured conditional random field. This allows training by likelihood instead of the margin.
  • Pruning and faster decoders. Since the label scores are known in advance, spans whose best label score is very low can be removed before the chart is filled. This is a heuristic and can lose the best tree.
  • The same idea for other structures. Scoring spans and decoding exactly is also the basis of the semi-Markov CRF for segmentation, where the spans do not nest, and of the biaffine dependency parser, which scores word pairs instead of spans.

When to use it

Use this decoder when a neural network can score spans and an exact, simple decoder is wanted. It needs no grammar, no rule extraction and no binarization of a grammar, only a binarized training tree. For sentences of ordinary length the cubic loop is usually cheap next to the encoder, but this is an observation about typical inputs, not a bound. For very long inputs or tight time budgets, the greedy top-down decoder or a transition-based parser is faster. When a grammar with hard constraints is needed, use probabilistic CKY or A* parsing instead. Evaluate the result with the PARSEVAL measures after the ∅\varnothing spans are deleted and the unary chains are expanded.

Pitfalls

  • The split range. Writing line L6 as "for k ← i to j" lets a span split into itself and an empty span. The right line is "the first k with i < k < j".
  • The bonus in the loss. Writing the augmented score as slabel(i,j,ℓ)+[ℓ=ℓ∗(i,j)]s_{\text{label}}(i, j, \ell) + [\ell = \ell^*(i, j)] rewards agreement with the gold tree, so the decoder looks for trees close to it and the loss is never 0. The right score is slabel(i,j,ℓ)+[ℓ≠ℓ∗(i,j)]s_{\text{label}}(i, j, \ell) + [\ell \ne \ell^*(i, j)], which rewards mistakes, so that the decoder finds the tree that violates the margin most.
  • Forgetting the empty gold label. A span that is not in the binarized gold tree has the gold label ∅\varnothing. Skipping such spans when adding the bonus makes the loss ignore extra brackets.
  • Length-one spans. For a span of one word the loop of line L6 is empty. Without the base case of line L5, best(i,i+1)(i, i + 1) is undefined. Line L5 sets it to vv.
  • Scoring with ∅\varnothing spans. PARSEVAL counts the brackets of the n-ary tree. Counting the ∅\varnothing spans of the binary tree, or not expanding a unary chain label such as S+VP into its two nodes, gives wrong precision and recall.
  • Greedy is not exact. The example shows a tree of score 13.0 from the greedy decoder against 13.5 from the chart. Use the chart for loss-augmented decoding, since a greedy maximum can make the hinge loss too small.

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.

span_based_constituency_parsing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/span-based-constituency-parsing/. The authors are listed in prov/M9QEWS.jsonl.

"""Span-based constituency parsing: the chart decoder over given span scores.

The code takes the network outputs as given: label_scores[(i, j)] is a list of
L real numbers, the score of each label for the fencepost span (i, j), which
covers the words i + 1 to j (words i to j - 1 counted from 0). Label 0 is the
empty label, which marks a span that exists only in the binarized tree.
span_scores[(i, j)] is an optional extra score for the span, 0 by default.

A binary tree over n words has exactly 2n - 1 spans. Its score is the sum over
its spans (i, j, l) of label_scores[(i, j)][l] + span_scores[(i, j)]. The chart
decoder finds a tree of largest score in O(n^3 + n^2 L) time and O(n^2) space.
The output tree drops the spans with the empty label, which can make it n-ary.
"""

from typing import Dict, List, Optional, Sequence, Set, Tuple

Span = Tuple[int, int]
LabeledSpan = Tuple[int, int, int]
EMPTY = 0


def _best_label(scores: Sequence[float]) -> int:
    best = 0
    for k in range(1, len(scores)):
        if scores[k] > scores[best]:
            best = k
    return best


def chart_parse(n: int, label_scores: Dict[Span, Sequence[float]],
                span_scores: Optional[Dict[Span, float]] = None) -> Tuple[float, List[LabeledSpan]]:
    """Return (best score, the 2n - 1 labeled spans of a best binary tree).

    The label of a span and the split below it are chosen independently, so
    the label max costs O(L) per span and the split max O(n) per span.
    """
    if n < 1:
        raise ValueError("a tree needs at least one word")
    span_scores = span_scores or {}
    best: Dict[Span, float] = {}
    split: Dict[Span, int] = {}
    label: Dict[Span, int] = {}
    for length in range(1, n + 1):  # @line L1
        for i in range(n - length + 1):  # @line L2
            j = i + length  # @line L3
            scores = label_scores[(i, j)]
            lab = _best_label(scores)  # @line L4
            v = scores[lab] + span_scores.get((i, j), 0.0)
            if length == 1:  # @line L5
                best[(i, j)] = v
            else:
                k_best = i + 1
                for k in range(i + 2, j):  # @line L6
                    if best[(i, k)] + best[(k, j)] > best[(i, k_best)] + best[(k_best, j)]:
                        k_best = k
                best[(i, j)] = v + best[(i, k_best)] + best[(k_best, j)]  # @line L7
                split[(i, j)] = k_best
            label[(i, j)] = lab  # @line L8
    spans: List[LabeledSpan] = []
    stack = [(0, n)]
    while stack:  # @line L9
        i, j = stack.pop()
        spans.append((i, j, label[(i, j)]))
        if j - i > 1:
            k = split[(i, j)]
            stack.append((k, j))
            stack.append((i, k))
    return best[(0, n)], spans  # @line L10


def tree_score(spans: Sequence[LabeledSpan], label_scores: Dict[Span, Sequence[float]],
               span_scores: Optional[Dict[Span, float]] = None) -> float:
    """Return the score of a tree given as its labeled spans."""
    span_scores = span_scores or {}
    return sum(label_scores[(i, j)][lab] + span_scores.get((i, j), 0.0) for i, j, lab in spans)


def labeled_spans(spans: Sequence[LabeledSpan]) -> Set[LabeledSpan]:
    """Return the spans with a label other than the empty label: the n-ary tree."""
    return {(i, j, lab) for i, j, lab in spans if lab != EMPTY}


def to_tree(n: int, spans: Sequence[LabeledSpan], labels: Sequence[str]):
    """Return the n-ary tree (label, children) of the spans, with the words as
    the integers 0 to n - 1. Spans with the empty label are dropped. If the
    root span is empty, the root gets the label of index 0 as a placeholder."""
    kept = sorted(((i, j, lab) for i, j, lab in spans if lab != EMPTY or (i, j) == (0, n)),
                  key=lambda s: (s[0], -s[1]))
    if not kept or kept[0][:2] != (0, n):
        raise ValueError("the spans have no root span (0, n)")
    root = (labels[kept[0][2]], [])
    stack = [(0, n, root)]  # a chain of nested open spans
    w = 0

    def emit_words_before(end: int) -> None:
        nonlocal w
        while w < end:
            while stack[-1][1] <= w:
                stack.pop()
            stack[-1][2][1].append(w)
            w += 1

    for i, j, lab in kept[1:]:
        emit_words_before(i)
        while not (stack[-1][0] <= i and j <= stack[-1][1]):
            stack.pop()
        node = (labels[lab], [])
        stack[-1][2][1].append(node)
        stack.append((i, j, node))
    emit_words_before(n)
    return root


def top_down_greedy(n: int, label_scores: Dict[Span, Sequence[float]],
                    span_scores: Optional[Dict[Span, float]] = None) -> Tuple[float, List[LabeledSpan]]:
    """The greedy top-down decoder: pick the best label of each span and the split
    k of largest span_scores[(i, k)] + span_scores[(k, j)], from the root down.
    O(n^2 + n L) time; not optimal in general."""
    span_scores = span_scores or {}
    spans: List[LabeledSpan] = []
    stack = [(0, n)]
    while stack:
        i, j = stack.pop()
        spans.append((i, j, _best_label(label_scores[(i, j)])))
        if j - i > 1:
            k_best = max(range(i + 1, j),
                         key=lambda k: (span_scores.get((i, k), 0.0) + span_scores.get((k, j), 0.0), -k))
            stack.append((k_best, j))
            stack.append((i, k_best))
    return tree_score(spans, label_scores, span_scores), spans


def loss_augmented_scores(n: int, label_scores: Dict[Span, Sequence[float]],
                          gold: Sequence[LabeledSpan]) -> Dict[Span, List[float]]:
    """Add 1 to every label that differs from the gold label of the span.

    gold is the binarized gold tree as labeled spans. A span that is not in it
    has the gold label EMPTY. Decoding with these scores maximizes
    score + Hamming loss over the spans of the tree."""
    gold_label = {(i, j): lab for i, j, lab in gold}
    out: Dict[Span, List[float]] = {}
    for (i, j), scores in label_scores.items():
        g = gold_label.get((i, j), EMPTY)
        out[(i, j)] = [s + (0.0 if lab == g else 1.0) for lab, s in enumerate(scores)]
    return out


def hinge_loss(n: int, label_scores: Dict[Span, Sequence[float]], gold: Sequence[LabeledSpan],
               span_scores: Optional[Dict[Span, float]] = None) -> float:
    """max(0, max over trees T of [s(T) + Hamming(T, gold)] - s(gold))."""
    aug = loss_augmented_scores(n, label_scores, gold)
    top, _ = chart_parse(n, aug, span_scores)
    return max(0.0, top - tree_score(gold, label_scores, span_scores))
test_span_based_constituency_parsing.py 188 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/span-based-constituency-parsing/. The authors are listed in prov/M9QEWS.jsonl.

import itertools
import math
import random

from span_based_constituency_parsing import (EMPTY, chart_parse, hinge_loss, labeled_spans,
                                             loss_augmented_scores, to_tree, top_down_greedy,
                                             tree_score)

LABELS = ["", "S", "NP", "VP"]


def bracketings(i, j):
    """All binary trees over the span (i, j), each as a list of its 2(j - i) - 1 spans."""
    if j - i == 1:
        return [[(i, j)]]
    out = []
    for k in range(i + 1, j):
        for left in bracketings(i, k):
            for right in bracketings(k, j):
                out.append([(i, j)] + left + right)
    return out


def brute_force(n, ls, ss=None):
    """Best score over all binary trees and all labelings, by full enumeration
    of the labels when the tree is small, and per-span max otherwise."""
    ss = ss or {}
    best = -math.inf
    for tree in bracketings(0, n):
        if len(tree) <= 5:
            for labs in itertools.product(*[range(len(ls[s])) for s in tree]):
                v = sum(ls[s][lab] + ss.get(s, 0.0) for s, lab in zip(tree, labs))
                best = max(best, v)
        else:
            best = max(best, sum(max(ls[s]) + ss.get(s, 0.0) for s in tree))
    return best


def random_scores(rng, n, n_labels, with_span=True):
    ls = {(i, j): [rng.choice([-2, -1, 0, 1, 2, 3]) + rng.random() for _ in range(n_labels)]
          for i in range(n) for j in range(i + 1, n + 1)}
    ss = {(i, j): rng.uniform(-2, 2) for i in range(n) for j in range(i + 1, n + 1)} if with_span else None
    return ls, ss


def is_binary_tree(n, spans):
    s = {(i, j) for i, j, _ in spans}
    if len(spans) != 2 * n - 1 or len(s) != len(spans) or (0, n) not in s:
        return False
    for i in range(n):
        if (i, i + 1) not in s:
            return False
    for i, j in s:
        if j - i > 1 and sum(1 for k in range(i + 1, j) if (i, k) in s and (k, j) in s) != 1:
            return False
    return True


def test_catalan_counts() -> None:
    assert [len(bracketings(0, n)) for n in range(1, 8)] == [1, 1, 2, 5, 14, 42, 132]


def example_scores():
    # She enjoys playing tennis: spans (i, j) with the label scores of
    # (empty, S, NP, VP) and a span score.
    ls = {
        (0, 1): [0.0, -2.0, 2.0, -1.0], (1, 2): [1.0, -2.0, -1.0, 0.0],
        (2, 3): [1.0, -1.0, -1.0, 0.0], (3, 4): [0.0, -2.0, 2.0, -1.0],
        (0, 2): [0.0, -1.0, -1.0, -1.0], (1, 3): [0.5, -2.0, -2.0, 0.0],
        (2, 4): [0.0, -1.0, 0.0, 1.5], (0, 3): [0.0, -1.0, -2.0, -2.0],
        (1, 4): [0.0, -1.0, -2.0, 2.0], (0, 4): [-1.0, 3.0, -1.0, 0.0],
    }
    ss = {(0, 1): 0.0, (1, 2): 0.0, (2, 3): 0.0, (3, 4): 0.0,
          (0, 2): 0.8, (1, 3): 0.5, (2, 4): 0.0, (0, 3): 0.0, (1, 4): 1.0, (0, 4): 0.0}
    return ls, ss


def test_example() -> None:
    ls, ss = example_scores()
    score, spans = chart_parse(4, ls, ss)
    assert math.isclose(score, 13.5)
    assert set(spans) == {(0, 4, 1), (0, 1, 2), (1, 4, 3), (1, 2, 0), (2, 4, 3), (2, 3, 0), (3, 4, 2)}
    assert labeled_spans(spans) == {(0, 4, 1), (0, 1, 2), (1, 4, 3), (2, 4, 3), (3, 4, 2)}
    assert to_tree(4, spans, LABELS) == ("S", [("NP", [0]), ("VP", [1, ("VP", [2, ("NP", [3])])])])
    g_score, g_spans = top_down_greedy(4, ls, ss)
    assert set(g_spans) == {(0, 4, 1), (0, 1, 2), (1, 4, 3), (1, 3, 0), (1, 2, 0), (2, 3, 0), (3, 4, 2)}
    assert math.isclose(g_score, 13.0)
    assert to_tree(4, g_spans, LABELS) == ("S", [("NP", [0]), ("VP", [1, 2, ("NP", [3])])])
    assert brute_force(4, ls, ss) == score


def test_one_word() -> None:
    score, spans = chart_parse(1, {(0, 1): [0.5, 2.0]})
    assert score == 2.0 and spans == [(0, 1, 1)]
    assert to_tree(1, spans, ["", "NP"]) == ("NP", [0])
    # an empty root keeps a placeholder label
    assert to_tree(1, [(0, 1, 0)], ["X", "NP"]) == ("X", [0])


def test_random_against_brute_force() -> None:
    rng = random.Random(2017)
    for trial in range(700):
        n = rng.randint(1, 4 if trial % 7 else 7)
        n_labels = rng.randint(1, 3 if n <= 3 else 4)
        ls, ss = random_scores(rng, n, n_labels, with_span=trial % 2 == 0)
        score, spans = chart_parse(n, ls, ss)
        assert is_binary_tree(n, spans)
        assert math.isclose(tree_score(spans, ls, ss), score, rel_tol=1e-12, abs_tol=1e-12)
        assert math.isclose(brute_force(n, ls, ss), score, rel_tol=1e-12, abs_tol=1e-12)
        g_score, g_spans = top_down_greedy(n, ls, ss)
        assert is_binary_tree(n, g_spans)
        assert g_score <= score + 1e-12


def hamming(spans, gold):
    g = {(i, j): lab for i, j, lab in gold}
    return sum(1 for i, j, lab in spans if g.get((i, j), EMPTY) != lab)


def test_loss_augmented_decoding() -> None:
    rng = random.Random(5)
    for _ in range(200):
        n = rng.randint(1, 5)
        ls, ss = random_scores(rng, n, 3)
        gold = rng.choice(bracketings(0, n))
        gold = [(i, j, rng.randrange(3)) for i, j in gold]
        aug = loss_augmented_scores(n, ls, gold)
        top, spans = chart_parse(n, aug, ss)
        brute = -math.inf
        for tree in bracketings(0, n):
            if len(tree) <= 5:  # every labeling
                for labs in itertools.product(range(3), repeat=len(tree)):
                    t = [(i, j, lab) for (i, j), lab in zip(tree, labs)]
                    brute = max(brute, tree_score(t, ls, ss) + hamming(t, gold))
            else:  # the best labeling of this bracketing, found by trying each label per span
                t = []
                for i, j in tree:
                    t.append(max(((i, j, lab) for lab in range(3)),
                                 key=lambda s: tree_score([s], ls, ss) + hamming([s], gold)))
                brute = max(brute, tree_score(t, ls, ss) + hamming(t, gold))
        assert math.isclose(top, brute, rel_tol=1e-12, abs_tol=1e-12)
        assert math.isclose(tree_score(spans, ls, ss) + hamming(spans, gold), top, abs_tol=1e-12)
        h = hinge_loss(n, ls, gold, ss)
        assert h >= 0.0
        assert math.isclose(h, max(0.0, brute - tree_score(gold, ls, ss)), abs_tol=1e-12)


def test_hinge_zero_with_margin() -> None:
    # gold labels beat every other label by more than 1 on every gold span,
    # and other spans have no chance: the hinge loss is 0
    n = 4
    gold = [(0, 4, 1), (0, 1, 2), (1, 4, 3), (1, 2, 0), (2, 4, 3), (2, 3, 0), (3, 4, 2)]
    ls = {(i, j): [0.0, 0.0, 0.0, 0.0] for i in range(n) for j in range(i + 1, n + 1)}
    ss = {(i, j): -10.0 for i in range(n) for j in range(i + 1, n + 1)}
    for i, j, lab in gold:
        ls[(i, j)][lab] = 5.0
        ss[(i, j)] = 0.0
    assert hinge_loss(n, ls, gold, ss) == 0.0
    assert set(chart_parse(n, ls, ss)[1]) == set(gold)


def test_long_sentence() -> None:
    rng = random.Random(9)
    n = 60
    ls, ss = random_scores(rng, n, 3)
    score, spans = chart_parse(n, ls, ss)
    assert is_binary_tree(n, spans)
    assert math.isclose(tree_score(spans, ls, ss), score, rel_tol=1e-12)
    tree = to_tree(n, spans, ["", "A", "B"])
    flat, stack = [], [tree]
    while stack:
        u = stack.pop()
        if isinstance(u, int):
            flat.append(u)
        else:
            stack.extend(reversed(u[1]))
    assert flat == list(range(n))


def test_bad_input() -> None:
    try:
        chart_parse(0, {})
    except ValueError:
        return
    raise AssertionError("n = 0 accepted")

History

Before 2016, statistical constituency parsers scored grammar rules, as in lexicalized PCFGs and latent-variable PCFGs. The first neural constituency parsers used transition systems or sequence models, and some of them already used BiLSTM features of spans. Stern, Andreas and Klein (2017) showed that the span scores are enough: with no grammar and no transition system, a chart over spans, trained with a margin loss and loss-augmented decoding, gave 91.69 F1 on the Penn Treebank. Kitaev and Klein (2018) kept the decoder, replaced the encoder by self-attention and reached 93.55 F1, and 95.13 with pre-trained representations. Later parsers kept the span chart and changed the encoder or the training loss.

References

  1. Mitchell Stern, Jacob Andreas and Dan Klein, A Minimal Span-Based Neural Constituency Parser, ACL 2017, pp. 818-827; the span representation, the label and span scores, the chart parser, the top-down parser, the margin training with loss-augmented decoding, and the test results
  2. Nikita Kitaev and Dan Klein, Constituency Parsing with a Self-Attentive Encoder, ACL 2018, pp. 2676-2686; the self-attentive encoder over the same span decoder and the results on the Penn Treebank

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.best
  • 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
  • at least three sources
  • a scene preset for the example