Algorithm Search⌘K

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.

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
Properties
deterministicofflineiterative
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 g(x)=x3g(x) = x^3, 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 w1⋯wnw_1 \cdots w_n 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 s0,s1,s2s_0, s_1, s_2 be the top three stack words and b0,b1,b2b_0, b_1, b_2 the first three buffer words. For a word ww, lc1(w)lc_1(w) and lc2(w)lc_2(w) are its leftmost and second leftmost dependents attached so far, and rc1(w)rc_1(w), rc2(w)rc_2(w) the rightmost and second rightmost. The 18 word positions are

s0,s1,s2,b0,b1,b2, and for s∈{s0,s1}:lc1(s),rc1(s),lc2(s),rc2(s),lc1(lc1(s)),rc1(rc1(s)).s_0, s_1, s_2, b_0, b_1, b_2, \text{ and for } s \in \{s_0, s_1\}: lc_1(s), rc_1(s), lc_2(s), rc_2(s), lc_1(lc_1(s)), rc_1(rc_1(s)).

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 kk selects a column of its embedding table, EwE^w, EtE^t or ElE^l, each with dd rows. The 48 vectors are joined into x∈R48dx \in \mathbb{R}^{48d}, and

h=(W1x+b1)3 (per entry),z=W2h,p(t∣c)=ezt∑u legalezu.h = (W_1 x + b_1)^3 \ \text{(per entry)}, \qquad z = W_2 h, \qquad p(t \mid c) = \frac{e^{z_t}}{\sum_{u \text{ legal}} e^{z_u}}.
  1. CHEN-MANNING-PARSE(words, tags, network)
  2. 1c <- ([0], [1, ..., n], {})
  3. 2while c is not terminal do
  4. 3f <- the 48 feature ids of c
  5. 4x <- the joined embeddings of f; h <- (W1 x + b1)^3; z <- W2 h
  6. 5log p <- the log softmax of z over the legal transitions of c
  7. 6t <- the legal transition with the largest z
  8. 7c <- t(c)
  9. 8return 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 s1s_1 is s0s_0; RIGHT-ARC if the gold head of s0s_0 is s1s_1 and s0s_0 has all its gold dependents; SHIFT otherwise. The loss is the cross-entropy −log⁡p(t∗∣c)-\log p(t^\ast \mid c) of the gold transition, summed over all examples, with L2 regularization. The gradient flows by backpropagation through W2W_2, W1W_1 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. W1x=∑k=148W1(k)ekW_1 x = \sum_{k=1}^{48} W_1^{(k)} e_k, where W1(k)W_1^{(k)} is the block of columns of feature kk and eke_k its embedding. For a fixed feature position kk and a frequent item vv, the vector W1(k)E:,vW_1^{(k)} E_{:,v} can be computed once and stored. Then the first layer is a sum of 48 stored vectors of length HH, 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-ARCdet_{det}, SHIFT, the stack is 0, cat, sat and the buffer is on the mat. Some of the 48 features:

position word tag label
s0s_0 sat VERB
s1s_1 cat NOUN
s2s_2 ROOT ROOT
b0,b1,b2b_0, b_1, b_2 on, the, mat ADP, DET, NOUN
lc1(s0)lc_1(s_0) NULL NULL NULL
lc1(s1)lc_1(s_1) the DET det
the other 10 dependents NULL NULL NULL

The gold move here is LEFT-ARCnsubj_{nsubj}, 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, d=3d = 3, H=5H = 5 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 −1.731-1.731. A search over all complete sequences finds SH, SH, SH, SH, LA, LA, LA, RA, with about −1.406-1.406. 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 2n2n 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 2n2n 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 n≤5n \le 5.

The cache is exact. The first layer is linear in the joined vector, so the sum of the stored blocks equals W1xW_1 x 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 SS, ∂(−log⁡pt∗)/∂zt=pt−[t=t∗]\partial(-\log p_{t^\ast}) / \partial z_t = p_t - [t = t^\ast] for t∈St \in S, and 0 outside SS. So the gradient in W2W_2 is (p−et∗)h⊤(p - e_{t^\ast}) h^\top 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 1,…,n1, \ldots, n and 0 is the root. The parser runs the arc-standard system: SHIFT, LEFT-ARCl_l (needs s1≠0s_1 \ne 0) and RIGHT-ARCl_l (under the single-root rule, from s1=0s_1 = 0 only with an empty buffer). The network gives a real number ztz_t to every transition tt; the parser takes a legal tt with the largest ztz_t.

Theorem 1 (termination and output). For every choice of weights, the parser stops after exactly 2n2n 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 2n2n 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. □\square

Lemma 2 (the oracle). For a projective gold tree GG, the static oracle (LEFT-ARC if h∗(s1)=s0h^\ast(s_1) = s_0; RIGHT-ARC if h∗(s0)=s1h^\ast(s_0) = s_1 and s0s_0 has all its gold dependents; SHIFT otherwise) gives a legal sequence of 2n2n moves that builds GG. For a non-projective tree it gets stuck.

Proof. We first build a run RR that produces GG, and then show that the oracle chooses the next move of RR in every configuration of RR.

Construction. For a word vv with gold left dependents l1<⋯<lal_1 < \cdots < l_a and right dependents r1<⋯<rmr_1 < \cdots < r_m, let

SEQ(v)=SEQ(l1)⋯SEQ(la) SHIFT LEFT-ARCa SEQ(r1) RIGHT-ARC⋯SEQ(rm) RIGHT-ARC\mathrm{SEQ}(v) = \mathrm{SEQ}(l_1) \cdots \mathrm{SEQ}(l_a)\ \text{SHIFT}\ \text{LEFT-ARC}^{a}\ \mathrm{SEQ}(r_1)\ \text{RIGHT-ARC} \cdots \mathrm{SEQ}(r_m)\ \text{RIGHT-ARC}

where SHIFT pushes vv and the LEFT-ARC moves attach la,…,l1l_a, \ldots, l_1 to vv in turn. Since GG is projective, the yields of l1,…,la,v,r1,…,rml_1, \ldots, l_a, v, r_1, \ldots, r_m 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 vv, then SEQ(v)\mathrm{SEQ}(v) is legal, pushes vv 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 SEQ(c1)\mathrm{SEQ}(c_1) RIGHT-ARC ⋯\cdots SEQ(cm)\mathrm{SEQ}(c_m) RIGHT-ARC for the root children c1<⋯<cmc_1 < \cdots < c_m; it has one SHIFT and one arc per word, 2n2n moves.

In every configuration of RR, the stack yields YA(v0),…,YA(vk)Y_A(v_0), \ldots, Y_A(v_k) are consecutive intervals in stack order, as in every arc-standard run. So the word s1s_1 below the top lies to the left of YA(s0)Y_A(s_0). In RR, once s0s_0 has its left dependents, YA(s0)Y_A(s_0) starts where the gold yield of s0s_0 starts, so s1s_1 is not in the gold yield of s0s_0.

The oracle follows RR. Take a configuration of RR and look at the next move of RR.

  • If it is LEFT-ARC, it attaches lil_i to vv inside SEQ(v)\mathrm{SEQ}(v): s0=vs_0 = v, s1=li≠0s_1 = l_i \ne 0 and h∗(s1)=s0h^\ast(s_1) = s_0. The oracle tests LEFT-ARC first and chooses it.
  • If it is RIGHT-ARC, it attaches rjr_j to vv (or a root child cjc_j to 0): s0=rjs_0 = r_j, s1=vs_1 = v, h∗(s0)=s1h^\ast(s_0) = s_1, and s0s_0 is complete, since SEQ(rj)\mathrm{SEQ}(r_j) added all gold arcs inside its yield. The LEFT-ARC test fails, because h∗(v)=rjh^\ast(v) = r_j together with h∗(rj)=vh^\ast(r_j) = v would be a cycle. So the oracle chooses RIGHT-ARC.
  • If it is SHIFT, then by the shape of RR 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 [0][0] and no arc move is legal; the end of some SEQ(u)\mathrm{SEQ}(u) with uu a left dependent of a word not yet pushed (each SHIFT of a word vv comes right after SEQ(la)\mathrm{SEQ}(l_a), or, when a=0a = 0, right after what came before SEQ(v)\mathrm{SEQ}(v)); or the SHIFT of vv with its LEFT-ARC block, or a RIGHT-ARC inside SEQ(v)\mathrm{SEQ}(v), with a right dependent rjr_j still to come. In the second case s0=us_0 = u, whose gold head is in the buffer, so the RIGHT-ARC test fails, and h∗(s1)=uh^\ast(s_1) = u would put s1s_1 in the yield of uu, which lies to its right, so the LEFT-ARC test fails. In the third case s0=vs_0 = v is not complete, so the RIGHT-ARC test fails, and h∗(s1)=vh^\ast(s_1) = v would put s1s_1 in the yield of vv, so the LEFT-ARC test fails. In all three cases the oracle chooses SHIFT.

So the oracle produces RR, which builds GG in 2n2n 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 GG the oracle cannot finish with A=GA = G; the code reports this as a failure. □\square

Lemma 3 (the cache). Let W1=[W1(1)⋯W1(48)]W_1 = [W_1^{(1)} \cdots W_1^{(48)}] be split into blocks of dd columns, one per feature, and let feature kk select the item vkv_k with embedding E:,vk(k)E^{(k)}_{:, v_k}. Then

W1x+b1=b1+∑k=148W1(k)E:,vk(k).W_1 x + b_1 = b_1 + \sum_{k=1}^{48} W_1^{(k)} E^{(k)}_{:, v_k}.

Proof. xx is the column of the 48 embeddings stacked in order, so W1xW_1 x 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 (k,v)(k, v) and adding them gives the same hidden layer. □\square

Lemma 4 (the gradient of the loss). Let SS be the set of legal transitions, pt=ezt/∑u∈Sezup_t = e^{z_t} / \sum_{u \in S} e^{z_u} for t∈St \in S, and ℓ=−log⁡pt∗\ell = -\log p_{t^\ast} for a gold t∗∈St^\ast \in S. Then ∂ℓ/∂zt=pt−[t=t∗]\partial \ell / \partial z_t = p_t - [t = t^\ast] for t∈St \in S and 0 for t∉St \notin S, and ∂ℓ/∂(W2)tj=(pt−[t=t∗])hj\partial \ell / \partial (W_2)_{tj} = (p_t - [t = t^\ast]) h_j for t∈St \in S and 0 otherwise.

Proof. ℓ=−zt∗+log⁡∑u∈Sezu\ell = -z_{t^\ast} + \log \sum_{u \in S} e^{z_u}. The derivative of the second term in ztz_t is ezt/∑u∈Sezu=pte^{z_t} / \sum_{u \in S} e^{z_u} = p_t for t∈St \in S and 0 for t∉St \notin S; the first term gives −1-1 for t=t∗t = t^\ast. Since zt=∑j(W2)tjhjz_t = \sum_j (W_2)_{tj} h_j, the chain rule gives the second formula. □\square

The tests check Theorem 1 on random sentences and weights, with and without the single-root rule; Lemma 2 on every tree with n≤5n \le 5; Lemma 3 on every configuration of the example; and Lemma 4 against central finite differences.

Complexity

Time. A parse has 2n2n steps. In each step, the embedding lookup reads 48d48d numbers, the first layer takes Θ(48dH)\Theta(48dH) operations, and the output layer Θ(TH)\Theta(TH), so a parse takes Θ(nH(d+T))\Theta(nH(d + T)) time, treating 48 as a constant. With the cache hit for every feature, the first layer costs Θ(48H)\Theta(48H) additions, and the time becomes Θ(nH(1+T))\Theta(nH(1 + T)). 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 O(n)O(n) per step.

Space. Θ(n)\Theta(n) for the configuration and Θ(d+H+T)\Theta(d + H + T) for the vectors of one step, besides the model. The model has (∣Vw∣+∣Vt∣+∣Vl∣)d+48dH+H+TH(|V_w| + |V_t| + |V_l|)d + 48dH + H + TH numbers, and the cache HH 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. (a1x1+⋯+amxm+b)3(a_1 x_1 + \cdots + a_m x_m + b)^3 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 nn, 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 s1s_1 is s0s_0 here. Mixing the two conventions shifts every feature.
  • The order of dependents. lc2lc_2 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 W1W_1 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.

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

  1. 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
  2. Joakim Nivre, Algorithms for deterministic incremental dependency parsing, Computational Linguistics 34(4), 513-553, 2008, the arc-standard system and its properties
  3. 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.

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
  • a scene preset for the example