Algorithmadvanced
Neural transition-based dependency parser
Also called Chen-Manning parser.
A transition parser whose next move is chosen by a feedforward network on embeddings of words, tags and labels near the stack top.
- Solves
- Dependency parsing
- Time
- Θ(n H (d + T)) worst · best
- Space
- Θ(n + d + H + T) extra
- Where
- H = the number of hidden units; T = the number of transitions, 2 times the number of labels plus 1; d = the embedding size; n = the number of words
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Danqi Chen, Christopher D. Manning, 2014
The Chen-Manning parser is greedy arc-standard parsing in which the next move is chosen by a small neural network. In each configuration it reads 48 items near the top of the stack and the front of the buffer: 18 words, their 18 part-of-speech tags, and 12 arc labels of dependents already attached. Each item is mapped to a dense vector, an embedding; the vectors are joined, passed through one hidden layer with the cube activation , and a softmax layer gives a probability for each transition. The parser takes the most probable legal transition. Chen and Manning (2014) showed that this dense model, with no hand-made feature combinations, is both more accurate and faster than the sparse feature-based parsers of the time. A cache of first-layer products for frequent words makes each step cost a few hundred additions.
In plain words
The parser works like arc-standard parsing: a pile of words being built, a queue of words still to read, and three kinds of moves. To choose a move, it looks at a fixed set of nearby things: the top three words on the pile, the next three words in the queue, some of the children already joined to the top two words, and the tags and labels of these. Each thing is turned into a short list of numbers, learned from data. A small network mixes all these numbers and gives a score to each possible move. The parser takes the best allowed move and goes on. It never goes back, so it is fast, but an early error can lead to more.
The problem
The input is a sentence with part-of-speech tags, and a trained network. The output is a labeled projective dependency tree. In the main version the root may get several children; with the single-root rule of arc-standard parsing, RIGHT-ARC from the root only when the buffer is empty, it gets exactly one. Training uses a treebank of projective trees: each sentence gives one example per configuration on its oracle path, with the gold transition as the class.
The code on this site takes the network weights as given, drawn from a seeded generator in the tests. It implements the features, the forward pass, the cache of first-layer products, the greedy parser, the oracle and the training loss with its gradient in the output layer, but it does not train the network.
The algorithm
Features. Let be the top three stack words and the first three buffer words. For a word , and are its leftmost and second leftmost dependents attached so far, and , the rightmost and second rightmost. The 18 word positions are
The 18 tag features are the tags of the same positions, and the 12 label features are the labels of the last 12 positions, the dependents. A missing position gives the special item NULL, and the root gives ROOT; unknown words give UNK.
Network. Each feature selects a column of its embedding table, , or , each with rows. The 48 vectors are joined into , and
CHEN-MANNING-PARSE(words, tags, network)- 1
c <- ([0], [1, ..., n], {}) - 2
while c is not terminal do - 3
f <- the 48 feature ids of c - 4
x <- the joined embeddings of f; h <- (W1 x + b1)^3; z <- W2 h - 5
log p <- the log softmax of z over the legal transitions of c - 6
t <- the legal transition with the largest z - 7
c <- t(c) - 8
return the tree A of c
Training. The gold sequence of a projective tree comes from a static oracle: LEFT-ARC if the gold head of is ; RIGHT-ARC if the gold head of is and has all its gold dependents; SHIFT otherwise. The loss is the cross-entropy of the gold transition, summed over all examples, with L2 regularization. The gradient flows by backpropagation through , and into the embeddings, which are updated too. Chen and Manning trained with AdaGrad and dropout, and started the word embeddings from vectors trained on unlabeled text.
The cache. , where is the block of columns of feature and its embedding. For a fixed feature position and a frequent item , the vector can be computed once and stored. Then the first layer is a sum of 48 stored vectors of length , with no multiplications.
Example
Take the cat sat on the mat (words 1 to 6) with the gold heads [-1, 2, 3, 0, 6, 6, 3] and the labels det, nsubj, root, case, det, obl. After SHIFT, SHIFT, LEFT-ARC, SHIFT, the stack is 0, cat, sat and the buffer is on the mat. Some of the 48 features:
| position | word | tag | label |
|---|---|---|---|
| sat | VERB | ||
| cat | NOUN | ||
| ROOT | ROOT | ||
| on, the, mat | ADP, DET, NOUN | ||
| NULL | NULL | NULL | |
| the | DET | det | |
| the other 10 dependents | NULL | NULL | NULL |
The gold move here is LEFT-ARC, which makes sat the head of cat. The full oracle sequence has 12 moves: SH, SH, LA-det, SH, LA-nsubj, SH, SH, SH, LA-det, LA-case, RA-obl, RA-root.
Greedy is not exact. With the sentence the cat sat down, one label, , and the weights drawn from the seed 10, the greedy parser takes SH, SH, SH, SH, LA, RA, LA, RA, with total log probability about . A search over all complete sequences finds SH, SH, SH, SH, LA, LA, LA, RA, with about . The tests check this case.
Correctness
The parser always returns a projective tree. The network only chooses among the legal transitions of the arc-standard system, so every run is an arc-standard run: it ends after exactly moves with a projective tree, with one root child under the single-root rule. This holds for any weights; the network affects only which tree. The tests check it for random weights and sentences.
The oracle gives the training data. The static oracle rebuilds every projective tree in moves and gets stuck on every non-projective one, so a treebank must be projective, or made projective, before training. The tests check this for all trees with .
The cache is exact. The first layer is linear in the joined vector, so the sum of the stored blocks equals before the cube. The tests compare the two hidden layers for every configuration of the example.
The loss gradient. For the softmax over the legal set , for , and 0 outside . So the gradient in is restricted to the legal rows. The tests compare it with finite differences.
The proofs are in the correctness proof.
Proof: The neural transition parser returns a projective tree after 2n moves for any weights, its cache is exact, and its loss gradient is p minus the gold indicatorfull
The words are and 0 is the root. The parser runs the arc-standard system: SHIFT, LEFT-ARC (needs ) and RIGHT-ARC (under the single-root rule, from only with an empty buffer). The network gives a real number to every transition ; the parser takes a legal with the largest .
Theorem 1 (termination and output). For every choice of weights, the parser stops after exactly moves and returns a projective dependency tree rooted at 0. Under the single-root rule the root has exactly one child.
Proof. The parser picks only legal transitions, so its run is a run of the arc-standard system with some choice rule. In any non-terminal configuration some transition is legal: SHIFT if the buffer is not empty; otherwise the stack has at least two words, and RIGHT-ARC is legal, also under the single-root rule, since the buffer is empty. So the maximum in line L6 is over a non-empty set. By the soundness theorem of arc-standard parsing (see the arc-standard proof), every run of that system ends after exactly transitions in a terminal configuration whose arcs form a projective tree, with one root child under the single-root rule. None of this depends on how the legal transition is chosen.
Lemma 2 (the oracle). For a projective gold tree , the static oracle (LEFT-ARC if ; RIGHT-ARC if and has all its gold dependents; SHIFT otherwise) gives a legal sequence of moves that builds . For a non-projective tree it gets stuck.
Proof. We first build a run that produces , and then show that the oracle chooses the next move of in every configuration of .
Construction. For a word with gold left dependents and right dependents , let
where SHIFT pushes and the LEFT-ARC moves attach to in turn. Since is projective, the yields of are consecutive intervals in this order. By induction on the size of the yield, if the buffer front is the first word of the yield of , then is legal, pushes on top of the old stack, moves the buffer front past the yield, and adds exactly the gold arcs inside the yield. The whole run is RIGHT-ARC RIGHT-ARC for the root children ; it has one SHIFT and one arc per word, moves.
In every configuration of , the stack yields are consecutive intervals in stack order, as in every arc-standard run. So the word below the top lies to the left of . In , once has its left dependents, starts where the gold yield of starts, so is not in the gold yield of .
The oracle follows . Take a configuration of and look at the next move of .
- If it is LEFT-ARC, it attaches to inside : , and . The oracle tests LEFT-ARC first and chooses it.
- If it is RIGHT-ARC, it attaches to (or a root child to 0): , , , and is complete, since added all gold arcs inside its yield. The LEFT-ARC test fails, because together with would be a cycle. So the oracle chooses RIGHT-ARC.
- If it is SHIFT, then by the shape of the move before it ended one of three blocks: the start of the run or a RIGHT-ARC to the root, so the stack is and no arc move is legal; the end of some with a left dependent of a word not yet pushed (each SHIFT of a word comes right after , or, when , right after what came before ); or the SHIFT of with its LEFT-ARC block, or a RIGHT-ARC inside , with a right dependent still to come. In the second case , whose gold head is in the buffer, so the RIGHT-ARC test fails, and would put in the yield of , which lies to its right, so the LEFT-ARC test fails. In the third case is not complete, so the RIGHT-ARC test fails, and would put in the yield of , so the LEFT-ARC test fails. In all three cases the oracle chooses SHIFT.
So the oracle produces , which builds in moves.
Non-projective trees. Every run ends with a projective tree by Theorem 1, and the oracle adds only gold arcs. So on a non-projective the oracle cannot finish with ; the code reports this as a failure.
Lemma 3 (the cache). Let be split into blocks of columns, one per feature, and let feature select the item with embedding . Then
Proof. is the column of the 48 embeddings stacked in order, so is the sum of the block products, by the rule for multiplying a matrix split into column blocks by a vector split into matching row blocks. The cube is applied after the sum, so storing the block products for each pair and adding them gives the same hidden layer.
Lemma 4 (the gradient of the loss). Let be the set of legal transitions, for , and for a gold . Then for and 0 for , and for and 0 otherwise.
Proof. . The derivative of the second term in is for and 0 for ; the first term gives for . Since , the chain rule gives the second formula.
The tests check Theorem 1 on random sentences and weights, with and without the single-root rule; Lemma 2 on every tree with ; Lemma 3 on every configuration of the example; and Lemma 4 against central finite differences.
Complexity
Time. A parse has steps. In each step, the embedding lookup reads numbers, the first layer takes operations, and the output layer , so a parse takes time, treating 48 as a constant. With the cache hit for every feature, the first layer costs additions, and the time becomes . The feature lookup takes constant time per step if each word keeps its leftmost and rightmost dependents; the code on this site scans the head list instead, for clarity, which adds per step.
Space. for the configuration and for the vectors of one step, besides the model. The model has numbers, and the cache numbers for each stored pair of feature position and item.
Properties
- Dense features. Similar words and tags get similar vectors, so the model can share what it learns between them, which a sparse indicator feature cannot.
- Cube activation. expands into products of up to three inputs, so one hidden unit can model a combination of three features, which feature-based parsers had to write by hand.
- Greedy and projective. It inherits the properties of greedy arc-standard parsing: linear time in , projective trees, and no guarantee of the best sequence.
- Locally normalized. The softmax is computed for each configuration, not for whole sequences, so the score of a parse is a product of local probabilities.
Variants and improvements
- Other transition systems. The same network can choose moves for arc-eager, arc-hybrid or swap parsing; with the swap system the parser can output non-projective trees.
- Dynamic oracle. Training on the parser's own configurations with a dynamic oracle reduces error propagation.
- Beam search and global training. Keeping several configurations with beam search and training the scores of whole sequences addresses the label bias of local normalization; Weiss et al. (2015) and Andor et al. (2016) did this with the same kind of network.
- Recurrent features. Kiperwasser and Goldberg (2016) replaced the embedding features by the outputs of a bidirectional recurrent network over the sentence, so that a few positions suffice. Graph-based parsers with the same encoders, such as the biaffine parser, became the most accurate.
When to use it
Use it for fast greedy dependency parsing on modest hardware, when projective trees are enough and a small model is wanted. When the best accuracy matters more than speed, or non-projective trees are common, a graph-based parser with a recurrent or transformer encoder is better.
Pitfalls
- Stack numbering. The paper numbers the stack from 1, so its is here. Mixing the two conventions shifts every feature.
- The order of dependents. is the second leftmost dependent, not the second closest one; and the label features must use the labels of the same positions as the word features.
- Illegal moves. The network gives a score to every transition. Without a mask, the parser can choose LEFT-ARC on the root or SHIFT on an empty buffer. Choose the best legal move, and normalize over the legal moves only.
- Non-projective training trees. The static oracle gets stuck on a non-projective tree. Skip such trees, make them projective, or use a system that can build them.
- Cube overflow. The cube grows fast, so large first-layer values give very large hidden values. Small initial weights and regularization keep them in range.
- Stale cache. The cache must be recomputed whenever or the embeddings change; use it at test time.
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/chen-manning-parser/. The authors are listed in prov/ZT8KWQ.jsonl.
"""The neural transition-based dependency parser of Chen and Manning (2014).
The parser is greedy arc-standard parsing. At each configuration it reads 48
features, embeds them, and a feedforward network with the cube activation
gives one score per transition:
x = [e(w_1); ...; e(w_18); e(t_1); ...; e(t_18); e(l_1); ...; e(l_12)] (48 d numbers)
h = (W1 x + b1) ** 3 (H numbers, cube per entry)
z = W2 h (one logit per transition)
The parser takes the legal transition with the largest logit. Training uses the
cross-entropy of the softmax of z over the legal transitions; the gold
transitions come from the "shortest stack" oracle, which prefers LEFT-ARC.
The words are 1..n and 0 is the root. The stack starts as [0]; s0 is its top,
s1 and s2 are under it; b0, b1, b2 are the first three buffer words. (Chen and
Manning number them from 1: their s1 is s0 here.) lc1(w) and lc2(w) are the
leftmost and second leftmost dependents of w, rc1(w) and rc2(w) the rightmost
and second rightmost.
This module takes the weights as given (from a seeded generator in the tests).
It implements the features, one forward pass, the pre-computation trick, the
greedy parser, the oracle and the loss with its gradient in W2; it does not
train the network.
"""
import math
import random
from typing import Dict, List, Optional, Sequence, Tuple
from nlslog import NEG_INF, log_softmax
NULL, ROOT, UNK = "<NULL>", "<ROOT>", "<UNK>"
class Vocab:
"""Strings to ids; ids 0, 1 and 2 are NULL, ROOT and UNK."""
def __init__(self, items: Sequence[str]):
self.items: List[str] = [NULL, ROOT, UNK]
self.ids: Dict[str, int] = {s: i for i, s in enumerate(self.items)}
for s in items:
if s not in self.ids:
self.ids[s] = len(self.items)
self.items.append(s)
def __len__(self) -> int:
return len(self.items)
def id(self, s: str) -> int:
return self.ids.get(s, self.ids[UNK])
class Config:
def __init__(self, n: int):
self.n = n
self.stack: List[int] = [0]
self.next = 1
self.heads = [-1] * (n + 1)
self.labels: List[Optional[str]] = [None] * (n + 1)
def is_terminal(self) -> bool:
return self.next > self.n and len(self.stack) == 1
def copy(self) -> "Config":
c = Config(self.n)
c.stack = list(self.stack)
c.next = self.next
c.heads = list(self.heads)
c.labels = list(self.labels)
return c
def transitions(labels: Sequence[str]) -> List[Tuple[str, Optional[str]]]:
"""Index 0 is SHIFT, then LEFT-ARC with each label, then RIGHT-ARC with each label."""
return [("SH", None)] + [("LA", l) for l in labels] + [("RA", l) for l in labels]
def is_legal(c: Config, t, single_root: bool = False) -> bool:
kind = t[0]
if kind == "SH":
return c.next <= c.n
if len(c.stack) < 2:
return False
if kind == "LA":
return c.stack[-2] != 0
if single_root and c.stack[-2] == 0:
return c.next > c.n
return True
def apply(c: Config, t) -> None:
kind, label = t
if kind == "SH":
c.stack.append(c.next)
c.next += 1
elif kind == "LA":
s0 = c.stack.pop()
s1 = c.stack.pop()
c.heads[s1], c.labels[s1] = s0, label
c.stack.append(s0)
else:
s0 = c.stack.pop()
c.heads[s0], c.labels[s0] = c.stack[-1], label
def _left_kids(c: Config, w: int) -> List[int]:
return [d for d in range(1, w) if c.heads[d] == w]
def _right_kids(c: Config, w: int) -> List[int]:
return [d for d in range(c.n, w, -1) if c.heads[d] == w]
def _kid(kids: List[int], i: int) -> Optional[int]:
return kids[i - 1] if len(kids) >= i else None
def lc(c: Config, w: Optional[int], i: int) -> Optional[int]:
return None if w is None else _kid(_left_kids(c, w), i)
def rc(c: Config, w: Optional[int], i: int) -> Optional[int]:
return None if w is None else _kid(_right_kids(c, w), i)
def feature_positions(c: Config) -> Tuple[List[Optional[int]], List[Optional[int]]]:
"""Return the 18 word positions (also used for the tags) and the 12 label positions.
None is a missing element. The 18 are s0, s1, s2, b0, b1, b2, then for
s in (s0, s1): lc1(s), rc1(s), lc2(s), rc2(s), lc1(lc1(s)), rc1(rc1(s)).
The 12 label positions are the last 12 of these.
"""
st = [c.stack[-k] if len(c.stack) >= k else None for k in (1, 2, 3)]
bu = [c.next + k if c.next + k <= c.n else None for k in (0, 1, 2)]
kids: List[Optional[int]] = []
for s in st[:2]:
kids += [lc(c, s, 1), rc(c, s, 1), lc(c, s, 2), rc(c, s, 2), lc(c, lc(c, s, 1), 1), rc(c, rc(c, s, 1), 1)]
return st + bu + kids, kids
def features(c: Config, words: Sequence[str], tags: Sequence[str], wv: Vocab, tv: Vocab, lv: Vocab) -> List[int]:
"""Return the 48 feature ids: 18 words, 18 tags, 12 labels. words[0] and tags[0] are unused."""
pos, kids = feature_positions(c)
def tok(p, seq, v):
if p is None:
return v.id(NULL)
if p == 0:
return v.id(ROOT)
return v.id(seq[p])
fw = [tok(p, words, wv) for p in pos]
ft = [tok(p, tags, tv) for p in pos]
fl = [lv.id(NULL) if p is None else lv.id(c.labels[p]) for p in kids]
return fw + ft + fl
class Model:
"""Embeddings E_w, E_t, E_l (d numbers each), W1 (H x 48d), b1 (H), W2 (T x H)."""
def __init__(self, n_words: int, n_tags: int, n_labels: int, d: int, hidden: int, n_trans: int, rng: random.Random, scale: float = 0.5):
def mat(r, k):
return [[rng.uniform(-scale, scale) for _ in range(k)] for _ in range(r)]
self.d, self.hidden = d, hidden
self.Ew, self.Et, self.El = mat(n_words, d), mat(n_tags, d), mat(n_labels, d)
self.W1 = mat(hidden, 48 * d)
self.b1 = [rng.uniform(-scale, scale) for _ in range(hidden)]
self.W2 = mat(n_trans, hidden)
def table(self, k: int):
"""The embedding table of feature number k (0..47)."""
return self.Ew if k < 18 else self.Et if k < 36 else self.El
def embed(self, f: Sequence[int]) -> List[float]:
x: List[float] = []
for k, v in enumerate(f):
x += self.table(k)[v]
return x
def hidden_layer(self, x: Sequence[float]) -> List[float]:
return [(math.fsum(w * a for w, a in zip(row, x)) + b) ** 3 for row, b in zip(self.W1, self.b1)]
def logits(self, h: Sequence[float]) -> List[float]:
return [math.fsum(w * a for w, a in zip(row, h)) for row in self.W2]
def forward(self, f: Sequence[int]) -> Tuple[List[float], List[float]]:
h = self.hidden_layer(self.embed(f))
return h, self.logits(h)
def precompute(model: Model, ids_per_feature: Sequence[Sequence[int]]):
"""The pre-computation trick: store W1[:, block k] E[v] for feature k and id v.
Chen and Manning store these products for the most frequent words; then the
first layer is H * 48 additions per configuration instead of H * 48 d
multiplications.
"""
d = model.d
pre = []
for k, ids in enumerate(ids_per_feature):
tab = model.table(k)
cols = range(k * d, (k + 1) * d)
pre.append({v: [math.fsum(row[j] * tab[v][j - k * d] for j in cols) for row in model.W1] for v in ids})
return pre
def hidden_from_precomputed(model: Model, pre, f: Sequence[int]) -> List[float]:
z = list(model.b1)
for k, v in enumerate(f):
z = [a + b for a, b in zip(z, pre[k][v])]
return [a ** 3 for a in z]
def legal_log_probs(z: Sequence[float], legal: Sequence[bool]) -> List[float]:
"""Log softmax of the logits over the legal transitions; NEG_INF for the others."""
idx = [i for i, ok in enumerate(legal) if ok]
lp = log_softmax([z[i] for i in idx])
out = [NEG_INF] * len(z)
for i, v in zip(idx, lp):
out[i] = v
return out
def parse(model: Model, words, tags, wv: Vocab, tv: Vocab, lv: Vocab, labels: Sequence[str], single_root: bool = False):
"""Greedy parsing. Returns (heads, labels, transitions, total log probability)."""
trans = transitions(labels)
n = len(words) - 1
c = Config(n) # @line L1
seq, total = [], 0.0
while not c.is_terminal(): # @line L2
f = features(c, words, tags, wv, tv, lv) # @line L3
_, z = model.forward(f) # @line L4
legal = [is_legal(c, t, single_root) for t in trans]
lp = legal_log_probs(z, legal) # @line L5
best = max((i for i in range(len(trans)) if legal[i]), key=lambda i: z[i]) # @line L6
total += lp[best]
apply(c, trans[best]) # @line L7
seq.append(trans[best])
return c.heads, c.labels, seq, total # @line L8
def exhaustive_best(model: Model, words, tags, wv: Vocab, tv: Vocab, lv: Vocab, labels: Sequence[str], single_root: bool = False):
"""The complete sequence with the largest total log probability, by search over all sequences."""
trans = transitions(labels)
n = len(words) - 1
best = [NEG_INF, None]
def go(c, total, seq):
if c.is_terminal():
if total > best[0]:
best[0], best[1] = total, (list(c.heads), list(seq))
return
_, z = model.forward(features(c, words, tags, wv, tv, lv))
legal = [is_legal(c, t, single_root) for t in trans]
lp = legal_log_probs(z, legal)
for i, t in enumerate(trans):
if legal[i]:
c2 = c.copy()
apply(c2, t)
seq.append(t)
go(c2, total + lp[i], seq)
seq.pop()
go(Config(n), 0.0, [])
return best[0], best[1][0], best[1][1]
def shortest_stack_oracle(c: Config, gold_heads: Sequence[int], gold_labels: Sequence[Optional[str]]):
"""LEFT-ARC if the gold head of s1 is s0; RIGHT-ARC if the gold head of s0 is s1 and s0 has
all its dependents; else SHIFT. Return None when no move is right (a non-projective tree)."""
if len(c.stack) >= 2:
s1, s0 = c.stack[-2], c.stack[-1]
if s1 != 0 and gold_heads[s1] == s0:
return ("LA", gold_labels[s1])
if gold_heads[s0] == s1 and all(c.heads[d] == s0 for d in range(1, c.n + 1) if gold_heads[d] == s0):
return ("RA", gold_labels[s0])
return ("SH", None) if c.next <= c.n else None
def training_examples(words, tags, gold_heads, gold_labels, wv: Vocab, tv: Vocab, lv: Vocab):
"""The (features, gold transition) pairs along the oracle sequence of a projective tree."""
n = len(words) - 1
c = Config(n)
out = []
while not c.is_terminal():
t = shortest_stack_oracle(c, gold_heads, gold_labels)
if t is None:
raise ValueError("the gold tree is not projective")
out.append((features(c, words, tags, wv, tv, lv), t, c.copy()))
apply(c, t)
if c.heads != list(gold_heads):
raise ValueError("the gold tree is not projective")
return out
def loss_and_grad_W2(model: Model, f: Sequence[int], legal: Sequence[bool], gold: int):
"""Cross-entropy -log p(gold) over the legal transitions, and its gradient in W2.
d loss / d W2[t][j] = (p_t - [t = gold]) h_j for legal t, and 0 for the others.
"""
h, z = model.forward(f)
lp = legal_log_probs(z, legal)
loss = -lp[gold]
grad = []
for t in range(len(z)):
g = (math.exp(lp[t]) if legal[t] else 0.0) - (1.0 if t == gold else 0.0)
grad.append([g * a for a in h])
return loss, grad
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_chen_manning_parser.py 201 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chen-manning-parser/. The authors are listed in prov/ZT8KWQ.jsonl.
import itertools
import math
import random
import pytest
from chen_manning_parser import (
NULL,
ROOT,
Config,
Model,
Vocab,
apply,
exhaustive_best,
feature_positions,
features,
hidden_from_precomputed,
is_legal,
legal_log_probs,
loss_and_grad_W2,
parse,
precompute,
shortest_stack_oracle,
training_examples,
transitions,
)
from nlslog import NEG_INF
WORDS = [None, "the", "cat", "sat", "on", "the", "mat"]
TAGS = [None, "DET", "NOUN", "VERB", "ADP", "DET", "NOUN"]
GOLD_HEADS = [-1, 2, 3, 0, 6, 6, 3]
GOLD_LABELS = [None, "det", "nsubj", "root", "case", "det", "obl"]
LABELS = ["det", "nsubj", "root", "case", "obl"]
WV, TV, LV = Vocab(WORDS[1:]), Vocab(TAGS[1:]), Vocab(LABELS)
def is_tree(heads):
n = len(heads) - 1
for d in range(1, n + 1):
x, steps = d, 0
while x != 0:
x, steps = heads[x], steps + 1
if x == -1 or steps > n:
return False
return True
def is_projective(heads):
n = len(heads) - 1
for d in range(1, n + 1):
h = heads[d]
for k in range(min(h, d) + 1, max(h, d)):
x = k
while x != h and x != 0:
x = heads[x]
if x != h:
return False
return True
def run(seq_names, n=6):
c = Config(n)
for name in seq_names:
kind, _, lab = name.partition("-")
apply(c, (kind, lab or None))
return c
def test_vocab_specials():
assert [WV.id(NULL), WV.id(ROOT), WV.id("zebra")] == [0, 1, 2]
assert WV.id("the") == 3 and len(WV) == 3 + 5
def test_feature_positions_on_the_example():
c = run(["SH", "SH", "LA-det", "SH"])
words_pos, label_pos = feature_positions(c)
assert words_pos[:6] == [3, 2, 0, 4, 5, 6]
assert words_pos[6:12] == [None] * 6 # "sat" has no dependent yet
assert words_pos[12:] == [1, None, None, None, None, None] # lc1(cat) = the
assert label_pos == words_pos[6:]
f = features(c, WORDS, TAGS, WV, TV, LV)
assert len(f) == 48
assert f[:6] == [WV.id("sat"), WV.id("cat"), WV.id(ROOT), WV.id("on"), WV.id("the"), WV.id("mat")]
assert f[18:21] == [TV.id("VERB"), TV.id("NOUN"), TV.id(ROOT)]
assert f[36:] == [LV.id(NULL)] * 6 + [LV.id("det")] + [LV.id(NULL)] * 5
def test_second_children_and_grandchildren():
c = Config(6)
c.stack, c.next = [0, 3], 7
c.heads = [-1, 2, 3, -1, 3, 6, 3] # 3 has left 2 (with 1 under it), right 4 and 6 (with 5 under it)
words_pos, _ = feature_positions(c)
assert words_pos[6:12] == [2, 6, None, 4, 1, None]
c.heads[1] = 3
words_pos, _ = feature_positions(c)
assert words_pos[6:12] == [1, 6, 2, 4, None, None]
def test_oracle_sequence_and_projectivity():
ex = training_examples(WORDS, TAGS, GOLD_HEADS, GOLD_LABELS, WV, TV, LV)
names = [t[0] if t[1] is None else f"{t[0]}-{t[1]}" for _, t, _ in ex]
assert names == ["SH", "SH", "LA-det", "SH", "LA-nsubj", "SH", "SH", "SH", "LA-det", "LA-case", "RA-obl", "RA-root"]
for n in range(1, 6):
words, tags = [None] + ["w"] * n, [None] + ["t"] * n
for hs in itertools.product(range(n + 1), repeat=n):
heads = [-1] + list(hs)
if not is_tree(heads):
continue
labels = [None] + ["dep"] * n
if is_projective(heads):
assert len(training_examples(words, tags, heads, labels, Vocab(["w"]), Vocab(["t"]), Vocab(["dep"]))) == 2 * n
else:
with pytest.raises(ValueError):
training_examples(words, tags, heads, labels, Vocab(["w"]), Vocab(["t"]), Vocab(["dep"]))
def test_cube_activation_and_precomputation():
rng = random.Random(1)
trans = transitions(LABELS)
m = Model(len(WV), len(TV), len(LV), 4, 6, len(trans), rng)
ex = training_examples(WORDS, TAGS, GOLD_HEADS, GOLD_LABELS, WV, TV, LV)
pre = precompute(m, [range(len(WV))] * 18 + [range(len(TV))] * 18 + [range(len(LV))] * 12)
for f, _, _ in ex:
h, _ = m.forward(f)
h2 = hidden_from_precomputed(m, pre, f)
assert all(abs(a - b) <= 1e-9 * max(1.0, abs(a)) for a, b in zip(h, h2))
m.W1 = [[0.0] * (48 * 4) for _ in range(6)]
m.b1 = [1.0, -2.0, 0.5, 0.0, 3.0, -1.0]
h, _ = m.forward(ex[0][0])
assert h == [1.0, -8.0, 0.125, 0.0, 27.0, -1.0]
def test_softmax_over_legal_transitions():
z = [2.0, 1.0, -1.0, 0.5]
lp = legal_log_probs(z, [True, False, True, True])
assert lp[1] == NEG_INF
assert abs(math.fsum(math.exp(v) for v in lp) - 1.0) <= 1e-12
assert abs(lp[0] - lp[3] - 1.5) <= 1e-12
def test_greedy_parser_gives_projective_trees():
rng = random.Random(2)
for trial in range(30):
n = rng.randint(1, 7)
words = [None] + [rng.choice(WORDS[1:]) for _ in range(n)]
tags = [None] + [rng.choice(TAGS[1:]) for _ in range(n)]
m = Model(len(WV), len(TV), len(LV), 3, 5, len(transitions(LABELS)), random.Random(trial))
single = trial % 2 == 1
heads, labels, seq, total = parse(m, words, tags, WV, TV, LV, LABELS, single_root=single)
assert len(seq) == 2 * n and is_tree(heads) and is_projective(heads)
assert all(labels[d] in LABELS for d in range(1, n + 1))
if single:
assert sum(1 for d in range(1, n + 1) if heads[d] == 0) == 1
assert total <= 0.0
def test_greedy_is_not_exact():
words, tags = [None, "the", "cat", "sat", "down"], [None, "DT", "NN", "VBD", "RP"]
wv, tv, lv = Vocab(words[1:]), Vocab(tags[1:]), Vocab(["dep"])
worse = 0
for seed in range(12):
m = Model(len(wv), len(tv), len(lv), 3, 5, 3, random.Random(seed))
_, _, _, greedy = parse(m, words, tags, wv, tv, lv, ["dep"])
best, heads, seq = exhaustive_best(m, words, tags, wv, tv, lv, ["dep"])
assert best >= greedy - 1e-12 and len(seq) == 8 and is_projective(heads)
worse += best > greedy + 1e-9
m = Model(len(wv), len(tv), len(lv), 3, 5, 3, random.Random(10))
_, _, _, greedy = parse(m, words, tags, wv, tv, lv, ["dep"])
best, _, _ = exhaustive_best(m, words, tags, wv, tv, lv, ["dep"])
assert best > greedy + 0.1
assert worse >= 1
def test_gradient_in_W2_by_finite_differences():
rng = random.Random(5)
trans = transitions(LABELS)
m = Model(len(WV), len(TV), len(LV), 3, 4, len(trans), rng)
ex = training_examples(WORDS, TAGS, GOLD_HEADS, GOLD_LABELS, WV, TV, LV)
f, t, c = ex[4]
legal = [is_legal(c, u) for u in trans]
gold = trans.index(t)
loss, grad = loss_and_grad_W2(m, f, legal, gold)
eps = 1e-6
for i in range(len(trans)):
for j in range(4):
old = m.W2[i][j]
m.W2[i][j] = old + eps
up, _ = loss_and_grad_W2(m, f, legal, gold)
m.W2[i][j] = old - eps
down, _ = loss_and_grad_W2(m, f, legal, gold)
m.W2[i][j] = old
assert abs((up - down) / (2 * eps) - grad[i][j]) <= 1e-6 * max(1.0, abs(grad[i][j]))
assert loss > 0
def test_oracle_prefers_left_arc():
c = run(["SH", "SH"])
assert shortest_stack_oracle(c, GOLD_HEADS, GOLD_LABELS) == ("LA", "det")
History
Transition-based parsers before 2014 used linear classifiers over millions of sparse indicator features, built from hand-made templates that combined words, tags and labels near the stack top; computing these features took most of the parse time. Chen and Manning (2014) replaced them by 48 dense embeddings and one hidden layer, and reported better accuracy and higher speed than the feature-based parsers of the time. Later work added beam search and global normalization, and replaced the hand-chosen positions by recurrent encoders.
References
- Danqi Chen and Christopher D. Manning, A fast and accurate dependency parser using neural networks, EMNLP 2014, the arc-standard system, the 48 features, the embedding and cube layers, the softmax output, training by cross-entropy, and the pre-computation trick
- Joakim Nivre, Algorithms for deterministic incremental dependency parsing, Computational Linguistics 34(4), 513-553, 2008, the arc-standard system and its properties
- Sandra Kübler, Ryan McDonald and Joakim Nivre, Dependency Parsing, Synthesis Lectures on Human Language Technologies, Morgan and Claypool, 2009, Chapter 3, Transition-Based Parsing (feature-based classifiers and oracles)
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 ZT8KWQ Edit this page History Report an error Markdown