Algorithm Search⌘K

Algorithmcore

Arc-standard parsing

Also called arc-standard transition system.

Transition-based dependency parsing with a stack, a buffer and the moves shift, left-arc and right-arc between the two top stack words.

Time
Θ(n) worst · best
Space
Θ(n) extra
Where
n = the number of words, with a scorer of constant cost for each of a fixed number of transitions
Properties
deterministicofflineiterative
Origin
Joakim Nivre, Hiroyasu Yamada, Yuji Matsumoto, 2004

Arc-standard parsing builds a dependency tree by reading the sentence from left to right with a stack of partly processed words and a buffer of words still to come. There are three moves. SHIFT pushes the next word onto the stack. LEFT-ARC makes the top word the head of the word below it and removes the lower word. RIGHT-ARC makes the second word the head of the top word and removes the top word. A classifier chooses the move in each configuration, and the parser simply takes the move with the highest score, so the whole parse is 2n2n moves for nn words: one shift and one arc for each word. The system builds exactly the projective trees, bottom up, since a word gets its head only after it has all its own dependents. It is the system of Nivre (2004, 2008), close to the parser of Yamada and Matsumoto (2003), and it is the base of the Chen-Manning parser and the arc-eager, arc-hybrid and swap systems.

In plain words

Read the words one at a time and put each one on a pile. Look at the two words on top of the pile. If the top word governs the word below it, draw that arrow and take the lower word out; it is finished. If the lower word governs the top word, and the top word has already collected all its own dependents, draw that arrow and take the top word out. Otherwise read the next word onto the pile. At the end only the start symbol is left, and every word has exactly one arrow into it. A trained classifier makes these choices; it looks at the words near the top of the pile and at the next words to be read.

The problem

The input is a sentence w1⋯wnw_1 \cdots w_n, with tags and other features, and a scoring function that gives each legal transition in a configuration a number; it is usually a trained classifier. The output is a dependency tree with labels. The goal of training is that the greedy choices rebuild the gold trees of a treebank. The system can build only projective trees; on a non-projective gold tree its static oracle gets stuck. In the main version the root may get any number of children. In the single-root version, RIGHT-ARC from the root is allowed only when the buffer is empty, so the root gets exactly one child.

The algorithm

A configuration is a triple (σ,β,A)(\sigma, \beta, A): the stack σ\sigma, written with its top on the right, the buffer β\beta, written with its front on the left, and the set AA of labeled arcs built so far. The initial configuration is ([0],[1,…,n],∅)([0], [1, \ldots, n], \emptyset), and the terminal ones are ([0],[ ],A)([0], [\,], A). The transitions, for each label ll:

transition before after condition
SHIFT (σ,b∣β,A)(\sigma, b \mid \beta, A) (σ∣b,β,A)(\sigma \mid b, \beta, A) buffer not empty
LEFT-ARCl_l (σ∣s1∣s0,β,A)(\sigma \mid s_1 \mid s_0, \beta, A) (σ∣s0,β,A∪{s0→ls1})(\sigma \mid s_0, \beta, A \cup \{s_0 \xrightarrow{l} s_1\}) s1≠0s_1 \ne 0
RIGHT-ARCl_l (σ∣s1∣s0,β,A)(\sigma \mid s_1 \mid s_0, \beta, A) (σ∣s1,β,A∪{s1→ls0})(\sigma \mid s_1, \beta, A \cup \{s_1 \xrightarrow{l} s_0\}) (single root: s1≠0s_1 \ne 0 or β\beta empty)

The greedy parser:

  1. ARC-STANDARD-PARSE(x, score)
  2. 1c <- ([0], [1, ..., n], {})
  3. 2while c is not terminal do
  4. 3T <- the legal transitions of c
  5. 4t <- argmax over t in T of score(c, t)
  6. 5if t = SHIFT then move the front of the buffer onto the stack
  7. 6if t = LEFT-ARC_l then add s0 -l-> s1 and remove s1 from the stack
  8. 7if t = RIGHT-ARC_l then add s1 -l-> s0 and remove s0 from the stack
  9. 8return the tree A

Ties in line L4 go to the first transition in the order SHIFT, LEFT-ARC, RIGHT-ARC, with the labels in a fixed order.

The static oracle. For training, the oracle turns each gold tree into one sequence of transitions, and the classifier learns the pairs of configuration and transition. In configuration cc with top words s1,s0s_1, s_0: choose LEFT-ARC if s1s_1 is a gold dependent of s0s_0; choose RIGHT-ARC if s0s_0 is a gold dependent of s1s_1 and all gold dependents of s0s_0 already have their head; else SHIFT.

Example

Parse the cat sat on the mat (words 1 to 6), with the gold heads [-1, 2, 3, 0, 6, 6, 3]. The oracle gives 12 transitions:

step transition stack buffer new arc
0 0 1 2 3 4 5 6
1 SH 0 1 2 3 4 5 6
2 SH 0 1 2 3 4 5 6
3 LA-det 0 2 3 4 5 6 cat →\to the
4 SH 0 2 3 4 5 6
5 LA-nsubj 0 3 4 5 6 sat →\to cat
6 SH 0 3 4 5 6
7 SH 0 3 4 5 6
8 SH 0 3 4 5 6
9 LA-det 0 3 4 6 mat →\to the
10 LA-case 0 3 6 mat →\to on
11 RA-obl 0 3 sat →\to mat
12 RA-root 0 root →\to sat

At step 6, sat is on top and mat is still in the buffer. RIGHT-ARC cannot attach mat yet, because mat is not on the stack; and sat must stay, because it still needs mat as a dependent. The arc sat →\to mat comes only at step 11, after mat has collected on and the. The root has one child, so the single-root version gives the same sequence.

Greedy search is not exact. Let the score of an arc transition be an arc score s(h,d)s(h, d), with s(0,1)=1s(0, 1) = 1, s(1,2)=s(1,3)=5s(1, 2) = s(1, 3) = 5, s(2,1)=3s(2, 1) = 3 and 0 for all other arcs, and let SHIFT score 0. After the first SHIFT, RIGHT-ARC (score 1) beats SHIFT (score 0), so word 1 is attached to the root and leaves the stack at once. It can then never take its dependents 2 and 3. The greedy tree scores 1, while the best projective tree, 0→10 \to 1, 1→21 \to 2, 1→31 \to 3, scores 11. The tests contain this case.

Correctness

Every run ends in a tree. If the buffer is not empty, SHIFT is legal; if it is empty and the stack has two or more words, RIGHT-ARC is legal. So the parser never gets stuck before a terminal configuration. Each word enters the stack once and leaves it only by getting a head, so at the end every word has exactly one head. The arcs form a tree because a word leaves the stack when it gets a head and can never become the head of anything after that, so no cycle can close.

The tree is projective. At all times, the words on the stack cover consecutive intervals of positions with their subtrees built so far, in stack order, and together they cover the positions from 0 to just before the buffer. An arc joins the two top intervals into one interval. So every subtree is an interval, which is projectivity.

Every projective tree is reached. For a projective tree, build each subtree recursively: first the subtrees of the left dependents, then SHIFT the head and attach the left dependents with LEFT-ARC, then each right dependent's subtree followed by RIGHT-ARC. Because each subtree is an interval, these pieces follow each other in the buffer. This is the sequence that the static oracle produces. The proofs are in the correctness proof. The tests check soundness and completeness by building every complete transition sequence for n≤5n \le 5, with and without the single-root rule: the sets of trees are exactly the projective trees, 1, 3, 12, 55, 273 of them, and 1, 2, 7, 30, 143 with one root child.

Proof: The arc-standard system is sound and complete for projective trees, and every run ends after 2n transitionsfull

The words are 1,…,n1, \ldots, n and 0 is the root. A configuration is (σ,β,A)(\sigma, \beta, A) as on the main page. Only SHIFT touches the buffer, and it takes the front, so β=[b,b+1,…,n]\beta = [b, b + 1, \ldots, n] for some bb. Write the stack as σ=[v0,v1,…,vk]\sigma = [v_0, v_1, \ldots, v_k] from bottom to top, and for a word vv let its partial yield YA(v)Y_A(v) be the set of words below vv in the arcs AA, vv included.

Lemma 1 (invariant). Every configuration reached from the initial one satisfies:

  • (a) v0=0v_0 = 0, and 0 has no head in AA;
  • (b) each word has at most one head in AA, and AA has no cycle;
  • (c) a word has a head in AA exactly when it has been shifted and is no longer on the stack;
  • (d) YA(v0),…,YA(vk)Y_A(v_0), \ldots, Y_A(v_k) are consecutive intervals in this order, and their union is {0,1,…,b−1}\{0, 1, \ldots, b - 1\};
  • (e) for each arc h→dh \to d in AA, every word strictly between hh and dd is in YA(h)Y_A(h).

Proof. At the start σ=[0]\sigma = [0], A=∅A = \emptyset and b=1b = 1, and all five hold. SHIFT pushes bb with YA(b)={b}Y_A(b) = \{b\}, the next interval, and adds no arc. LEFT-ARC adds s0→s1s_0 \to s_1 for the top two words s1=vk−1≠0s_1 = v_{k - 1} \ne 0 and s0=vks_0 = v_k, and removes s1s_1. By (c), s1s_1 had no head, so (b) keeps one head per word, and (a) holds since s1≠0s_1 \ne 0. No cycle closes: a cycle through the new arc would need s0∈YA(s1)s_0 \in Y_A(s_1), but by (d) the two partial yields are disjoint. The new YA(s0)Y_A(s_0) is YA(s1)∪YA(s0)Y_A(s_1) \cup Y_A(s_0), the union of two neighbouring intervals, so (d) holds. Every word strictly between s1s_1 and s0s_0 is in that union, which gives (e) for the new arc; the older arcs keep (e) because partial yields only grow. (c) holds since s1s_1 left the stack with its head. RIGHT-ARC is the mirror image, with s1s_1 as the head and s0s_0 removed; here s1=0s_1 = 0 is allowed, and (a) still holds. □\square

Theorem 2 (soundness and termination). Every run stops after exactly 2n2n transitions in a terminal configuration, and its arcs AA form a projective tree rooted at 0. Under the single-root rule, 0 has exactly one child.

Proof. No dead end. In a configuration that is not terminal, either the buffer is not empty and SHIFT is legal, or the buffer is empty and the stack has at least two words, and then RIGHT-ARC is legal, also under the single-root rule, whose condition asks only for an empty buffer when s1=0s_1 = 0.

Count. The quantity 2∣β∣+∣σ∣2|\beta| + |\sigma| is 2n+12n + 1 at the start and 1 in a terminal configuration. SHIFT lowers ∣β∣|\beta| by one and raises ∣σ∣|\sigma| by one; each arc transition lowers ∣σ∣|\sigma| by one. So each transition lowers the quantity by exactly one, and every run stops after exactly 2n2n transitions.

Tree. In a terminal configuration σ=[0]\sigma = [0] and β\beta is empty, so by (c) every word has a head, by (b) exactly one and no cycle. Following heads from any word therefore reaches the only word without a head, which is 0 by (a).

Projective. For each arc h→dh \to d, (e) says that hh dominates every word strictly between hh and dd, which is the definition of a projective arc.

Single root. A RIGHT-ARC with s1=0s_1 = 0 requires s1=v0s_1 = v_0, so the stack is [0,s0][0, s_0], and under the rule the buffer is empty. After it the configuration is terminal. So 0 gets at most one child, and it gets at least one, because some word of a tree on {0,…,n}\{0, \ldots, n\} has 0 as its head. □\square

Theorem 3 (completeness). For every projective tree GG there is a sequence of legal transitions from the initial configuration to a terminal configuration with A=GA = G. If 0 has one child in GG, the sequence is legal under the single-root rule.

Proof. For a word vv with gold left dependents l1<⋯<lal_1 < \cdots < l_a and right dependents r1<⋯<rmr_1 < \cdots < r_m, define the sequence

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},

with the labels of GG. Let Y(v)Y(v) be the yield of vv in GG. Since GG is projective, Y(v)Y(v) is an interval, and it is split into the consecutive intervals Y(l1),…,Y(la),{v},Y(r1),…,Y(rm)Y(l_1), \ldots, Y(l_a), \{v\}, Y(r_1), \ldots, Y(r_m), in this order.

Claim. If the buffer starts at min⁡Y(v)\min Y(v) and the stack is some σ\sigma, then SEQ(v)\mathrm{SEQ}(v) is legal, it ends with the stack σ∣v\sigma \mid v, the buffer starting at max⁡Y(v)+1\max Y(v) + 1, and the arcs of GG inside Y(v)Y(v) added, and nothing else changed. By induction on ∣Y(v)∣|Y(v)|: the calls SEQ(li)\mathrm{SEQ}(l_i) leave σ∣l1∣⋯∣la\sigma \mid l_1 \mid \cdots \mid l_a with the buffer at vv, because the yields follow each other. SHIFT pushes vv. Each LEFT-ARC then attaches the word below vv to vv: first lal_a, then la−1l_{a - 1}, down to l1l_1, and it is legal since these words are not 0. Then each SEQ(rj)\mathrm{SEQ}(r_j) leaves rjr_j on top of vv with the buffer at the start of the next yield, and RIGHT-ARC attaches rjr_j to vv and removes it. In the end vv is on top of σ\sigma with all arcs of GG in Y(v)Y(v). Every LEFT-ARC and RIGHT-ARC here has s1≠0s_1 \ne 0, because the words of Y(v)Y(v) are not 0, so the single-root rule never blocks them.

For the whole tree, let c1<⋯<cmc_1 < \cdots < c_m be the children of 0. Run SEQ(c1)\mathrm{SEQ}(c_1), RIGHT-ARC, ..., SEQ(cm)\mathrm{SEQ}(c_m), RIGHT-ARC from the initial configuration. By the claim, each SEQ(cj)\mathrm{SEQ}(c_j) leaves [0,cj][0, c_j] on the stack, and RIGHT-ARC adds 0→cj0 \to c_j. The yields of the children cover 1,…,n1, \ldots, n in order, so the run ends with [0][0], an empty buffer and A=GA = G. If m=1m = 1, the only RIGHT-ARC with s1=0s_1 = 0 is the last transition, when the buffer is empty, so the rule allows it. □\square

The static oracle. The sequence of Theorem 3 is the one that the static oracle of the main page produces: it does every LEFT-ARC as soon as the dependent and its head are the top two words, and every RIGHT-ARC as soon as the dependent is complete. The tests check that the oracle builds every projective tree with n≤5n \le 5, and random projective trees up to n=6n = 6, and that it fails on every non-projective tree with n≤5n \le 5. They also check Theorems 2 and 3 by brute force, by building all complete transition sequences for n≤5n \le 5, with and without the single-root rule.

Complexity

Number of transitions. A SHIFT lowers the buffer by one, and an arc transition lowers the stack by one. Take the potential 2∣β∣+∣σ∣2 |\beta| + |\sigma|: it is 2n+12n + 1 at the start and 1 at the end, and every transition lowers it by exactly one. So every complete sequence has exactly 2n2n transitions, nn shifts and nn arcs.

Time. Each step scores at most 1+2∣R∣1 + 2|R| transitions for the label set RR. With a scorer that takes constant time for a fixed label set and fixed feature templates, the parse takes Θ(n)\Theta(n) time. In general it is 2n2n times the cost of one classifier call.

Space. The stack, the buffer pointer and the head list take Θ(n)\Theta(n).

Properties

  • Sound and complete for projective trees. Every terminal configuration holds a projective tree, and every projective tree has a sequence.
  • Bottom up. A word is attached to its head only after all its dependents are attached. Right dependents therefore wait on the stack, which can grow to n+1n + 1 words, for example in a chain of right arcs.
  • Spurious ambiguity. A tree can have several sequences. A head with one dependent on each side can take the left one first or the right one first. For n=1n = 1 to 5 there are 1, 3, 13, 67, 381 complete sequences for 1, 3, 12, 55, 273 trees; the tree [-1, 2, 0, 2] has two sequences. The static oracle picks one of them, the one with left arcs as early as possible.
  • Incremental, with lookahead. The words are read in order, and a decision uses only the stack and a few buffer words. The final tree is known only at the end.
  • Not exact. Greedy choices can lose the best tree under a given score, as in the example. Beam search and exact search over the transition sequences are the alternatives.

Variants and improvements

  • Beam search. Keep the kk best configurations at each step, as in beam search, and train the scores of whole sequences with a global perceptron or a global loss.
  • Neural classifiers. The Chen-Manning parser chooses the arc-standard move with a feedforward network on embeddings of the words near the top of the stack.
  • Arc-eager and arc-hybrid. The arc-eager system attaches right dependents as soon as they are read; the arc-hybrid system builds left arcs between the stack top and the buffer front.
  • Non-projective trees. The swap system adds a SWAP move that reorders words and builds all trees. Pseudo-projective parsing instead transforms the treebank and undoes the transformation after parsing.
  • Exact search. Under scores that depend on a few top elements, the space of arc-standard sequences can be searched by dynamic programming. Kuhlmann, Gómez-Rodríguez and Satta (2011) give such a deduction system in O(n5)O(n^5) time, or O(n4)O(n^4) with a further trick; this is slower than the arc-hybrid and arc-eager systems, for which the same method gives O(n3)O(n^3).
  • Dynamic oracles. Arc-standard has a dynamic oracle as well, but it is less simple than those of arc-eager and arc-hybrid; see the dynamic oracle page.

When to use it

Use arc-standard parsing when speed matters more than exact search, when the trees are projective or can be made projective, and when a simple classifier on local features is enough. It is a good default for greedy neural parsers. When most errors come from early right attachments that wait too long, or when a simple dynamic oracle is needed, the arc-hybrid system is the usual alternative. For languages with many crossing arcs, use the swap system or an MST parser.

Pitfalls

  • LEFT-ARC on the root. The root must never become a dependent; the condition s1≠0s_1 \ne 0 guards this.
  • Early RIGHT-ARC. Attaching a word to its head before it has its own right dependents removes it from the stack for ever. The static oracle must check that s0s_0 is complete before choosing RIGHT-ARC; a classifier that does this too early cannot recover.
  • Several root children. Without the single-root rule, a greedy parser can attach several words to the root. If the treebank requires one root child, use the rule.
  • Non-projective training trees. The static oracle gets stuck on them. Remove such trees, projectivize them, or use the swap system.
  • Ties. The order of ties changes the tree when scores are equal, so fix the order and keep it the same in training and parsing.

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.

arc_standard_parsing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/arc-standard-parsing/. The authors are listed in prov/D0MMXM.jsonl.

"""The arc-standard transition system for dependency parsing.

The words are 1..n and 0 is the artificial root. A configuration is
(stack, buffer, arcs). The stack starts as [0] and its top is the last element;
the buffer is the list of words not yet shifted, front first. The transitions
are ("SH", None), ("LA", label) and ("RA", label):

    SHIFT         (sigma, b|beta, A)       => (sigma|b, beta, A)                 needs a non-empty buffer
    LEFT-ARC_l    (sigma|s1|s0, beta, A)   => (sigma|s0, beta, A + {(s0, l, s1)})  needs s1 != 0
    RIGHT-ARC_l   (sigma|s1|s0, beta, A)   => (sigma|s1, beta, A + {(s1, l, s0)})

The terminal configuration is ([0], [], A). Every complete sequence has exactly
2n transitions: n shifts and n arcs. With single_root=True, RIGHT-ARC from the
root needs an empty buffer, so the root gets exactly one child.

A tree is a pair (heads, labels) of lists of length n + 1 with heads[0] = -1.
"""

from typing import Callable, List, Optional, Sequence, Tuple

Transition = Tuple[str, Optional[str]]
SHIFT: Transition = ("SH", None)


class Config:
    """A parser configuration. heads[d] is -1 while word d has no head."""

    def __init__(self, n: int):
        self.n = n
        self.stack: List[int] = [0]
        self.next = 1  # the buffer is next, next + 1, ..., n
        self.heads = [-1] * (n + 1)
        self.labels: List[Optional[str]] = [None] * (n + 1)

    def buffer(self) -> List[int]:
        return list(range(self.next, self.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 is_legal(c: Config, t: Transition, single_root: bool = False) -> bool:
    kind = t[0]
    if kind == "SH":
        return c.next <= c.n
    if len(c.stack) < 2:
        return False
    s1 = c.stack[-2]
    if kind == "LA":
        return s1 != 0
    if kind == "RA":
        return not (single_root and s1 == 0 and c.next <= c.n)
    raise ValueError(f"unknown transition {t}")


def apply(c: Config, t: Transition) -> None:
    """Apply the legal transition t to c in place."""
    kind, label = t
    if kind == "SH":
        c.stack.append(c.next)  # @line L5
        c.next += 1
    elif kind == "LA":
        s0 = c.stack.pop()  # @line L6
        s1 = c.stack.pop()
        c.heads[s1], c.labels[s1] = s0, label
        c.stack.append(s0)
    else:
        s0 = c.stack.pop()  # @line L7
        s1 = c.stack[-1]
        c.heads[s0], c.labels[s0] = s1, label


def legal_transitions(c: Config, label_set: Sequence[str], single_root: bool = False) -> List[Transition]:
    out = [SHIFT] if is_legal(c, SHIFT) else []
    for kind in ("LA", "RA"):
        for lab in label_set:
            if is_legal(c, (kind, lab), single_root):
                out.append((kind, lab))
    return out


Scorer = Callable[[Config, Transition], float]


def parse(n: int, score: Scorer, label_set: Sequence[str] = ("dep",), single_root: bool = False):
    """Greedy parsing: in each configuration take the legal transition of highest score.

    Returns (heads, labels, transitions). Ties go to the first transition in the
    order SHIFT, then LEFT-ARC, then RIGHT-ARC, labels in the given order.
    """
    c = Config(n)  # @line L1
    seq: List[Transition] = []
    while not c.is_terminal():  # @line L2
        cands = legal_transitions(c, label_set, single_root)  # @line L3
        best = None
        for t in cands:  # @line L4
            s = score(c, t)
            if best is None or s > best[0]:
                best = (s, t)
        apply(c, best[1])
        seq.append(best[1])
    return c.heads, c.labels, seq  # @line L8


def static_oracle(c: Config, gold_heads: Sequence[int], gold_labels: Sequence[Optional[str]]) -> Optional[Transition]:
    """Return the transition of the static oracle, or None if no transition can lead to the gold tree.

    LEFT-ARC when s1 is a dependent of s0; RIGHT-ARC when s0 is a dependent of s1
    and has all its own dependents; SHIFT otherwise.
    """
    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:
            done = all(c.heads[d] == s0 for d in range(1, c.n + 1) if gold_heads[d] == s0)
            if done:
                return ("RA", gold_labels[s0])
    if c.next <= c.n:
        return SHIFT
    return None


def oracle_sequence(gold_heads: Sequence[int], gold_labels: Optional[Sequence[Optional[str]]] = None) -> List[Transition]:
    """Return the static oracle sequence that builds the gold tree.

    Raise ValueError if the oracle gets stuck or builds another tree, which
    happens exactly when the gold tree is not projective.
    """
    n = len(gold_heads) - 1
    if gold_labels is None:
        gold_labels = [None] + ["dep"] * n
    c = Config(n)
    seq: List[Transition] = []
    while not c.is_terminal():
        t = static_oracle(c, gold_heads, gold_labels)
        if t is None:
            raise ValueError("the oracle is stuck: the tree is not projective")
        apply(c, t)
        seq.append(t)
    if c.heads[1:] != list(gold_heads[1:]):
        raise ValueError("the oracle built another tree")
    return seq


def run(n: int, seq: Sequence[Transition], single_root: bool = False) -> Config:
    """Apply a transition sequence from the initial configuration; raise ValueError on an illegal step."""
    c = Config(n)
    for t in seq:
        if not is_legal(c, t, single_root):
            raise ValueError(f"illegal transition {t}")
        apply(c, t)
    return c
test_arc_standard_parsing.py 169 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/arc-standard-parsing/. The authors are listed in prov/D0MMXM.jsonl.

import itertools
import random

import pytest

from arc_standard_parsing import (
    SHIFT,
    Config,
    apply,
    is_legal,
    legal_transitions,
    oracle_sequence,
    parse,
    run,
    static_oracle,
)

# the cat sat on the mat
SENT = ["the", "cat", "sat", "on", "the", "mat"]
GOLD_HEADS = [-1, 2, 3, 0, 6, 6, 3]
GOLD_LABELS = [None, "det", "nsubj", "root", "case", "det", "obl"]


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 all_trees(n):
    return [[-1] + list(hs) for hs in itertools.product(range(n + 1), repeat=n) if is_tree([-1] + list(hs))]


TREES = {n: all_trees(n) for n in range(1, 6)}


def all_complete_runs(n, single_root=False):
    """Brute force: every complete transition sequence (unlabeled), by depth-first search."""
    out = []
    todo = [(Config(n), [])]
    while todo:
        c, seq = todo.pop()
        if c.is_terminal():
            out.append((tuple(c.heads), seq))
            continue
        for t in legal_transitions(c, ["dep"], single_root):
            c2 = c.copy()
            apply(c2, t)
            todo.append((c2, seq + [t]))
    return out


def test_example_sequence():
    seq = oracle_sequence(GOLD_HEADS, GOLD_LABELS)
    names = [t[0] if t[1] is None else f"{t[0]}-{t[1]}" for t in seq]
    assert names == [
        "SH", "SH", "LA-det", "SH", "LA-nsubj", "SH", "SH", "SH", "LA-det", "LA-case", "RA-obl", "RA-root",
    ]
    c = run(6, seq)
    assert c.heads == GOLD_HEADS and c.labels == GOLD_LABELS


def test_oracle_succeeds_exactly_on_projective_trees():
    for n in range(1, 6):
        for heads in TREES[n]:
            if is_projective(heads):
                seq = oracle_sequence(heads)
                assert len(seq) == 2 * n
            else:
                with pytest.raises(ValueError):
                    oracle_sequence(heads)


@pytest.mark.parametrize("single_root", [False, True])
def test_sound_and_complete_for_projective_trees(single_root):
    for n in range(1, 6):
        runs = all_complete_runs(n, single_root)
        built = {heads for heads, _ in runs}
        expected = {
            tuple(t) for t in TREES[n]
            if is_projective(t) and (not single_root or t[1:].count(0) == 1)
        }
        assert built == expected
        assert all(len(seq) == 2 * n for _, seq in runs)
    counts = [len({h for h, _ in all_complete_runs(n, single_root)}) for n in range(1, 6)]
    assert counts == ([1, 2, 7, 30, 143] if single_root else [1, 3, 12, 55, 273])


def test_spurious_ambiguity():
    # a h b with h the root child: the two arcs of h can be built in either order.
    runs = [seq for heads, seq in all_complete_runs(3) if heads == (-1, 2, 0, 2)]
    assert len(runs) == 2


def test_greedy_with_oracle_scores_rebuilds_gold():
    rng = random.Random(1)
    labels = ["a", "b", "c"]
    for n in range(1, 7):
        for _ in range(20):
            heads = [-1] + [rng.randint(0, n) for _ in range(n)]
            if not is_tree(heads) or not is_projective(heads):
                continue
            gl = [None] + [rng.choice(labels) for _ in range(n)]

            def score(c, t, heads=heads, gl=gl):
                return 1.0 if t == static_oracle(c, heads, gl) else 0.0

            got_heads, got_labels, seq = parse(n, score, labels)
            assert got_heads == heads and got_labels == gl
            assert seq == oracle_sequence(heads, gl)


def test_greedy_random_scores_give_projective_trees():
    rng = random.Random(2)
    for _ in range(200):
        n = rng.randint(1, 8)
        heads, labels, seq = parse(n, lambda c, t: rng.random(), ["x", "y"])
        assert len(seq) == 2 * n
        assert is_tree(heads) and is_projective(heads)


def test_greedy_is_not_exact():
    # Arc-factored scores; SHIFT scores 0. Greedy attaches word 1 to the root at
    # once (score 1 > 0), so word 1 can no longer take its dependents 2 and 3.
    s = [[0, 1, 0, 0], [0, 0, 5, 5], [0, 3, 0, 0], [0, 0, 0, 0]]

    def score(c, t):
        if t[0] == "SH":
            return 0.0
        s1, s0 = c.stack[-2], c.stack[-1]
        return s[s0][s1] if t[0] == "LA" else s[s1][s0]

    heads, _, _ = parse(3, score)
    greedy = sum(s[heads[d]][d] for d in range(1, 4))
    best = max(sum(s[t[d]][d] for d in range(1, 4)) for t in TREES[3] if is_projective(t))
    assert best == 11
    assert greedy < best


def test_preconditions():
    c = Config(2)
    assert not is_legal(c, ("LA", "x")) and not is_legal(c, ("RA", "x"))
    apply(c, SHIFT)
    assert not is_legal(c, ("LA", "x"))  # s1 is the root
    assert is_legal(c, ("RA", "x"))
    assert not is_legal(c, ("RA", "x"), single_root=True)  # buffer not empty
    with pytest.raises(ValueError):
        run(2, [("LA", "x")])

History

Shift-reduce parsing is a classic method for context-free grammars. Yamada and Matsumoto (2003) used a deterministic parser with the actions shift, right and left between neighbouring words, chosen by support vector machines, which took several passes over the sentence. Nivre (2003, 2004) gave stack-based systems that make one left-to-right pass, and named the arc-standard and arc-eager strategies; Nivre (2008) set them in a common framework of transition systems and proved their soundness and completeness. Chen and Manning (2014) replaced the feature-based classifier with a neural network, which made greedy arc-standard parsing both fast and accurate.

References

  1. Joakim Nivre, Algorithms for deterministic incremental dependency parsing, Computational Linguistics 34(4), 513-553, 2008, the stack-based arc-standard system, its soundness and completeness for projective trees, and the bound of 2n transitions
  2. Joakim Nivre, Incrementality in deterministic dependency parsing, Workshop on Incremental Parsing, ACL 2004, the arc-standard and arc-eager strategies compared for incrementality
  3. Hiroyasu Yamada and Yuji Matsumoto, Statistical dependency analysis with support vector machines, IWPT 2003, the shift, right and left actions between neighbouring words, chosen by support vector machines
  4. 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 (configurations, transition systems, oracles and classifiers)

Where this leads

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