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.
- Solves
- Dependency parsing
- 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
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 moves for 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 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 , as in arc-standard parsing, with the stack top and the buffer front . The initial configuration is , and every configuration with an empty buffer is terminal. The transitions, for each label :
| transition | before | after | condition |
|---|---|---|---|
| SHIFT | |||
| LEFT-ARC | , has no head | ||
| RIGHT-ARC | |||
| REDUCE | has a head |
The greedy parser:
ARC-EAGER-PARSE(x, score)- 1
c <- ([0], [1, ..., n], {}) - 2
while the buffer of c is not empty do - 3
for each legal transition t of c - 4
compute score(c, t), and keep the best t - 5
if t = SHIFT then push b - 6
if t = LEFT-ARC_l then add b -l-> s and pop s - 7
if t = RIGHT-ARC_l then add s -l-> b and push b - 8
if t = REDUCE then pop s - 9
attach every word without a head to the root 0, with the label root - 10
return the tree A
The static oracle. For a projective gold tree: choose LEFT-ARC if is the gold head of ; RIGHT-ARC if is the gold head of ; REDUCE if has its head and no gold dependent of 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 the |
| 3 | SH | 0 2 | 3 4 5 6 | |
| 4 | LA-nsubj | 0 | 3 4 5 6 | sat cat |
| 5 | RA-root | 0 3 | 4 5 6 | root sat |
| 6 | SH | 0 3 4 | 5 6 | |
| 7 | SH | 0 3 4 5 | 6 | |
| 8 | LA-det | 0 3 4 | 6 | mat the |
| 9 | LA-case | 0 3 | 6 | mat on |
| 10 | RA-obl | 0 3 6 | sat 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 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 and the buffer front , and every word between them has been pushed after 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 : 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 and 0 is the root. A configuration is with stack top and buffer front ; the buffer is always , since only SHIFT and RIGHT-ARC change it and both take the front. "Before time " 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 , 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 of a stack word is a stack word below it;
- (e) has no cycle.
Proof. At the start all hold. (a): SHIFT and RIGHT-ARC push , which is larger than every shifted word; pops keep the order; 0 is never popped, since LEFT-ARC and REDUCE need (REDUCE needs a head, and 0 never has one by (c)). (b): LEFT-ARC pops 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 without a head and ; RIGHT-ARC gives a head to , which has none by (b). (d): RIGHT-ARC gives the head , directly below 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 ; a cycle through the new arc would need a path of heads from up to , but has no head. RIGHT-ARC adds ; a cycle would need to be an ancestor of , but by (d) all ancestors of are on the stack, and is not.
Lemma 2 (no arc passes over a stack word). If , is on the stack in some configuration, and contains an arc between and in that configuration or later, then 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, was the top and the front. Then had been shifted. If were on the stack at that time, (a) would give , since is the top; but .
Theorem 3 (soundness and termination). Every run ends after at most 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 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 of them. So the run ends, after at most 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, added before , with and , both added by LEFT-ARC or RIGHT-ARC. When was added, was the top and the front. If they crossed, one endpoint of would lie strictly between and and the other outside. The endpoint was the front at an earlier time, so . If : when was added, had been shifted, and is on the stack later, at the time of , so it was on the stack then too, since a popped word is never pushed again. That contradicts Lemma 2 for . If : impossible, since . The arcs of line L9 join 0 to a word that is on the stack at the end; an arc crosses only if with , which Lemma 2 forbids, and two arcs from 0 cannot cross.
Theorem 4 (completeness). For every projective tree with heads , the static oracle produces a legal run whose final arcs, before line L9, are exactly .
Proof. We show that the oracle run keeps two properties: (i) ; (ii) every arc of whose two endpoints are both smaller than is in .
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 ; then , and has no head. Indeed, by (i) a head of in would be ; but an arc from a larger word to a smaller one is added only by LEFT-ARC, which pops the dependent, and is still on the stack. REDUCE is chosen only when has a head. Every arc added is a gold arc, so (i) holds.
(ii). LEFT-ARC and REDUCE do not move and only add arcs, so (ii) is kept. Consider a buffer move of , by SHIFT or RIGHT-ARC. The new gold arcs with both endpoints below are the arcs between and smaller words: the arc from a gold head , and the arcs to the gold dependents of .
First, the dependents. Suppose with and the arc not in . Then has no head by (i), so by (b) it is on the stack. If , the oracle would choose LEFT-ARC, not a buffer move. So by (a). The gold arc passes over , so dominates in . The gold head is not , or the oracle would choose LEFT-ARC. It is not larger than : the arc would pass over , so would dominate , while dominates and hence its parent . So , and by (ii) the arc is in ; has a head. A gold dependent of is impossible: would make the parent of and an ancestor of ; would make the arc pass over , so would dominate , which dominates . 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 , while dominates . This contradicts the buffer move.
Next, the head. Suppose and the oracle moves without adding , so it chooses SHIFT and . If had been popped, then by LEFT-ARC with a head , or by REDUCE. REDUCE was impossible, since , a gold dependent of , was in the buffer. A LEFT-ARC gave the gold head : would make and each other's parents, and would make the gold arc pass over , so would dominate its own parent. So is on the stack, and . The gold arc passes over , so dominates . The gold head is not (the oracle would choose LEFT-ARC) and not larger than (the arc would pass over , so would dominate and its parent , while dominates and its parent ; this forces , a contradiction). So and by (ii) has a head. A gold dependent of is impossible: contradicts , and makes dominate and its parent , while dominates . So the oracle would choose REDUCE, a contradiction.
End. When the buffer is empty, , and (ii) says that every arc of is in . With (i), before line L9, and line L9 adds nothing.
The tests check Theorems 3 and 4 by brute force: for 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 of them. LEFT-ARC and REDUCE each pop a word that some earlier SHIFT or RIGHT-ARC pushed, so there are at most of them. A complete sequence therefore has between and transitions; with the terminal condition of this page the tests find at most .
Time. Each step scores at most transitions. With a scorer of constant cost for a fixed label set, the parse takes time, and line L9 adds .
Space. 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 to 5; already for 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 in the buffer, plus 1 if the gold head of is in the buffer after or is the root. The cost of RIGHT-ARC counts the gold arc into if its head is deeper in the stack or later in the buffer, plus the headless stack words whose gold head is . The cost of REDUCE is the number of gold dependents of in the buffer. SHIFT loses the gold arcs between 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 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 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 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 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.
# 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
- 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
- Joakim Nivre, Incrementality in deterministic dependency parsing, Workshop on Incremental Parsing, ACL 2004, the comparison of the arc-standard and arc-eager strategies
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag BSRJBW Edit this page History Report an error Markdown