Algorithm Search⌘K

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.

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
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 2n2n moves for nn 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 O(n3)O(n^3) 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 w1⋯wnw_1 \cdots w_n 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 (σ,β,A)(\sigma, \beta, A) with stack top s0s_0, the word below it s1s_1, and buffer front bb. The initial configuration is ([0],[1,…,n],∅)([0], [1, \ldots, n], \emptyset) and the terminal ones are ([0],[ ],A)([0], [\,], A). The transitions, for each label ll:

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

The greedy parser:

  1. ARC-HYBRID-PARSE(x, score)
  2. 1c <- ([0], [1, ..., n], {})
  3. 2while c is not terminal 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-> s0 and pop s0
  8. 7if t = RIGHT-ARC_l then add s1 -l-> s0 and pop s0
  9. 8return the tree A

The static oracle. If s0≠0s_0 \ne 0 has all its gold dependents: LEFT-ARC if its gold head is bb, RIGHT-ARC if its gold head is s1s_1. 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 σ\sigma the stack below s1s_1 and β\beta the buffer after bb:

  • LEFT-ARC loses the gold dependents of s0s_0 in {b}∪β\{b\} \cup \beta, and the gold arc into s0s_0 if its head is s1s_1 or in β\beta.
  • RIGHT-ARC loses the gold dependents of s0s_0 in {b}∪β\{b\} \cup \beta, and the gold arc into s0s_0 if its head is bb or in β\beta.
  • SHIFT loses the gold dependents of bb on the stack, and the gold arc into bb if its head is on the stack below s0s_0.

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 →\to the
3 SH 0 2 3 4 5 6
4 LA-nsubj 0 3 4 5 6 sat →\to 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 →\to the
9 LA-case 0 3 6 mat →\to on
10 SH 0 3 6
11 RA-obl 0 3 sat →\to mat
12 RA-root 0 root →\to 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 →\to 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 2n2n 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 2n2n 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 s0s_0 to the interval of bb 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 n≤5n \le 5 and find exactly the projective trees, each sequence of length 2n2n.

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 n≤4n \le 4 and for 12 sampled gold trees with n=5n = 5.

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

The words are 1,…,n1, \ldots, n and 0 is the root. A configuration is (σ,β,A)(\sigma, \beta, A) with σ=[v0,…,vk]\sigma = [v_0, \ldots, v_k] from bottom to top and buffer [b,…,n][b, \ldots, n], a suffix of the sentence. For a word vv, YA(v)Y_A(v) is the set of words below vv in AA, vv included. When the buffer is empty, put b=n+1b = n + 1 and YA(b)=∅Y_A(b) = \emptyset.

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

  • (a) v0=0v_0 = 0, and no arc enters 0;
  • (b) a word has a head in AA exactly when it has been shifted and popped; in particular, no stack word and no buffer word has a head;
  • (c) AA has no cycle;
  • (d) YA(v0),…,YA(vk),YA(b)Y_A(v_0), \ldots, Y_A(v_k), Y_A(b) are consecutive intervals in this order, and their union is {0,…,b}\{0, \ldots, b\} (or {0,…,n}\{0, \ldots, n\} when the buffer is empty); the buffer words after bb have no dependents in AA;
  • (e) for each arc h→dh \to d in AA, every word strictly between hh and dd is in YA(h)Y_A(h).

Proof. At the start σ=[0]\sigma = [0], A=∅A = \emptyset, b=1b = 1, and all hold. SHIFT pushes bb, whose interval is already next in line, and the new front b+1b + 1 has YA(b+1)={b+1}Y_A(b + 1) = \{b + 1\} by the last part of (d). LEFT-ARC adds b→s0b \to s_0 with s0≠0s_0 \ne 0 and pops s0s_0, which had no head by (b). No cycle closes, because bb has no head, so no path of heads leads from bb to s0s_0. The intervals of s0s_0 and bb are neighbours, so YA(b)Y_A(b) becomes their union, an interval, and every word strictly between s0s_0 and bb lies in it, which gives (e). RIGHT-ARC adds s1→s0s_1 \to s_0 and pops s0s_0; s0s_0 had no head, no cycle closes because s1s_1 is not below s0s_0 (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. □\square

Theorem 2 (soundness and termination). Every run ends after exactly 2n2n 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 2∣β∣+∣σ∣2|\beta| + |\sigma| is 2n+12n + 1 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 2n2n transitions. Tree. At the end, σ=[0]\sigma = [0] 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. □\square

Theorem 3 (completeness). For every projective tree GG there is a run that ends with A=GA = G.

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

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

Since GG is projective, the yield Y(v)Y(v) is an interval, split into the consecutive intervals Y(l1),…,Y(la),{v},Y(r1),…,Y(rm)Y(l_1), \ldots, Y(l_a), \{v\}, Y(r_1), \ldots, Y(r_m).

Claim. If the buffer front is min⁡Y(v)\min Y(v) and the stack is σ\sigma, then SEQ(v)\mathrm{SEQ}(v) is legal and ends with the stack σ∣v\sigma \mid v, the buffer front max⁡Y(v)+1\max Y(v) + 1, and exactly the arcs of GG inside Y(v)Y(v) added. By induction on ∣Y(v)∣|Y(v)|: the calls SEQ(li)\mathrm{SEQ}(l_i) leave σ∣l1∣⋯∣la\sigma \mid l_1 \mid \cdots \mid l_a with the front at vv. Each LEFT-ARC then attaches the stack top to the front vv: first lal_a, then la−1l_{a - 1}, down to l1l_1; they are not 0, so the moves are legal. SHIFT pushes vv. Each SEQ(rj)\mathrm{SEQ}(r_j) leaves rjr_j above vv, and RIGHT-ARC attaches rjr_j to vv and pops it.

For the whole tree, with root children c1<⋯<cmc_1 < \cdots < c_m, all to the right of 0, run SEQ(c1)\mathrm{SEQ}(c_1), RIGHT-ARC, ..., SEQ(cm)\mathrm{SEQ}(c_m), RIGHT-ARC. Each block leaves [0,cj][0, c_j] and then adds 0→cj0 \to c_j. The yields cover 1,…,n1, \ldots, n in order, so the run ends in ([0],[ ],G)([0], [\,], G). 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. □\square

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 n≤5n \le 5 in 2n2n moves and fails on every non-projective tree, and that the set of trees built by all complete sequences for n≤5n \le 5 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 n≤4n \le 4 and 12 sampled gold trees with n=5n = 5, 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 2n2n: nn shifts and nn arcs.

Time. Each step scores at most 1+2∣R∣1 + 2|R| transitions, so the greedy parse takes Θ(n)\Theta(n) time with a scorer of constant cost. The cost of a transition in the dynamic oracle takes O(n)O(n) time as written, by a scan of the stack and the buffer.

Exact search. The deduction system of Kuhlmann et al. uses items [i,j][i, j], 0≤i<j≤n+10 \le i < j \le n + 1: a computation that pushes word ii and moves the buffer front from ii to jj. Two adjacent items [i,k][i, k] and [k,j][k, j] combine into [i,j][i, j] with the arc j→kj \to k (a LEFT-ARC, if j≤nj \le n) or the arc i→ki \to k (a RIGHT-ARC). With one score per arc this takes O(n3)O(n^3) time and O(n2)O(n^2) 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 n=1n = 1 to 5.

Properties

  • Sound and complete for projective trees, in exactly 2n2n 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 n=1n = 1 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 →\to 1 can be made before or after the arc 3→23 \to 2.
  • 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 kk 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 s0≠0s_0 \ne 0 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.

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

  1. 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
  2. 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
  3. 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.

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