Algorithmadvanced
Swap transition system
Also called non-projective swap parsing.
Arc-standard parsing with an extra swap move that reorders words, so it builds any non-projective tree, in quadratic time at worst and near linear time on treebanks.
- Solves
- Dependency parsing
- Time
- Θ(n^2) worstΘ(n) 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, 2009
The swap transition system extends arc-standard parsing so that it can build every dependency tree, not only the projective ones. It adds one move, SWAP, which takes the second word of the stack and puts it back at the front of the buffer. This changes the order in which words meet on the stack. Arcs are still made only between the two top stack words, so the system builds a projective tree over a reordered sentence, and every tree is projective under some order of its words: its projective order, given by an inorder traversal. Nivre (2009) proposed the system. With swaps a parse takes moves for words. Each pair of words can be swapped at most once, so and the worst case is quadratic. On treebanks, few swaps are needed, and the time is close to linear. The title of the paper speaks of expected linear time; that is a statement about real data, not a bound.
In plain words
Arc-standard parsing reads the words onto a pile and joins the two words on top. It can only join words that become neighbours on the pile, so it cannot build arrows that cross. The swap system adds one more move: take the word under the top and put it back in front of the unread words. The two words now come in the opposite order. By doing this several times, the parser can bring words that belong together next to each other, join them, and leave the rest for later. A word that has been put back can come up again later. Any tree can be built this way, but each swap costs two extra moves, so many swaps make the parse slower.
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 dependency tree, with crossing arcs allowed. In the version on this page the root may have several children, since RIGHT-ARC can attach any number of words to the root. The single-root rule of arc-standard parsing, RIGHT-ARC from the root only when the buffer is empty, can be added in the same way.
The algorithm
Configurations are as in arc-standard parsing, but the buffer is now a list that SWAP can add to, not just a suffix of the sentence. The initial configuration is , the terminal ones are , and the words are compared by their original positions. The transitions, for each label :
| transition | before | after | condition |
|---|---|---|---|
| SHIFT | |||
| LEFT-ARC | |||
| RIGHT-ARC | |||
| SWAP |
The condition lets SWAP only undo the original order of a pair, so a pair is never swapped back and the parser cannot loop.
SWAP-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 move the front of the buffer onto the stack - 6
if t = LEFT-ARC_l then add s0 -l-> s1 and remove s1 from the stack - 7
if t = RIGHT-ARC_l then add s1 -l-> s0 and remove s0 from the stack - 8
if t = SWAP then move s1 from the stack to the front of the buffer - 9
return the tree A
The oracle. For a gold tree, let be the rank of in its projective order: the inorder traversal that visits, at each word, the subtrees of its left dependents, then the word, then the subtrees of its right dependents, each group in word order. In a configuration with top words : choose LEFT-ARC if is the gold head of and has all its dependents; RIGHT-ARC if is the gold head of and has all its dependents; SWAP if ; else SHIFT.
Example
A small tree. The head list [-1, 3, 0, 2] has the arcs , and . The arc passes over word 2, the head of 3, so the tree is not projective. Its projective order is 0, 2, 1, 3. The oracle:
| step | transition | stack | buffer | new arc |
|---|---|---|---|---|
| 0 | 0 | 1 2 3 | ||
| 1 | SH | 0 1 | 2 3 | |
| 2 | SH | 0 1 2 | 3 | |
| 3 | SWAP | 0 2 | 1 3 | |
| 4 | SH | 0 2 1 | 3 | |
| 5 | SH | 0 2 1 3 | ||
| 6 | LA | 0 2 3 | ||
| 7 | RA | 0 2 | ||
| 8 | RA | 0 |
At step 3, word 2 comes before word 1 in the projective order, so SWAP puts word 1 back. After that the stack meets the words in the order 0, 2, 1, 3, in which the tree is projective, and the rest is arc-standard parsing. There are moves.
A longer sentence. In A hearing is scheduled on the issue today, with the heads [-1, 2, 3, 0, 3, 2, 7, 5, 4], the phrase on the issue belongs to hearing but comes after is scheduled. The projective order is 0 1 2 5 6 7 3 4 8: the phrase moves before is scheduled. The oracle of this page swaps eagerly, word by word, and uses 6 swaps and 28 moves. A search over all sequences finds that 2 swaps suffice, 20 moves: first build on the issue into one subtree headed by on, then swap on past scheduled and past is. The tests check all three numbers.
Correctness
Every run ends in a tree. If the buffer is not empty, SHIFT is legal; otherwise RIGHT-ARC is legal while the stack has two words. So the parser never gets stuck before a terminal configuration. Each word gets its head when it leaves the stack by an arc, and a word that has left the stack this way never comes back; SWAP puts back only words without a head. In a terminal configuration every word has thus exactly one head, and no cycle can form, because a word with a head is never again a head. The result is a tree, but not always a projective one.
Termination. A SWAP inverts a pair of words, and a pair cannot be swapped back, so there are at most swaps. Between swaps the run behaves as in arc-standard parsing.
Every tree is reached. A tree is projective with respect to its projective order. Run arc-standard parsing on the words in that order, and replace each SHIFT of a word by shifting the words in front of in the buffer, shifting , and swapping those words back one by one. The SWAPs are legal because the buffer stays in the original order. So every tree has a sequence. The proof is in the correctness proof. The tests build all complete sequences for and find all trees, and they run the oracle on every tree with .
Proof: The swap system is sound and complete for all dependency trees, and every run ends after 2n + 2k transitions with k at most n(n - 1)/2full
The words are and 0 is the root. A configuration is with stack , buffer (a list of words) and arc set ; is the stack top and the word below it. Words are compared by their positions in the sentence.
Lemma 1 (invariant). In every configuration of a run:
- (a) 0 is at the bottom of the stack and nowhere else, and no arc enters 0;
- (b) every word is in exactly one of three places: on the stack, in the buffer, or removed; a word is removed exactly when it has a head in , and it then has exactly one;
- (c) no removed word is ever again on the stack or in the buffer;
- (d) has no cycle.
Proof. At the start, , and . SHIFT and SWAP move one word between the buffer and the stack, add no arc, and never move 0: SWAP needs . LEFT-ARC adds with and removes ; RIGHT-ARC adds and removes ; in both cases the dependent was on the stack, so by (b) it had no head, and it now has one. No arc into 0 is added, since LEFT-ARC needs and because 0 is at the bottom. Removed words are not on the stack or in the buffer, and no transition brings a word back from the removed ones, which gives (c). For (d): a new arc closes a cycle only if already has a path of arcs from to . Such a path ends with an arc into , so would have a head. But stays on the stack, so by (b) it has no head, and no cycle closes.
Lemma 2 (no pair is swapped twice). For words , there is at most one SWAP with and , and there is never a SWAP with and .
Proof. The second part is the condition . For the first, define the relative order of and while both are on the stack or in the buffer, reading the stack from bottom to top and then the buffer from front to back. SHIFT keeps this sequence as it is (the front of the buffer becomes the new top of the stack), and LEFT-ARC and RIGHT-ARC only delete words from it. SWAP exchanges and , two neighbours in this sequence, and changes no other relative order. At the start, comes before . The only transition that changes their order is a SWAP with , , which puts before ; after that, the only one that could change it back is a SWAP with , , which is never legal.
Theorem 3 (soundness and termination). Every run ends after exactly transitions, where is its number of swaps, in a terminal configuration whose arcs form a dependency tree rooted at 0.
Proof. Termination. By Lemma 2 there are at most swaps. Let . SHIFT lowers by 1, LEFT-ARC and RIGHT-ARC lower it by 1, and SWAP raises it by 1. is at the start and at least 1, so a run with swaps has at most transitions of the other kinds, and is finite.
No dead end. If the configuration is not terminal, the buffer is not empty and SHIFT is legal, or the buffer is empty and the stack has at least two words, and RIGHT-ARC is legal.
Count. At the end, , so the number of SHIFT, LEFT-ARC and RIGHT-ARC transitions is . Each of the words is removed once, by an arc, so there are arcs and shifts. The total is .
Tree. In the terminal configuration, and is empty, so by (b) every word is removed and has exactly one head. By (a) 0 has none, and by (d) there is no cycle. So following heads from any word ends at 0, and is a dependency tree.
The projective order. For a dependency tree , define the order by an inorder traversal: at a word with left dependents and right dependents , visit the subtrees of , then , then the subtrees of ; start at 0. In , each subtree is a block of consecutive words, so is projective when the words are put in the order . Write for the rank of in .
Theorem 4 (completeness). For every dependency tree there is a run that ends with .
Proof. Let be the words in the order . By the completeness of arc-standard parsing, applied to the sentence in which is projective, there is an arc-standard sequence that builds ; in it, the -th SHIFT pushes , and every arc is made between the two top stack words. We change into a run of the swap system that keeps two properties before each SHIFT of : (P1) the stack and the arc set are the same as in the arc-standard run; (P2) the buffer is the list of words not yet pushed, in sentence order.
Both hold at the start. LEFT-ARC and RIGHT-ARC of are copied unchanged: they are legal in the swap system under the same conditions, and they do not touch the buffer. A SHIFT of that pushes is replaced as follows. By (P2), the buffer is in sentence order and holds ; let be the words in front of , all smaller than . Do SHIFT times, which pushes , and then SWAP times. The first SWAP has and , so it is legal, and it puts at the front of the buffer. The next has and puts in front of , and so on. After the swaps, is on top of the old stack and the buffer is followed by the rest, in sentence order. So (P1) and (P2) hold again, and the arc-standard run and the new run end together, with .
The run of Theorem 4 uses, for each , as many swaps as there are words still unpushed that come before in the sentence but after it in ; in total, the number of pairs whose order in the sentence is the opposite of their order in . The oracle of the main page can do better, because it may make an arc and remove a word before that word has to be moved. The tests check, for every tree with , that the oracle builds the tree in transitions with at most the number of such pairs, and they compare with the least number of swaps, found by search, for every tree with and 150 sampled trees with . They also build all complete sequences for and find that the trees they produce are exactly all dependency trees, which checks Theorems 3 and 4.
Complexity
Number of transitions. Let be the number of swaps. SHIFT and SWAP move a word between the buffer and the stack in opposite directions, so there are shifts, and there are arcs. The total is . Since , a run has at most transitions, and a parser that swaps every pair reaches this bound.
The oracle's swaps. Let be the number of pairs of words whose order in the sentence is the opposite of their order in the projective order, and the least number of swaps of any sequence for the tree. Then the eager oracle uses swaps with . For projective trees . can be smaller than , because an arc can remove a word before it has to be moved: for the tree [-1, 0, 0, 2, 1], and . The largest over all trees of words is 0, 0, 1, 2, 4, 7 for to 6. The tests check the upper bound for every tree with , and compare with , found by search, for every tree with and 150 sampled trees with .
Time. With a scorer of constant cost, , which is at best and at worst. Nivre (2009) reports that on treebanks the number of swaps stays small, so the running time is close to linear in practice.
Space. : the buffer never holds more than words.
Properties
- Sound and complete for all trees. Every terminal configuration holds a dependency tree, and every tree, projective or not, has a sequence.
- Projective trees need no swap. For a projective tree the projective order is the word order, and the oracle gives exactly the arc-standard sequence.
- Sorting by adjacent exchanges. SWAP exchanges two neighbours, much as bubble sort does; the number of inversions between the word order and the projective order bounds the swaps the oracle needs, as it bounds the exchanges of bubble sort.
- Spurious ambiguity. A tree has many sequences, with different numbers of swaps, as the hearing example shows.
- Not exact. The greedy parser can miss the best tree. Unlike the projective systems, there is no known polynomial dynamic program over its sequences for arc scores; for exact non-projective search with arc scores, use MST parsing.
Variants and improvements
- Lazy swapping. Nivre, Kuhlmann and Hall (2009) delay each SWAP until the words to be moved form a complete subtree, so that whole phrases move at once and fewer swaps are needed. On the hearing example the best sequence, found by search in the tests, moves the subtree of on as one unit in this way.
- Other scorers. The scorer is separate from the system, so beam search and neural scorers can be used with the swap system as with arc-standard parsing.
- Training on own errors. The dynamic oracle method needs the cost of each move. For the swap system these costs are harder to compute than for arc-eager or arc-hybrid parsing, and the oracle of this page is static.
- Other routes to crossing arcs. Pseudo-projective parsing transforms the treebank into projective trees and undoes the transformation after parsing. Graph-based parsers find the best tree of all directly, with MST parsing.
When to use it
Use the swap system when a transition-based parser must produce non-projective trees, for languages with free word order or treebanks with many crossing arcs, and greedy or beam parsing at near linear speed is wanted. When exact search with arc scores is wanted, use MST parsing. When the treebank is almost all projective, a projective system with fewer moves is simpler.
Pitfalls
- Comparing by stack order instead of word order. The condition uses the original positions. Without it, the parser can swap a pair back and forth for ever.
- SWAP with the root. The root must stay at the bottom of the stack; SWAP requires .
- Eager oracle, many swaps. The eager oracle moves words one at a time and can use many more swaps than needed (6 against 2 on the hearing example), which gives the classifier longer sequences to learn. Lazy swapping helps.
- The projective order. The oracle must use the inorder traversal with the left dependents before the head and the right dependents after it, each group in word order. Another order can make the gold tree non-projective under it, and the oracle then fails.
- Expected linear time is not a bound. On a hostile input, or with a bad classifier, the parse takes quadratic time.
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/swap-transition-system/. The authors are listed in prov/CCPJNB.jsonl.
"""The swap transition system of Nivre (2009) for non-projective dependency parsing.
The words are 1..n and 0 is the artificial root. A configuration is
(stack, buffer, arcs); the stack starts as [0] with its top s0 last and s1
under it, and the buffer starts as [1, ..., n]. The transitions are
("SH", None), ("LA", label), ("RA", label) and ("SW", None):
SHIFT (sigma, b|beta, A) => (sigma|b, beta, A)
LEFT-ARC_l (sigma|s1|s0, beta, A) => (sigma|s0, beta, A + {(s0, l, s1)}) needs s1 != 0
RIGHT-ARC_l (sigma|s1|s0, beta, A) => (sigma|s1, beta, A + {(s1, l, s0)})
SWAP (sigma|s1|s0, beta, A) => (sigma|s0, s1|beta, A) needs 0 < s1 < s0
The terminal configuration is ([0], [], A). Without SWAP this is arc-standard.
A complete sequence with k swaps has 2n + 2k transitions, and k <= n(n - 1) / 2.
The oracle is the one of Nivre (2009), figure 4: LEFT-ARC or RIGHT-ARC when the
gold arc joins s0 and s1 and the dependent has all its own dependents, SWAP
when s0 comes before s1 in the projective order of the gold tree, else SHIFT.
"""
from typing import Callable, List, Optional, Sequence, Tuple
Transition = Tuple[str, Optional[str]]
SHIFT: Transition = ("SH", None)
SWAP: Transition = ("SW", None)
class Config:
def __init__(self, n: int):
self.n = n
self.stack: List[int] = [0]
self.buffer: List[int] = list(range(1, n + 1))
self.heads = [-1] * (n + 1)
self.labels: List[Optional[str]] = [None] * (n + 1)
def is_terminal(self) -> bool:
return not self.buffer and len(self.stack) == 1
def copy(self) -> "Config":
c = Config(self.n)
c.stack = list(self.stack)
c.buffer = list(self.buffer)
c.heads = list(self.heads)
c.labels = list(self.labels)
return c
def is_legal(c: Config, t: Transition) -> bool:
kind = t[0]
if kind == "SH":
return bool(c.buffer)
if len(c.stack) < 2:
return False
s1, s0 = c.stack[-2], c.stack[-1]
if kind == "LA":
return s1 != 0
if kind == "RA":
return True
if kind == "SW":
return 0 < s1 < s0
raise ValueError(f"unknown transition {t}")
def apply(c: Config, t: Transition) -> None:
kind, label = t
if kind == "SH":
c.stack.append(c.buffer.pop(0)) # @line L5
elif kind == "LA":
s0 = c.stack.pop() # @line L6
s1 = c.stack.pop()
c.heads[s1], c.labels[s1] = s0, label
c.stack.append(s0)
elif kind == "RA":
s0 = c.stack.pop() # @line L7
c.heads[s0], c.labels[s0] = c.stack[-1], label
else:
s0 = c.stack.pop() # @line L8
s1 = c.stack.pop()
c.stack.append(s0)
c.buffer.insert(0, s1)
def legal_transitions(c: Config, label_set: Sequence[str]) -> List[Transition]:
out = [t for t in (SHIFT, SWAP) 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
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 L9
def projective_order(heads: Sequence[int]) -> List[int]:
"""Return pos with pos[w] the rank of word w in the inorder traversal of the tree.
Each node comes after the subtrees of its left dependents and before the
subtrees of its right dependents, all in word order. Ordering the words by
pos makes the tree projective.
"""
n = len(heads) - 1
kids: List[List[int]] = [[] for _ in range(n + 1)]
for d in range(1, n + 1):
kids[heads[d]].append(d)
order: List[int] = []
todo: List[Tuple[int, bool]] = [(0, False)]
while todo:
v, emit = todo.pop()
if emit:
order.append(v)
continue
left = [d for d in kids[v] if d < v]
right = [d for d in kids[v] if d > v]
for d in reversed(right):
todo.append((d, False))
todo.append((v, True))
for d in reversed(left):
todo.append((d, False))
pos = [0] * (n + 1)
for r, v in enumerate(order):
pos[v] = r
return pos
def oracle(c: Config, gold_heads: Sequence[int], gold_labels: Sequence[Optional[str]], pos: Sequence[int]) -> Optional[Transition]:
if len(c.stack) >= 2:
s1, s0 = c.stack[-2], c.stack[-1]
def complete(w):
return all(c.heads[d] == w for d in range(1, c.n + 1) if gold_heads[d] == w)
if s1 != 0 and gold_heads[s1] == s0 and complete(s1):
return ("LA", gold_labels[s1])
if gold_heads[s0] == s1 and complete(s0):
return ("RA", gold_labels[s0])
if pos[s0] < pos[s1]:
return SWAP
return SHIFT if c.buffer else None
def oracle_sequence(gold_heads: Sequence[int], gold_labels: Optional[Sequence[Optional[str]]] = None) -> List[Transition]:
"""Return the oracle sequence that builds the gold tree, projective or not."""
n = len(gold_heads) - 1
if gold_labels is None:
gold_labels = [None] + ["dep"] * n
pos = projective_order(gold_heads)
c = Config(n)
seq: List[Transition] = []
while not c.is_terminal():
t = oracle(c, gold_heads, gold_labels, pos)
if t is None or not is_legal(c, t):
raise ValueError("the oracle is stuck")
apply(c, t)
seq.append(t)
if c.heads != list(gold_heads):
raise ValueError("the oracle built another tree")
return seq
test_swap_transition_system.py 162 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/swap-transition-system/. The authors are listed in prov/CCPJNB.jsonl.
import heapq
import itertools
import random
from swap_transition_system import (
SHIFT,
SWAP,
Config,
apply,
is_legal,
legal_transitions,
oracle_sequence,
parse,
projective_order,
)
# A hearing is scheduled on the issue today
HEARING = [-1, 2, 3, 0, 3, 2, 7, 5, 4]
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_under(heads, pos):
"""Projectivity of the tree when word w is placed at position pos[w]."""
n = len(heads) - 1
at = sorted(range(n + 1), key=lambda w: pos[w])
for d in range(1, n + 1):
h = heads[d]
lo, hi = sorted((pos[h], pos[d]))
for k in at[lo + 1:hi]:
x = k
while x != h and x != 0:
x = heads[x]
if x != h:
return False
return True
def all_trees(n):
return [[-1] + list(hs) for hs in itertools.product(range(n + 1), repeat=n) if is_tree([-1] + list(hs))]
TREES = {n: all_trees(n) for n in range(1, 6)}
def key(c):
return (tuple(c.stack), tuple(c.buffer), tuple(c.heads))
def terminal_trees(n):
"""All trees in terminal configurations reachable from the start, by search."""
seen, out, todo = set(), set(), [Config(n)]
while todo:
c = todo.pop()
if key(c) in seen:
continue
seen.add(key(c))
if c.is_terminal():
out.add(tuple(c.heads))
continue
for t in legal_transitions(c, ["dep"]):
c2 = c.copy()
apply(c2, t)
todo.append(c2)
return out
def min_swaps(gold):
"""The fewest swaps of any sequence that builds the gold tree (search by swaps)."""
n = len(gold) - 1
tie = itertools.count()
pq = [(0, next(tie), Config(n))]
seen = set()
while pq:
k, _, c = heapq.heappop(pq)
if key(c) in seen:
continue
seen.add(key(c))
if c.is_terminal():
return k
for t in legal_transitions(c, ["dep"]):
if t[0] in ("LA", "RA"):
s1, s0 = c.stack[-2], c.stack[-1]
if (t[0] == "LA" and gold[s1] != s0) or (t[0] == "RA" and gold[s0] != s1):
continue
c2 = c.copy()
apply(c2, t)
heapq.heappush(pq, (k + (t[0] == "SW"), next(tie), c2))
raise AssertionError("no sequence")
def test_projective_order():
pos = projective_order(HEARING)
assert sorted(range(9), key=lambda w: pos[w]) == [0, 1, 2, 5, 6, 7, 3, 4, 8]
for n in range(1, 6):
for heads in TREES[n]:
assert is_projective_under(heads, projective_order(heads))
def test_example_sequence():
seq = oracle_sequence(HEARING)
assert seq.count(SWAP) == 6 and len(seq) == 28
assert min_swaps(HEARING) == 2
def test_oracle_builds_every_tree():
# The search for the least number of swaps is slow, so for n = 5 it runs
# on a fixed sample of 150 of the 1296 trees; the other checks run on all.
sample = set(map(tuple, random.Random(7).sample(TREES[5], 150)))
for n in range(1, 6):
for heads in TREES[n]:
seq = oracle_sequence(heads) # raises if the tree is not built
k = seq.count(SWAP)
assert len(seq) == 2 * n + 2 * k
assert k <= n * (n - 1) // 2 and len(seq) <= n + n * n
pos = projective_order(heads)
inversions = sum(1 for a in range(1, n + 1) for b in range(a + 1, n + 1) if pos[a] > pos[b])
assert k <= inversions
if n <= 4 or tuple(heads) in sample:
assert min_swaps(heads) <= k
if inversions == 0:
assert k == 0
def test_sound_and_complete():
for n in range(1, 5):
assert terminal_trees(n) == {tuple(t) for t in TREES[n]}
def test_greedy_terminates_with_a_tree():
rng = random.Random(3)
for _ in range(300):
n = rng.randint(1, 9)
heads, labels, seq = parse(n, lambda c, t: rng.random(), ["x"])
assert is_tree(heads)
k = seq.count(SWAP)
assert len(seq) == 2 * n + 2 * k <= n + n * n
def test_preconditions():
c = Config(2)
assert is_legal(c, SHIFT) and not is_legal(c, SWAP) and not is_legal(c, ("RA", "x"))
apply(c, SHIFT)
assert not is_legal(c, ("LA", "x")) and not is_legal(c, SWAP) and is_legal(c, ("RA", "x"))
apply(c, SHIFT)
assert is_legal(c, SWAP)
apply(c, SWAP)
assert c.stack == [0, 2] and c.buffer == [1]
apply(c, SHIFT)
assert not is_legal(c, SWAP) # 2 > 1: the same pair cannot be swapped back
History
Before 2009, transition-based parsers handled crossing arcs by pseudo-projective transformations of the treebank, or by systems that could add arcs between words further apart on the stack. Nivre (2009) proposed the SWAP move, proved that the extended system is sound and complete for all trees, gave the oracle that sorts the words into the projective order, and reported that the number of swaps on several treebanks was small, so the parser ran in about linear time on real data. Later in 2009, Nivre, Kuhlmann and Hall proposed lazy swapping, which moves whole subtrees and needs fewer swaps.
References
- Joakim Nivre, Non-projective dependency parsing in expected linear time, ACL-IJCNLP 2009, the SWAP transition, the proof of soundness and completeness for all trees, the oracle based on the projective order, the quadratic worst case and the experiments
- Joakim Nivre, Algorithms for deterministic incremental dependency parsing, Computational Linguistics 34(4), 513-553, 2008, the arc-standard system that the swap system extends
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 CCPJNB Edit this page History Report an error Markdown