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.
- Solves
- Constituency parsing
- 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
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 words and a label set , where label 0 is the empty label . For every fencepost span with , which covers the words to , the network gives a label score for every label and a span score . All scores are arbitrary reals.
A binary tree over the sentence is a set of spans: the root span , the spans of one word, and for every span of more than one word a split with such that and are also in the set. Each span gets one label. The score of a labeled tree is
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 , 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 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 for every span of the tree, root included. Every tree contains the root span, so the two scores differ by the constant , and they have the same best tree.
The algorithm
CHART-PARSE(n, s_label, s_span)- 1
for len ← 1 to n do - 2
for i ← 0 to n - len do - 3
j ← i + len - 4
lab ← a label ℓ of largest s_label(i, j, ℓ); v ← s_label(i, j, lab) + s_span(i, j) - 5
if len = 1 then best(i, j) ← v - 6
else split(i, j) ← the first k with i < k < j of largest best(i, k) + best(k, j) - 7
best(i, j) ← v + best(i, split(i, j)) + best(split(i, j), j) - 8
label(i, j) ← lab - 9
walk from (0, n): output (i, j, label(i, j)), and if j - i > 1 walk (i, split(i, j)) and (split(i, j), j) - 10
return 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 time, and line L6 picks the split once per span, in 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 , the Hamming loss counts the spans of whose label differs from the gold label, where a span that is not in has the gold label . The hinge loss is
The inner maximum is computed by CHART-PARSE itself, after 1 is added to every label score with different from the gold label of . 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 and the labels , S, NP, VP. The scores below are made up for the example; in a real parser they come from the network.
| span | words | S | NP | VP | ||
|---|---|---|---|---|---|---|
| She | 0 | -2 | 2 | -1 | 0 | |
| enjoys | 1 | -2 | -1 | 0 | 0 | |
| playing | 1 | -1 | -1 | 0 | 0 | |
| tennis | 0 | -2 | 2 | -1 | 0 | |
| She enjoys | 0 | -1 | -1 | -1 | 0.8 | |
| enjoys playing | 0.5 | -2 | -2 | 0 | 0.5 | |
| playing tennis | 0 | -1 | 0 | 1.5 | 0 | |
| She enjoys playing | 0 | -1 | -2 | -2 | 0 | |
| enjoys playing tennis | 0 | -1 | -2 | 2 | 1 | |
| the whole sentence | -1 | 3 | -1 | 0 | 0 |
The chart, in the order of lines L1 to L8. The column is the value of line L4, and the split column lists for each .
| span | label | splits | split | best | |
|---|---|---|---|---|---|
| NP | 2 | 2 | |||
| 1 | 1 | ||||
| 1 | 1 | ||||
| NP | 2 | 2 | |||
| 0.8 | : 3 | 1 | 3.8 | ||
| 1 | : 2 | 2 | 3 | ||
| VP | 1.5 | : 3 | 3 | 4.5 | |
| 0 | : 5, : 4.8 | 1 | 5 | ||
| VP | 3 | : 5.5, : 5 | 2 | 8.5 | |
| S | 3 | : 10.5, : 8.3, : 7 | 1 | 13.5 |
The walk of line L9 gives the seven spans S, NP, VP, , VP, , NP, with score 13.5. After the 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 with the largest , from the root down. At the root the split values are 1, 0.8 and 0 for , so it takes , as the chart does. At the values are 0 for and 0.5 for , so it takes and keeps the span enjoys playing, with the label . 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 , 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 on each span. Second, a binary tree over with more than one word is the span , a split , and two independent binary trees over and . So the best weight satisfies
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 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 , a finite label set with , where 0 is the empty label , real label scores and real span scores for every fencepost span with . The span covers the words to . The scores are arbitrary reals; nothing is assumed about their sign.
Definitions
A binary bracketing of is a set of spans defined by induction: for it is , and for it is for some split with , a bracketing of and a bracketing of . Since and contain only spans inside and , the union is disjoint and is in neither part, and the split is determined by , because is the longest span of other than that starts at . A bracketing of has exactly spans, by induction.
A labeled tree over is a bracketing with a label for each span . Its score is
Let be the largest score of a labeled tree over . The maximum exists because there are finitely many labeled trees.
Lemma 1: the labels separate from the bracketing
For every span , let . Then
where ranges over the bracketings of , and a labeled tree has score exactly when its bracketing attains this maximum and every span has a label of largest .
Proof. For a fixed bracketing , the score is a sum of terms, one per span, and the term of depends only on . The labels are chosen independently, so the sum is largest when each term is, and its largest value is . Taking the maximum over gives the claim.
Lemma 2: the recurrence
, and for ,
Proof. The first equation is Lemma 1 with the only bracketing . For , every bracketing of is for a split and bracketings of and of , and every such choice gives a bracketing. The sum of over it is , because the union is disjoint. For a fixed , the two sums are chosen independently, so their largest total is by Lemma 1. Maximizing over gives the recurrence.
Theorem
CHART-PARSE stops, returns , and returns the spans of a labeled tree over with this score.
Proof. Termination. Lines L1 to L8 are three nested loops with fixed bounds: lengths, at most start positions, at most splits and labels. The walk of line L9 visits each span of the result once, and there are of them.
The table. We show by induction on the length . Line L4 takes a label of largest , so . For length 1, line L5 sets , which is the base case of Lemma 2. For a length , the loop of line L1 has finished all shorter lengths, so by the induction hypothesis and for every . Line L6 picks a split that maximizes their sum, and line L7 stores plus that sum. By Lemma 2 this is .
The tree. Let be the labeled tree that the walk of line L9 produces from : the span with the label , and, if , the trees and for . By induction on the length, is a labeled tree over with score : for length 1 its score is ; for a longer span its score is by line L7. Line L10 returns and .
Corollary: loss-augmented decoding
Let be a binarized gold tree, and for a span let be its gold label if and otherwise. For a labeled tree with bracketing , let the Hamming loss be . Run CHART-PARSE with the label scores . Then it returns a tree that maximizes over all labeled trees.
Proof. The score of under is . The theorem applies to , since it allows any real scores.
The page uses the corollary for the hinge loss , which is therefore computed exactly by one run of the decoder.
Complexity
Time. There are spans. Line L4 costs per span, and line L6 costs per span. The total is split checks plus for the labels, so the decoder takes time on the word RAM, on every input. The cost of the network that produces the 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 space. The input scores themselves take .
Greedy decoding. The top-down decoder computes splits, each in time, so it takes 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 nonterminals takes for binary rules, while this decoder takes .
- Fixed size. Every binary tree over words has spans, so trees of different shapes are compared over the same number of terms.
- n-ary output. Deleting the spans turns the binary tree into an n-ary tree. The root span can also get the label ; the code then puts a placeholder label on the root, and a parser can forbid at 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 by , 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 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 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 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 , 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 . 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 is undefined. Line L5 sets it to .
- Scoring with spans. PARSEVAL counts the brackets of the n-ary tree. Counting the 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.
# 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
- 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
- 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.
| 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 M9QEWS Edit this page History Report an error Markdown