Algorithmadvanced
Arc-hybrid parsing
Also called arc-hybrid transition system.
A transition system that takes left-arc from arc-eager and right-arc from arc-standard. It has a simple exact dynamic oracle.
- 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
- Marco Kuhlmann, Carlos Gómez Rodríguez, Giorgio Satta, 2011
Arc-hybrid parsing is a transition system for dependency parsing that combines the moves of two older systems. Its LEFT-ARC is the one of arc-eager parsing: the buffer front becomes the head of the stack top, which is popped. Its RIGHT-ARC is the one of arc-standard parsing: the second stack word becomes the head of the stack top, which is popped. With SHIFT, these three moves build exactly the projective trees in exactly moves for words, and every word gets its head at the moment it leaves the stack, with all its dependents already in place. Kuhlmann, Gómez-Rodríguez and Satta (2011) defined the system and showed that, for arc scores, its computations can be searched exactly in time. Goldberg and Nivre (2013) showed that it has a simple exact dynamic oracle, which made it a common choice for greedy parsers trained on their own errors.
In plain words
Read the words one at a time onto a pile. Look at the top word of the pile, the word under it, and the next unread word. When the top word has collected all its dependents, it is finished, and it gets its own head in one of two ways: the next unread word can become its head, or the word under it on the pile can become its head. Either way the top word leaves the pile. Otherwise read the next word onto the pile. In the end only the start symbol is left, and each word has one arrow into it. 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. The output is a labeled projective dependency tree. In the version on this page the root may have several children: RIGHT-ARC can attach any number of words to the root. The rule of arc-standard parsing, RIGHT-ARC from the root only when the buffer is empty, gives exactly one root child here too.
The algorithm
A configuration is with stack top , the word below it , and buffer front . The initial configuration is and the terminal ones are . The transitions, for each label :
| transition | before | after | condition |
|---|---|---|---|
| SHIFT | |||
| LEFT-ARC | |||
| RIGHT-ARC |
The greedy parser:
ARC-HYBRID-PARSE(x, score)- 1
c <- ([0], [1, ..., n], {}) - 2
while c is not terminal 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-> s0 and pop s0 - 7
if t = RIGHT-ARC_l then add s1 -l-> s0 and pop s0 - 8
return the tree A
The static oracle. If has all its gold dependents: LEFT-ARC if its gold head is , RIGHT-ARC if its gold head is . Otherwise SHIFT.
The dynamic oracle. The cost of a transition is the number of gold arcs that it makes impossible to build. For a projective gold tree, with the stack below and the buffer after :
- LEFT-ARC loses the gold dependents of in , and the gold arc into if its head is or in .
- RIGHT-ARC loses the gold dependents of in , and the gold arc into if its head is or in .
- SHIFT loses the gold dependents of on the stack, and the gold arc into if its head is on the stack below .
The dynamic oracle allows every legal transition of cost 0. These costs are exact: the best tree still reachable loses exactly the arcs counted so far, so no move of cost 0 ever makes things worse.
Example
Parse the cat sat on the mat (words 1 to 6) with the gold heads [-1, 2, 3, 0, 6, 6, 3]. The static 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 | 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 | SH | 0 3 | 4 5 6 | |
| 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 | SH | 0 3 6 | ||
| 11 | RA-obl | 0 3 | sat mat | |
| 12 | RA-root | 0 | root sat |
The left arcs come as early as in arc-eager parsing (steps 2, 4, 8, 9), and the right arcs come bottom up as in arc-standard parsing (steps 11 and 12).
A wrong step. Suppose the parser shifts twice at the start, so that the lies under cat on the stack. The arc cat the is lost: the can now get a head only from the buffer front or from the word under it, and cat is neither. The cost of the second SHIFT is 1, because the is a gold dependent of the buffer front cat and lies on the stack. Following the dynamic oracle from there gives a tree with exactly one wrong head, the least possible. The tests check this case.
Correctness
Every run ends in a tree after moves. SHIFT is legal while the buffer is not empty, and RIGHT-ARC is legal while the stack has two words, so a configuration that is not terminal always has a legal move. Each word is shifted once and popped once, by an arc that gives it its head, so there are exactly moves and every word gets exactly one head. A word gets its head only when it leaves the stack, and after that it is never a head again, so no cycle can form.
The tree is projective. The partial subtrees of the stack words and of the buffer front are consecutive intervals in this order. LEFT-ARC joins the interval of to the interval of on its right, and RIGHT-ARC joins the two top intervals, so every subtree stays an interval.
Every projective tree is reached. For a word, build the subtrees of its left dependents one after the other, attach them with LEFT-ARC when the word is the buffer front, SHIFT the word, and then build each right dependent's subtree and attach it with RIGHT-ARC. The proofs are in the correctness proof. The tests build all complete sequences for and find exactly the projective trees, each sequence of length .
The dynamic oracle. The tests compare the cost formulas with the true cost, the loss of the best tree still reachable minus the loss already incurred, found by search over all transition sequences, in every reachable configuration, for every projective gold tree with and for 12 sampled gold trees with .
Proof: The arc-hybrid system is sound and complete for projective trees, and every run ends after 2n transitionsfull
The words are and 0 is the root. A configuration is with from bottom to top and buffer , a suffix of the sentence. For a word , is the set of words below in , included. When the buffer is empty, put and .
Lemma 1 (invariant). Every configuration reached from the initial one satisfies:
- (a) , and no arc enters 0;
- (b) a word has a head in exactly when it has been shifted and popped; in particular, no stack word and no buffer word has a head;
- (c) has no cycle;
- (d) are consecutive intervals in this order, and their union is (or when the buffer is empty); the buffer words after have no dependents in ;
- (e) for each arc in , every word strictly between and is in .
Proof. At the start , , , and all hold. SHIFT pushes , whose interval is already next in line, and the new front has by the last part of (d). LEFT-ARC adds with and pops , which had no head by (b). No cycle closes, because has no head, so no path of heads leads from to . The intervals of and are neighbours, so becomes their union, an interval, and every word strictly between and lies in it, which gives (e). RIGHT-ARC adds and pops ; had no head, no cycle closes because is not below (their intervals are disjoint), the two top intervals merge, and (e) holds for the new arc in the same way. Older arcs keep (e) because partial yields only grow.
Theorem 2 (soundness and termination). Every run ends after exactly transitions in a terminal configuration whose arcs form a projective tree rooted at 0.
Proof. No dead end. If the configuration is not terminal, either the buffer is not empty and SHIFT is legal, or the buffer is empty and the stack has two or more words, and RIGHT-ARC is legal. Count. The quantity is at the start and 1 at the end, and every transition lowers it by exactly one: SHIFT moves a word from the buffer to the stack, LEFT-ARC and RIGHT-ARC pop one word. So there are exactly transitions. Tree. At the end, and the buffer is empty, so by (b) every word has a head, exactly one since a word gets its head only when it is popped, and by (c) there is no cycle; following heads from any word ends at 0. Projective. By (e), the head of every arc dominates every word strictly between its ends.
Theorem 3 (completeness). For every projective tree there is a run that ends with .
Proof. For a word with gold left dependents and right dependents , let
Since is projective, the yield is an interval, split into the consecutive intervals .
Claim. If the buffer front is and the stack is , then is legal and ends with the stack , the buffer front , and exactly the arcs of inside added. By induction on : the calls leave with the front at . Each LEFT-ARC then attaches the stack top to the front : first , then , down to ; they are not 0, so the moves are legal. SHIFT pushes . Each leaves above , and RIGHT-ARC attaches to and pops it.
For the whole tree, with root children , all to the right of 0, run , RIGHT-ARC, ..., , RIGHT-ARC. Each block leaves and then adds . The yields cover in order, so the run ends in . With one root child, the only RIGHT-ARC from 0 is the last move, when the buffer is empty, so the single-root rule allows it.
The static oracle. The sequence of Theorem 3 is the one that the static oracle produces: it makes an arc as soon as the stack top is complete and its gold head is the buffer front or the word below it, and shifts otherwise. The tests check that the oracle rebuilds every projective tree with in moves and fails on every non-projective tree, and that the set of trees built by all complete sequences for is exactly the set of projective trees.
The dynamic oracle. The exactness of the cost formulas on the main page is due to Goldberg and Nivre (2013), through arc decomposition. Here it is checked by search: for every projective gold tree with and 12 sampled gold trees with , and for every reachable configuration, the tests compute the true cost of each move, the least loss reachable after it minus the least loss reachable before it, and compare it with the formula.
Complexity
Transitions. Exactly : shifts and arcs.
Time. Each step scores at most transitions, so the greedy parse takes time with a scorer of constant cost. The cost of a transition in the dynamic oracle takes time as written, by a scan of the stack and the buffer.
Exact search. The deduction system of Kuhlmann et al. uses items , : a computation that pushes word and moves the buffer front from to . Two adjacent items and combine into with the arc (a LEFT-ARC, if ) or the arc (a RIGHT-ARC). With one score per arc this takes time and space, and finds the best projective tree. The tests check it against a search over all trees, and use the same system to count the complete sequences: 1, 3, 13, 67, 381 for to 5.
Properties
- Sound and complete for projective trees, in exactly moves.
- Bottom up. Every word has all its dependents before it gets its head; there is no REDUCE.
- Spurious ambiguity. A tree can have several sequences: for to 5 there are 1, 3, 13, 67, 381 sequences for 1, 3, 12, 55, 273 trees. The tree
[-1, 0, 3, 0]has two: the arc root 1 can be made before or after the arc . - Arc-decomposable. If each gold arc is still reachable on its own from a configuration, all of them are reachable together. This is why the cost is a simple count, and why the dynamic oracle is exact.
- Exact search in cubic time. With arc scores, the computations can be searched by the deduction system above, the same order of time as the Eisner algorithm.
- Not exact when greedy. The greedy parser can miss the best tree under a given score.
Variants and improvements
- Training with the dynamic oracle. Let the parser follow its own predictions during training, sometimes taking a wrong move on purpose, and train it to choose a move of cost 0 in every configuration it reaches. This is an instance of imitation learning, close to DAgger.
- Neural features. Kiperwasser and Goldberg (2016) used arc-hybrid with features from a bidirectional recurrent network over the sentence, trained with the dynamic oracle.
- Non-projective trees. The system builds only projective trees. The swap system shows how a SWAP move that reorders words removes this limit for arc-standard parsing.
- Beam search. Keeping the best configurations, as in beam search, works as for the other systems.
When to use it
Use arc-hybrid parsing for a greedy or beam parser of projective trees when training with a dynamic oracle, which is simpler and exact here, or when exact search over the transition sequences is wanted. For a system with eager right arcs, use arc-eager. For many crossing arcs, use the swap system or an MST parser.
Pitfalls
- LEFT-ARC needs a buffer. The head of LEFT-ARC is the buffer front, so it is not legal when the buffer is empty; only RIGHT-ARC finishes the parse.
- LEFT-ARC on the root. The root must not get a head; the condition guards this.
- Several root children. Without the single-root rule, the parser can attach several words to the root.
- Using arc-standard costs. The dynamic oracle of arc-hybrid does not carry over to arc-standard, where the cost of a move is not a simple count; arc-standard is not arc-decomposable.
- Spurious ambiguity in the dynamic program. Sums over computations count trees with several sequences more than once; use the deduction system for maxima, or for counting sequences, not for counting trees.
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-hybrid-parsing/. The authors are listed in prov/TTAZ45.jsonl.
"""The arc-hybrid transition system, its oracles and its cubic-time dynamic program.
The words are 1..n and 0 is the artificial root. A configuration is
(stack, buffer, arcs); the stack starts as [0], its top is s0 and the element
under it s1; the buffer front is b. The transitions are ("SH", None),
("LA", label) and ("RA", label):
SHIFT (sigma, b|beta, A) => (sigma|b, beta, A)
LEFT-ARC_l (sigma|s0, b|beta, A) => (sigma, b|beta, A + {(b, l, s0)}) needs s0 != 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 n shifts
and n arcs, so exactly 2n transitions. A word gets its head when it is popped,
so the words on the stack never have a head.
cost() is the dynamic oracle of Goldberg and Nivre (2013), section 4.5, with the
root at the bottom of the stack. viterbi_dp() and count_dp() are the deduction
system of Kuhlmann, Gomez-Rodriguez and Satta (2011), section 6, for scores
that add one score per arc.
"""
from typing import Callable, List, Optional, Sequence, Tuple
Transition = Tuple[str, Optional[str]]
SHIFT: Transition = ("SH", None)
class Config:
def __init__(self, n: int):
self.n = n
self.stack: List[int] = [0]
self.next = 1
self.heads = [-1] * (n + 1)
self.labels: List[Optional[str]] = [None] * (n + 1)
def is_terminal(self) -> bool:
return self.next > self.n and len(self.stack) == 1
def copy(self) -> "Config":
c = Config(self.n)
c.stack = list(self.stack)
c.next = self.next
c.heads = list(self.heads)
c.labels = list(self.labels)
return c
def key(self):
return (tuple(self.stack), self.next, tuple(self.heads))
def is_legal(c: Config, t: Transition) -> bool:
kind = t[0]
if kind == "SH":
return c.next <= c.n
if kind == "LA":
return c.next <= c.n and c.stack[-1] != 0
if kind == "RA":
return len(c.stack) >= 2
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":
s0 = c.stack.pop() # @line L6
c.heads[s0], c.labels[s0] = c.next, label
else:
s0 = c.stack.pop() # @line L7
c.heads[s0], c.labels[s0] = c.stack[-1], label
def legal_transitions(c: Config, label_set: Sequence[str]) -> 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)):
out.append((kind, lab))
return out
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])
return c.heads, c.labels, seq # @line L8
def _complete(c: Config, w: int, gold_heads: Sequence[int]) -> bool:
return all(c.heads[d] == w for d in range(1, c.n + 1) if gold_heads[d] == w)
def static_oracle(c: Config, gold_heads: Sequence[int], gold_labels: Sequence[Optional[str]]) -> Optional[Transition]:
"""LEFT-ARC or RIGHT-ARC when s0 has all its dependents and its gold head is b or s1; else SHIFT."""
s0 = c.stack[-1]
if s0 != 0 and _complete(c, s0, gold_heads):
if c.next <= c.n and gold_heads[s0] == c.next:
return ("LA", gold_labels[s0])
if len(c.stack) >= 2 and gold_heads[s0] == c.stack[-2]:
return ("RA", gold_labels[s0])
return SHIFT if c.next <= c.n else None
def oracle_sequence(gold_heads: Sequence[int], gold_labels: Optional[Sequence[Optional[str]]] = None) -> List[Transition]:
"""Run the static oracle; raise ValueError if it cannot build the gold tree (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 != list(gold_heads):
raise ValueError("the oracle built another tree")
return seq
def cost(c: Config, t: Transition, gold_heads: Sequence[int]) -> int:
"""The number of gold arcs that t makes unreachable (unlabeled, projective gold tree)."""
if not is_legal(c, t):
raise ValueError("illegal transition")
n, b = c.n, c.next
s0 = c.stack[-1]
s1 = c.stack[-2] if len(c.stack) >= 2 else None
rest = set(range(b + 1, n + 1)) # beta, the buffer after b
kind = t[0]
if kind == "LA":
heads_lost = ({s1} | rest) - {None}
deps_lost = {b} | rest
elif kind == "RA":
heads_lost = {b} | rest if b <= n else set()
deps_lost = heads_lost
else:
below = set(c.stack[:-2])
heads_lost = below | ({s1} - {None})
deps_lost = below | {s0} | ({s1} - {None})
g = gold_heads[b]
return int(g in heads_lost) + sum(1 for d in deps_lost if d != 0 and gold_heads[d] == b)
return int(gold_heads[s0] in heads_lost) + sum(1 for d in deps_lost if gold_heads[d] == s0)
def dynamic_oracle(c: Config, gold_heads: Sequence[int]) -> List[Transition]:
return [t for t in legal_transitions(c, ["dep"]) if cost(c, t, gold_heads) == 0]
def viterbi_dp(scores: Sequence[Sequence]) -> Tuple[object, List[int]]:
"""The deduction system of Kuhlmann et al. (2011) for the hybrid system, with arc scores.
The item [i, j] (0 <= i < j <= n + 1) stands for a computation that pushes
word i and moves the buffer front from i to j. Rules: [i, j] gives [j, j + 1]
(shift); [i, k] and [k, j] give [i, j] with the arc j -> k when j <= n
(left-arc) or with the arc i -> k (right-arc). The goal is [0, n + 1].
Returns the best total score over all complete computations and its tree.
"""
n = len(scores) - 1
m = n + 1
V = [[None] * (m + 1) for _ in range(m + 1)]
back = [[None] * (m + 1) for _ in range(m + 1)]
for i in range(m):
V[i][i + 1] = 0
for length in range(2, m + 1):
for i in range(0, m - length + 1):
j = i + length
for k in range(i + 1, j):
if V[i][k] is None or V[k][j] is None:
continue
base = V[i][k] + V[k][j]
if j <= n and (V[i][j] is None or base + scores[j][k] > V[i][j]):
V[i][j], back[i][j] = base + scores[j][k], (k, j)
if V[i][j] is None or base + scores[i][k] > V[i][j]:
V[i][j], back[i][j] = base + scores[i][k], (k, i)
heads = [-1] * (n + 1)
todo = [(0, m)]
while todo:
i, j = todo.pop()
if j == i + 1:
continue
k, h = back[i][j]
heads[k] = h
todo.append((i, k))
todo.append((k, j))
return V[0][m], heads
def count_dp(n: int) -> int:
"""The number of complete computations, by the same deduction system."""
m = n + 1
N = [[0] * (m + 1) for _ in range(m + 1)]
for i in range(m):
N[i][i + 1] = 1
for length in range(2, m + 1):
for i in range(0, m - length + 1):
j = i + length
ways = 2 if j <= n else 1
N[i][j] = sum(N[i][k] * N[k][j] for k in range(i + 1, j)) * ways
return N[0][m]
test_arc_hybrid_parsing.py 202 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/arc-hybrid-parsing/. The authors are listed in prov/TTAZ45.jsonl.
import itertools
import random
import pytest
from arc_hybrid_parsing import (
SHIFT,
Config,
apply,
cost,
count_dp,
dynamic_oracle,
is_legal,
legal_transitions,
oracle_sequence,
parse,
viterbi_dp,
)
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(c.heads), steps))
continue
for t in legal_transitions(c, ["dep"]):
c2 = c.copy()
apply(c2, t)
todo.append((c2, steps + 1))
return out
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 min_loss(c, gold, memo):
k = c.key()
if k in memo:
return memo[k]
if c.is_terminal():
v = sum(1 for d in range(1, c.n + 1) if c.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 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_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", "SH", "SH", "SH", "LA-det", "LA-case", "SH", "RA-obl", "RA-root"]
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(steps == 2 * n for _, steps in runs)
# The deduction system counts computations, not trees.
assert count_dp(n) == len(runs)
assert [count_dp(n) for n in range(1, 6)] == [1, 3, 13, 67, 381]
def test_spurious_ambiguity():
# 0 -> 1, 0 -> 3, 3 -> 2: RIGHT-ARC 0 -> 1 can come before or after LEFT-ARC 3 -> 2.
runs = [h for h, _ in all_complete_runs(3) if h == (-1, 0, 3, 0)]
assert len(runs) == 2
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 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(6)
for gold in rng.sample(PROJ[5], 12):
check_costs(5, gold)
def test_dynamic_oracle_after_an_error():
gold = GOLD_HEADS
c = Config(6)
apply(c, SHIFT)
apply(c, SHIFT) # "the" can no longer get its head "cat": one gold arc is lost
best = min_loss(c, gold, {})
while not c.is_terminal():
apply(c, dynamic_oracle(c, gold)[0])
assert sum(1 for d in range(1, 7) if c.heads[d] != gold[d]) == best == 1
def test_viterbi_dp_against_brute_force():
rng = random.Random(10)
for n in range(1, 6):
for _ in range(20 if n < 5 else 8):
s = [[rng.randint(-9, 9) for _ in range(n + 1)] for _ in range(n + 1)]
best = max(sum(s[t[d]][d] for d in range(1, n + 1)) for t in PROJ[n])
score, heads = viterbi_dp(s)
assert score == best
assert is_tree(heads) and is_projective(heads)
assert sum(s[heads[d]][d] for d in range(1, n + 1)) == score
def test_greedy_and_preconditions():
rng = random.Random(12)
for _ in range(200):
n = rng.randint(1, 8)
heads, _, seq = parse(n, lambda c, t: rng.random(), ["x"])
assert len(seq) == 2 * n and is_tree(heads) and is_projective(heads)
c = Config(1)
assert not is_legal(c, ("LA", "x")) and not is_legal(c, ("RA", "x"))
apply(c, SHIFT)
assert not is_legal(c, SHIFT) and not is_legal(c, ("LA", "x")) and is_legal(c, ("RA", "x"))
History
Kuhlmann, Gómez-Rodríguez and Satta (2011) studied dynamic programming for transition-based parsers and defined the arc-hybrid system, which joins the LEFT-ARC of arc-eager parsing with the RIGHT-ARC of arc-standard parsing; for it, the deduction system is cubic. Goldberg and Nivre (2012) introduced dynamic oracles for arc-eager parsing, and Goldberg and Nivre (2013) defined arc decomposition and gave dynamic oracles for arc-hybrid and other systems. Arc-hybrid with a dynamic oracle then became a standard base for neural greedy parsers.
References
- Marco Kuhlmann, Carlos Gómez-Rodríguez and Giorgio Satta, Dynamic programming algorithms for transition-based dependency parsers, ACL 2011, the arc-hybrid system and its deduction system over items [i, j] in cubic time
- Yoav Goldberg and Joakim Nivre, Training deterministic parsers with non-deterministic oracles, Transactions of the Association for Computational Linguistics 1, 2013, arc decomposition, and the costs of the arc-hybrid transitions for the dynamic oracle
- Joakim Nivre, Algorithms for deterministic incremental dependency parsing, Computational Linguistics 34(4), 513-553, 2008, the arc-standard and arc-eager systems from which arc-hybrid takes its moves
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 TTAZ45 Edit this page History Report an error Markdown