Algorithm Search⌘K

Algorithmcore

Arc-eager parsing

Also called arc-eager transition system, Nivre parser.

Transition-based parsing that adds right arcs as early as possible, with moves shift, left-arc, right-arc and reduce, in linear time.

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

Arc-eager parsing is a transition system for dependency parsing that adds each arc as soon as both of its words have been seen. Like arc-standard parsing it reads the sentence from left to right with a stack and a buffer, but its arcs join the top of the stack and the front of the buffer. LEFT-ARC makes the buffer front the head of the stack top and pops the stack. RIGHT-ARC makes the stack top the head of the buffer front and pushes the front, so a word is attached to its head on the left before its own right dependents are read. Because of this, a word can stay on the stack after it has its head, and a fourth move, REDUCE, pops it when it is finished. SHIFT pushes the buffer front as before. A parse takes at most 2n2n moves for nn words, and the system builds exactly the projective trees. Nivre gave it in 2003. Goldberg and Nivre (2012) gave it a simple dynamic oracle, which lets a parser learn to recover from its own mistakes.

In plain words

Read the words one at a time. Keep a pile of words that may still get dependents, and look at the top of the pile and at the next unread word. If the next word governs the top word, draw that arrow and take the top word off the pile. If the top word governs the next word, draw that arrow at once and put the next word on the pile, since it may still have its own dependents further on. If the top word already has its arrow and nothing more can attach to it, take it off the pile. Otherwise put the next word on the pile. When all words are read, any word still without an arrow is joined to the start symbol. A trained classifier makes the choice at each step.

The problem

The input is a sentence w1⋯wnw_1 \cdots w_n with features, and a scoring function on the legal transitions of a configuration, usually a trained classifier. The output is a labeled projective dependency tree. In the version on this page, the root may have several children: RIGHT-ARC from the root can attach any number of words to it, and the words that are still without a head at the end are attached to it too. A parser that needs one root child must change the end of the parse; Nivre and Fernández-González (2014) study such changes.

The algorithm

A configuration is (σ,β,A)(\sigma, \beta, A), as in arc-standard parsing, with the stack top ss and the buffer front bb. The initial configuration is ([0],[1,…,n],∅)([0], [1, \ldots, n], \emptyset), and every configuration with an empty buffer is terminal. 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)
LEFT-ARCl_l (σ∣s,b∣β,A)(\sigma \mid s, b \mid \beta, A) (σ,b∣β,A∪{b→ls})(\sigma, b \mid \beta, A \cup \{b \xrightarrow{l} s\}) s≠0s \ne 0, ss has no head
RIGHT-ARCl_l (σ∣s,b∣β,A)(\sigma \mid s, b \mid \beta, A) (σ∣s∣b,β,A∪{s→lb})(\sigma \mid s \mid b, \beta, A \cup \{s \xrightarrow{l} b\})
REDUCE (σ∣s,β,A)(\sigma \mid s, \beta, A) (σ,β,A)(\sigma, \beta, A) ss has a head

The greedy parser:

  1. ARC-EAGER-PARSE(x, score)
  2. 1c <- ([0], [1, ..., n], {})
  3. 2while the buffer of c is not empty do
  4. 3for each legal transition t of c
  5. 4compute score(c, t), and keep the best t
  6. 5if t = SHIFT then push b
  7. 6if t = LEFT-ARC_l then add b -l-> s and pop s
  8. 7if t = RIGHT-ARC_l then add s -l-> b and push b
  9. 8if t = REDUCE then pop s
  10. 9attach every word without a head to the root 0, with the label root
  11. 10return the tree A

The static oracle. For a projective gold tree: choose LEFT-ARC if bb is the gold head of ss; RIGHT-ARC if ss is the gold head of bb; REDUCE if ss has its head and no gold dependent of ss is still in the buffer; SHIFT otherwise. The labels come from the gold tree.

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 10 transitions, against 12 for arc-standard:

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

At step 5 sat gets its head before any of its right dependents is read, which arc-standard parsing cannot do. The buffer is empty after step 10, so the parse stops; sat and mat stay on the stack, but they already have their heads, and no REDUCE is needed. The root has one child here, by the choice of the oracle.

A wrong step and the dynamic oracle. Suppose the parser starts with RIGHT-ARC, which attaches the (word 1) to the root. The gold arc cat →\to the is now lost, since a word gets only one head. The cost of this move is 1: the number of gold arcs that no longer can be built. From the new configuration, the dynamic oracle allows the moves of cost 0, and following them gives a tree with exactly one wrong head, the least possible. The tests check this case, and they check the cost formulas against a search over all transition sequences.

Correctness

Every run gives a tree. While the buffer is not empty, SHIFT is legal, so the parser never gets stuck. LEFT-ARC is allowed only for a word without a head, and RIGHT-ARC attaches the buffer front, which has no head yet, so each word gets at most one head; line L9 gives the rest a head. A new arc cannot close a cycle: the buffer front has no head when LEFT-ARC makes it a head, and the ancestors of a stack word are all below it on the stack, so they never include the buffer front.

The tree is projective. The stack is increasing in position. An arc always joins the stack top ss and the buffer front bb, and every word between them has been pushed after ss and popped. No arc can pass over a word that is still on the stack, because that word would sit between the top and the front. From this it follows that no two arcs cross, including the root arcs of line L9.

Every projective tree is reached. The static oracle builds every projective tree. The key step is that when a word leaves the buffer, all gold arcs between it and the words to its left are already built; projectivity rules out every configuration in which SHIFT would leave one behind. The proofs are in the correctness proof. The tests also build every complete transition sequence for n≤5n \le 5: the trees obtained are exactly the 1, 3, 12, 55, 273 projective trees.

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

The words are 1,…,n1, \ldots, n and 0 is the root. A configuration is (σ,β,A)(\sigma, \beta, A) with stack top ss and buffer front bb; the buffer is always [b,…,n][b, \ldots, n], since only SHIFT and RIGHT-ARC change it and both take the front. "Before time tt" refers to the configurations of one run in order.

Lemma 1 (invariant). In every configuration of a run:

  • (a) the stack is increasing in position from bottom to top, and its bottom is 0;
  • (b) every word that has been popped from the stack has a head in AA, and no word in the buffer has a head;
  • (c) each word has at most one head, and no arc enters 0;
  • (d) every head in AA of a stack word is a stack word below it;
  • (e) AA has no cycle.

Proof. At the start all hold. (a): SHIFT and RIGHT-ARC push bb, which is larger than every shifted word; pops keep the order; 0 is never popped, since LEFT-ARC and REDUCE need s≠0s \ne 0 (REDUCE needs a head, and 0 never has one by (c)). (b): LEFT-ARC pops ss after giving it a head, REDUCE pops only a word with a head, and the only arc into a buffer word is the one RIGHT-ARC adds when it moves the word to the stack. (c): LEFT-ARC needs ss without a head and s≠0s \ne 0; RIGHT-ARC gives a head to bb, which has none by (b). (d): RIGHT-ARC gives bb the head ss, directly below bb after the push; a stack word is never popped while words are above it, so the head stays below it on the stack. (e): LEFT-ARC adds b→sb \to s; a cycle through the new arc would need a path of heads from bb up to ss, but bb has no head. RIGHT-ARC adds s→bs \to b; a cycle would need bb to be an ancestor of ss, but by (d) all ancestors of ss are on the stack, and bb is not. □\square

Lemma 2 (no arc passes over a stack word). If p<v<qp < v < q, vv is on the stack in some configuration, and AA contains an arc between pp and qq in that configuration or later, then vv was not on the stack when the arc was added.

Proof. An arc is always added between the stack top and the buffer front, and the top is the smaller of the two, since the buffer holds only words larger than every shifted word. So when the arc was added, pp was the top and qq the front. Then v<qv < q had been shifted. If vv were on the stack at that time, (a) would give v<pv < p, since pp is the top; but p<vp < v. □\square

Theorem 3 (soundness and termination). Every run ends after at most 2n2n transitions, and the arcs, with line L9, form a projective tree rooted at 0.

Proof. No dead end and count. While the buffer is not empty, SHIFT is legal. SHIFT and RIGHT-ARC remove one word from the buffer, so there are exactly nn of them. LEFT-ARC and REDUCE pop a word that was pushed by one of these, and each word is popped at most once, so there are at most nn of them. So the run ends, after at most 2n2n transitions, when the buffer is empty.

Tree. At the end, by (b) every word that is not on the stack has a head; line L9 gives a head 0 to every stack word without a head. With (c) every word has exactly one head and 0 has none. The arcs of line L9 cannot close a cycle, since they point from 0, which has no head; with (e) the whole set has no cycle. So following heads from any word ends at 0, and the arcs form a tree.

Projective. By the crossing form of projectivity, it is enough to show that no two arcs cross, with the root arcs included. Take two arcs, (p,q)(p, q) added before (x,y)(x, y), with p<qp < q and x<yx < y, both added by LEFT-ARC or RIGHT-ARC. When (x,y)(x, y) was added, xx was the top and yy the front. If they crossed, one endpoint of (p,q)(p, q) would lie strictly between xx and yy and the other outside. The endpoint qq was the front at an earlier time, so q≤yq \le y. If p<x<q<yp < x < q < y: when (p,q)(p, q) was added, x<qx < q had been shifted, and xx is on the stack later, at the time of (x,y)(x, y), so it was on the stack then too, since a popped word is never pushed again. That contradicts Lemma 2 for v=xv = x. If x<p<y<qx < p < y < q: impossible, since q≤yq \le y. The arcs of line L9 join 0 to a word vv that is on the stack at the end; an arc (x,y)(x, y) crosses (0,v)(0, v) only if x<v<yx < v < y with x>0x > 0, which Lemma 2 forbids, and two arcs from 0 cannot cross. □\square

Theorem 4 (completeness). For every projective tree GG with heads h∗h^\ast, the static oracle produces a legal run whose final arcs, before line L9, are exactly GG.

Proof. We show that the oracle run keeps two properties: (i) A⊆GA \subseteq G; (ii) every arc of GG whose two endpoints are both smaller than bb is in AA.

Legality and (i). The oracle is called only while the buffer is not empty, so SHIFT and RIGHT-ARC are legal. It chooses LEFT-ARC only when h∗(s)=bh^\ast(s) = b; then s≠0s \ne 0, and ss has no head. Indeed, by (i) a head of ss in AA would be h∗(s)=bh^\ast(s) = b; but an arc from a larger word to a smaller one is added only by LEFT-ARC, which pops the dependent, and ss is still on the stack. REDUCE is chosen only when ss has a head. Every arc added is a gold arc, so (i) holds.

(ii). LEFT-ARC and REDUCE do not move bb and only add arcs, so (ii) is kept. Consider a buffer move of bb, by SHIFT or RIGHT-ARC. The new gold arcs with both endpoints below b+1b + 1 are the arcs between bb and smaller words: the arc from a gold head h=h∗(b)<bh = h^\ast(b) < b, and the arcs to the gold dependents d<bd < b of bb.

First, the dependents. Suppose h∗(d)=bh^\ast(d) = b with d<bd < b and the arc not in AA. Then dd has no head by (i), so by (b) it is on the stack. If d=sd = s, the oracle would choose LEFT-ARC, not a buffer move. So d<s<bd < s < b by (a). The gold arc b→db \to d passes over ss, so bb dominates ss in GG. The gold head g=h∗(s)g = h^\ast(s) is not bb, or the oracle would choose LEFT-ARC. It is not larger than bb: the arc g→sg \to s would pass over bb, so gg would dominate bb, while bb dominates ss and hence its parent gg. So g<bg < b, and by (ii) the arc g→sg \to s is in AA; ss has a head. A gold dependent e≥be \ge b of ss is impossible: e=be = b would make ss the parent of bb and bb an ancestor of ss; e>be > b would make the arc s→es \to e pass over bb, so ss would dominate bb, which dominates ss. So the conditions of REDUCE hold, and the oracle, which tries REDUCE before SHIFT, would choose REDUCE. Its choice of RIGHT-ARC is also excluded, since RIGHT-ARC needs h∗(b)=sh^\ast(b) = s, while bb dominates ss. This contradicts the buffer move.

Next, the head. Suppose h=h∗(b)<bh = h^\ast(b) < b and the oracle moves bb without adding h→bh \to b, so it chooses SHIFT and h≠sh \ne s. If hh had been popped, then by LEFT-ARC with a head b′≤bb' \le b, or by REDUCE. REDUCE was impossible, since bb, a gold dependent of hh, was in the buffer. A LEFT-ARC gave hh the gold head b′b': b′=bb' = b would make bb and hh each other's parents, and b′<bb' < b would make the gold arc h→bh \to b pass over b′b', so hh would dominate its own parent. So hh is on the stack, and h<s<bh < s < b. The gold arc h→bh \to b passes over ss, so hh dominates ss. The gold head g=h∗(s)g = h^\ast(s) is not bb (the oracle would choose LEFT-ARC) and not larger than bb (the arc g→sg \to s would pass over bb, so gg would dominate bb and its parent hh, while hh dominates ss and its parent gg; this forces g=h<bg = h < b, a contradiction). So g<bg < b and by (ii) ss has a head. A gold dependent e≥be \ge b of ss is impossible: e=be = b contradicts h∗(b)=h≠sh^\ast(b) = h \ne s, and e>be > b makes ss dominate bb and its parent hh, while hh dominates ss. So the oracle would choose REDUCE, a contradiction.

End. When the buffer is empty, b=n+1b = n + 1, and (ii) says that every arc of GG is in AA. With (i), A=GA = G before line L9, and line L9 adds nothing. □\square

The tests check Theorems 3 and 4 by brute force: for n≤5n \le 5 they build all complete sequences and compare the trees with the projective trees found by a search over all head lists, and they check that the static oracle rebuilds every projective tree and fails on every other tree.

Complexity

Number of transitions. SHIFT and RIGHT-ARC each take one word from the buffer, so there are exactly nn of them. LEFT-ARC and REDUCE each pop a word that some earlier SHIFT or RIGHT-ARC pushed, so there are at most nn of them. A complete sequence therefore has between nn and 2n2n transitions; with the terminal condition of this page the tests find at most 2n−12n - 1.

Time. Each step scores at most 2+2∣R∣2 + 2|R| transitions. With a scorer of constant cost for a fixed label set, the parse takes Θ(n)\Theta(n) time, and line L9 adds O(n)O(n).

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

Properties

  • Sound and complete for projective trees. Every terminal configuration, after line L9, holds a projective tree, and every projective tree has a sequence.
  • Eager right arcs. A word is attached to a head on its left as soon as both have been read. The partial tree is more connected at each step than in arc-standard parsing, which was the reason Nivre called the strategy incremental.
  • Spurious ambiguity. A tree can have several sequences. With this page's terminal condition there are 2, 8, 40, 224, 1344 complete sequences for n=1n = 1 to 5; already for n=1n = 1 both SHIFT and RIGHT-ARC lead to the single tree, since a word left without a head goes to the root.
  • Early commitment. A wrong RIGHT-ARC fixes a head before the parser has seen the words that could show it to be wrong. This is the main source of errors that the dynamic oracle trains against.
  • Arc-decomposable. The gold arcs that can still be built from a configuration can be built all together, so the cost of a move is a count of lost gold arcs that can be read off from the configuration. This is why the dynamic oracle is simple and exact.
  • Not exact. Greedy choices can miss the best tree under a given score. Beam search over sequences is the usual remedy.

Variants and improvements

  • Dynamic oracle. The cost of LEFT-ARC is the number of gold dependents of ss in the buffer, plus 1 if the gold head of ss is in the buffer after bb or is the root. The cost of RIGHT-ARC counts the gold arc into bb if its head is deeper in the stack or later in the buffer, plus the headless stack words whose gold head is bb. The cost of REDUCE is the number of gold dependents of ss in the buffer. SHIFT loses the gold arcs between bb and the stack words that could still be built, except an arc from the root, which line L9 still gives. These are the formulas of Goldberg and Nivre (2012), adapted to the root at the bottom of the stack; the code computes them and the tests compare them with a search over all sequences.
  • Arc-hybrid. The arc-hybrid system keeps LEFT-ARC of arc-eager and takes RIGHT-ARC of arc-standard; it needs no REDUCE.
  • Beam search and global training. Keeping the kk best configurations at each step, as in beam search, with a structured perceptron over whole sequences, gives large gains over greedy parsing.
  • Exact search. For a scorer that looks only at the stack top and the buffer front, Kuhlmann, Gómez-Rodríguez and Satta (2011) give a deduction system for arc-eager in O(n3)O(n^3) time.
  • Non-projective trees. Pseudo-projective parsing transforms the treebank and undoes the transformation after parsing; the swap system is the arc-standard route to all trees.

When to use it

Use arc-eager parsing for fast greedy or beam parsing of projective trees, especially when the partial tree should be as connected as possible at each word, as in incremental processing, or when training with a dynamic oracle. For a system without REDUCE and without the end-of-parse root rule, arc-hybrid is simpler. For many crossing arcs, use the swap system or an MST parser.

Pitfalls

  • REDUCE of a headless word. Popping a word without a head leaves it unattached for ever; the condition on REDUCE prevents this. In the other direction, LEFT-ARC must not give a second head to a word that already has one.
  • The end of the parse. Words that are still on the stack without a head when the buffer becomes empty go to the root. This can give the root several children, even when every gold tree has one.
  • The static oracle's REDUCE condition. REDUCE must wait until no gold dependent of ss remains in the buffer; otherwise the dependent can no longer reach its head.
  • Spurious ambiguity in training. The static oracle picks one sequence among several correct ones, and the classifier is penalized for choosing another correct move. The dynamic oracle accepts all moves of cost 0.
  • Root as the stack top. LEFT-ARC with s=0s = 0 would make the root a dependent; it is not allowed, and REDUCE of the root is not allowed either.

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_eager_parsing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/arc-eager-parsing/. The authors are listed in prov/BSRJBW.jsonl.

"""The arc-eager transition system, its static oracle and its dynamic oracle.

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 s is the last
element; the buffer front is b. The transitions are ("SH", None),
("LA", label), ("RA", label) and ("RE", None):

    SHIFT         (sigma, b|beta, A)    => (sigma|b, beta, A)
    LEFT-ARC_l    (sigma|s, b|beta, A)  => (sigma, b|beta, A + {(b, l, s)})    needs s != 0 and s without a head
    RIGHT-ARC_l   (sigma|s, b|beta, A)  => (sigma|s|b, beta, A + {(s, l, b)})
    REDUCE        (sigma|s, beta, A)    => (sigma, beta, A)                     needs s with a head

A configuration with an empty buffer is terminal. The words that still have no
head then get the root 0 as head, with the label "root". A complete sequence
has n moves out of the buffer (SHIFT or RIGHT-ARC) and at most n pops (LEFT-ARC
or REDUCE), so at most 2n transitions.

The dynamic oracle follows Goldberg and Nivre (2012, 2013): the cost of a
transition is the number of gold arcs that it makes unreachable. The formulas
are adapted to this page's convention, the root at the bottom of the stack and
the final attachment to the root; the tests compare them with the cost found by
search over all transition sequences.
"""

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

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


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

    def is_terminal(self) -> bool:
        return self.next > self.n

    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 key(self):
        return (tuple(self.stack), self.next, tuple(self.heads))


def is_legal(c: Config, t: Transition) -> bool:
    kind = t[0]
    s = c.stack[-1]
    if kind == "RE":
        return s != 0 and c.heads[s] != -1
    if c.next > c.n:
        return False
    if kind == "SH" or kind == "RA":
        return True
    if kind == "LA":
        return s != 0 and c.heads[s] == -1
    raise ValueError(f"unknown transition {t}")


def apply(c: Config, t: Transition) -> None:
    kind, label = t
    if kind == "SH":
        c.stack.append(c.next)  # @line L5
        c.next += 1
    elif kind == "LA":
        s = c.stack.pop()  # @line L6
        c.heads[s], c.labels[s] = c.next, label
    elif kind == "RA":
        b = c.next  # @line L7
        c.heads[b], c.labels[b] = c.stack[-1], label
        c.stack.append(b)
        c.next += 1
    else:
        c.stack.pop()  # @line L8


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


def finish(c: Config) -> Tuple[List[int], List[Optional[str]]]:
    """Return the tree of a terminal configuration: headless words go to the root."""
    heads, labels = list(c.heads), list(c.labels)
    for d in range(1, c.n + 1):  # @line L9
        if heads[d] == -1:
            heads[d], labels[d] = 0, "root"
    return heads, labels


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


def parse(n: int, score: Scorer, label_set: Sequence[str] = ("dep",)):
    """Greedy parsing. Returns (heads, labels, transitions)."""
    c = Config(n)  # @line L1
    seq: List[Transition] = []
    while not c.is_terminal():  # @line L2
        best = None
        for t in legal_transitions(c, label_set):  # @line L3
            s = score(c, t)  # @line L4
            if best is None or s > best[0]:
                best = (s, t)
        apply(c, best[1])
        seq.append(best[1])
    heads, labels = finish(c)
    return heads, labels, seq  # @line L10


def static_oracle(c: Config, gold_heads: Sequence[int], gold_labels: Sequence[Optional[str]]) -> Transition:
    """A static oracle for a projective gold tree.

    LEFT-ARC if b is the gold head of s; RIGHT-ARC if s is the gold head of b;
    REDUCE if s has its head and no gold dependent of s is left in the buffer;
    SHIFT otherwise.
    """
    s, b = c.stack[-1], c.next
    if s != 0 and gold_heads[s] == b:
        return ("LA", gold_labels[s])
    if gold_heads[b] == s:
        return ("RA", gold_labels[b])
    if s != 0 and c.heads[s] != -1 and not any(gold_heads[k] == s for k in range(b, c.n + 1)):
        return REDUCE
    return SHIFT


def oracle_sequence(gold_heads: Sequence[int], gold_labels: Optional[Sequence[Optional[str]]] = None) -> List[Transition]:
    """Run the static oracle; raise ValueError if it builds another tree (a non-projective gold tree)."""
    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 not is_legal(c, t):
            raise ValueError("the oracle is stuck: the tree is not projective")
        apply(c, t)
        seq.append(t)
    heads, _ = finish(c)
    if heads != list(gold_heads):
        raise ValueError("the oracle built another tree: the gold tree is not projective")
    return seq


def cost(c: Config, t: Transition, gold_heads: Sequence[int]) -> int:
    """The number of gold arcs that are reachable from c but not after t (unlabeled).

    The gold tree must be projective. Here sigma is the stack below s and beta
    is the buffer after b.
    """
    if not is_legal(c, t):
        raise ValueError("illegal transition")
    s, b, n = c.stack[-1], c.next, c.n
    below = set(c.stack[:-1])
    beta = range(b + 1, n + 1)
    kind = t[0]
    if kind == "LA":
        lost = 1 if (gold_heads[s] == 0 or gold_heads[s] > b) else 0
        return lost + sum(1 for k in range(b, n + 1) if gold_heads[k] == s)
    if kind == "RA":
        g = gold_heads[b]
        lost = 1 if (g in below or g > b) else 0
        return lost + sum(1 for k in below | {s} if k != 0 and c.heads[k] == -1 and gold_heads[k] == b)
    if kind == "RE":
        return sum(1 for k in range(b, n + 1) if gold_heads[k] == s)
    g = gold_heads[b]
    lost = 1 if (g != 0 and (g in below or g == s)) else 0
    return lost + sum(1 for k in below | {s} if k != 0 and c.heads[k] == -1 and gold_heads[k] == b)


def dynamic_oracle(c: Config, gold_heads: Sequence[int]) -> List[Transition]:
    """Return the legal unlabeled transitions of cost 0 (labels are ignored)."""
    return [t for t in legal_transitions(c, ["dep"]) if cost(c, t, gold_heads) == 0]
test_arc_eager_parsing.py 194 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/arc-eager-parsing/. The authors are listed in prov/BSRJBW.jsonl.

import itertools
import random

import pytest

from arc_eager_parsing import (
    REDUCE,
    SHIFT,
    Config,
    apply,
    cost,
    dynamic_oracle,
    finish,
    is_legal,
    legal_transitions,
    oracle_sequence,
    parse,
    static_oracle,
)

GOLD_HEADS = [-1, 2, 3, 0, 6, 6, 3]  # the cat sat on the mat
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)}
PROJ = {n: [t for t in TREES[n] if is_projective(t)] for n in TREES}


def all_complete_runs(n):
    out = []
    todo = [(Config(n), 0)]
    while todo:
        c, steps = todo.pop()
        if c.is_terminal():
            out.append((tuple(finish(c)[0]), steps))
            continue
        for t in legal_transitions(c, ["dep"]):
            c2 = c.copy()
            apply(c2, t)
            todo.append((c2, steps + 1))
    return out


def min_loss(c, gold, memo):
    """Brute force: the smallest Hamming loss of a tree reachable from c."""
    k = c.key()
    if k in memo:
        return memo[k]
    if c.is_terminal():
        heads, _ = finish(c)
        v = sum(1 for d in range(1, c.n + 1) if heads[d] != gold[d])
    else:
        v = None
        for t in legal_transitions(c, ["dep"]):
            c2 = c.copy()
            apply(c2, t)
            x = min_loss(c2, gold, memo)
            v = x if v is None else min(v, x)
    memo[k] = v
    return v


def reachable_configs(n):
    seen, out, todo = set(), [], [Config(n)]
    while todo:
        c = todo.pop()
        if c.key() in seen:
            continue
        seen.add(c.key())
        out.append(c)
        if not c.is_terminal():
            for t in legal_transitions(c, ["dep"]):
                c2 = c.copy()
                apply(c2, t)
                todo.append(c2)
    return out


CONFIGS = {n: reachable_configs(n) for n in range(1, 6)}


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", "LA-det", "SH", "LA-nsubj", "RA-root", "SH", "SH", "LA-det", "LA-case", "RA-obl"]


def test_sound_and_complete_for_projective_trees():
    for n in range(1, 6):
        runs = all_complete_runs(n)
        assert {h for h, _ in runs} == {tuple(t) for t in PROJ[n]}
        assert all(n <= steps <= 2 * n for _, steps in runs)
        assert max(steps for _, steps in runs) == 2 * n - 1 if n > 1 else True


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


def check_costs(n, gold):
    memo = {}
    for c in CONFIGS[n]:
        if c.is_terminal():
            continue
        base = min_loss(c, gold, memo)
        zero = 0
        for t in legal_transitions(c, ["dep"]):
            c2 = c.copy()
            apply(c2, t)
            brute = min_loss(c2, gold, memo) - base
            assert cost(c, t, gold) == brute, (c.key(), t, gold)
            zero += brute == 0
        assert zero >= 1


def test_dynamic_oracle_cost_equals_brute_force_small():
    for n in range(1, 5):
        for gold in PROJ[n]:
            check_costs(n, gold)


def test_dynamic_oracle_cost_equals_brute_force_n5():
    rng = random.Random(4)
    for gold in rng.sample(PROJ[5], 12):
        check_costs(5, gold)


def test_dynamic_oracle_recovers_after_an_error():
    # Take a wrong first step, then follow the dynamic oracle: the loss is the
    # smallest one still reachable.
    gold = GOLD_HEADS
    c = Config(6)
    apply(c, ("RA", "dep"))  # attaches "the" to the root: one gold arc is lost
    memo = {}
    best = min_loss(c, gold, memo)
    while not c.is_terminal():
        apply(c, dynamic_oracle(c, gold)[0])
    heads, _ = finish(c)
    assert sum(1 for d in range(1, 7) if heads[d] != gold[d]) == best == 1


def test_greedy_parse_and_preconditions():
    rng = random.Random(8)
    for _ in range(200):
        n = rng.randint(1, 8)
        heads, labels, seq = parse(n, lambda c, t: rng.random(), ["x"])
        assert n <= len(seq) <= 2 * n
        assert is_tree(heads) and is_projective(heads)
    c = Config(2)
    assert not is_legal(c, ("LA", "x"))  # s is the root
    assert not is_legal(c, REDUCE)  # the root never has a head
    apply(c, SHIFT)
    assert is_legal(c, ("LA", "x")) and not is_legal(c, REDUCE)
    apply(c, ("LA", "x"))
    apply(c, ("RA", "x"))
    assert c.is_terminal() and not is_legal(c, SHIFT)
    assert static_oracle(Config(1), [-1, 0], [None, "root"]) == ("RA", "root")

History

Nivre (2003) described a deterministic parser for projective dependency trees with the four moves of this page, and proved that it runs in linear time. Nivre (2004) compared it with the arc-standard strategy and called it arc-eager, because right dependents are attached at the first opportunity. Nivre (2008) set both systems in a common framework of transition systems with formal proofs, and they became the base of the MaltParser system. Zhang and Clark (2008) and others added beam search and global training. Goldberg and Nivre (2012) defined the dynamic oracle for arc-eager parsing and showed that training on the parser's own errors improves accuracy, and Goldberg and Nivre (2013) extended the idea to other systems.

References

  1. Joakim Nivre, An efficient algorithm for projective dependency parsing, IWPT 2003, the four transitions, the linear bound on their number, and projectivity of the output
  2. Joakim Nivre, Incrementality in deterministic dependency parsing, Workshop on Incremental Parsing, ACL 2004, the comparison of the arc-standard and arc-eager strategies
  3. Joakim Nivre, Algorithms for deterministic incremental dependency parsing, Computational Linguistics 34(4), 513-553, 2008, the arc-eager system in the stack and buffer form, its soundness, completeness and complexity
  4. Yoav Goldberg and Joakim Nivre, A dynamic oracle for arc-eager dependency parsing, COLING 2012, the cost of each transition and the dynamic oracle for arc-eager
  5. 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

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