Algorithm Search⌘K

Algorithmcore

Maximum spanning tree dependency parsing

Also called MST parser, graph-based dependency parsing.

Score every possible arc and take the maximum spanning arborescence by Chu-Liu-Edmonds, which allows non-projective trees.

Time
O(n^3) worstΘ(n^2) best
Space
O(n^3) extra
Where
n = the number of words of the sentence
Properties
deterministicofflinerecursive
Origin
Ryan McDonald, Fernando Pereira, Kiril Ribarov, Jan Hajič, 2005

Maximum spanning tree (MST) dependency parsing finds the best dependency tree of a sentence, projective or not, when the score of a tree is the sum of the scores of its arcs. The words and the artificial root are the nodes of a complete directed graph, each possible arc h→dh \to d carries the score s(h,d)s(h, d), and a dependency tree is exactly a spanning arborescence rooted at the root. So the parser takes a maximum spanning arborescence, with the algorithm of Chu and Liu (1965) and Edmonds (1967). Each word first takes its best head. If that makes a cycle, the cycle is contracted into one node, the arcs into it are rescored, and the smaller problem is solved; then the cycle is opened at the one word that takes a head from outside. McDonald, Pereira, Ribarov and Hajič (2005) introduced this view of parsing. The simple recursive form runs in O(n3)O(n^3) time for nn words, and Tarjan's form in O(n2)O(n^2), which is optimal for a dense score matrix. Unlike the Eisner algorithm, it can return crossing arcs.

In plain words

Every word must choose one word it belongs to, or the start symbol, and each choice has a score. First let each word take its best choice alone. If the choices lead back to the start without loops, they form a tree and nothing can do better. If some words choose each other in a loop, at least one of them must look outside the loop instead. Treat the loop as one big word. Price each outside choice by how much it would cost the loop to accept it, that is, its score minus the score of the loop link it replaces. Solve this smaller problem in the same way. Then open the loop: the winning outside choice tells which word leaves the loop, and the other words keep their loop links.

The problem

The words are 1,…,n1, \ldots, n and 0 is the root. The input is a matrix of arc scores s(h,d)s(h, d), real numbers of any sign, for h∈{0,…,n}h \in \{0, \ldots, n\}, d∈{1,…,n}d \in \{1, \ldots, n\}, h≠dh \ne d. For labeled parsing, take s(h,d)=max⁡rs(h,d,r)s(h, d) = \max_r s(h, d, r) and keep the best label of each arc. The output is a head list h(1),…,h(n)h(1), \ldots, h(n) that forms a tree rooted at 0 and maximizes ∑ds(h(d),d)\sum_d s(h(d), d), over all trees, projective or not. In the main version the root may have any number of children. In the single-root version it has exactly one; the page shows how to enforce that below.

The algorithm

The recursion works on a general directed graph with node set VV, root ρ\rho and arc scores ww. At the top level V={0,…,n}V = \{0, \ldots, n\}, ρ=0\rho = 0 and w(h,d)=s(h,d)w(h, d) = s(h, d).

  1. CLE(V, rho, w) ▷ returns a head for every v in V other than rho
  2. 1for each v in V, v != rho: best[v] <- argmax over u of w(u, v)
  3. 2look for a cycle C in the arcs best[v] -> v
  4. 3if there is none then return best
  5. 4add a new node c that stands for C; S <- sum over v in C of w(best[v], v)
  6. 5build w' on V' = (V - C) + {c}:
  7. for u outside C: w'(u, c) <- max over v in C of w(u, v) - w(best[v], v) + S
  8. for d outside C: w'(c, d) <- max over v in C of w(v, d)
  9. arcs between nodes outside C keep their scores
  10. 6head' <- CLE(V', rho, w')
  11. 7map head' back: the arc u -> c becomes u -> v for the v in C that gave its maximum,
  12. an arc c -> d becomes v -> d for the v in C that gave its maximum, others stay
  13. 8every v in C that got no head in L7 keeps best[v]
  14. 9return the heads

The parser calls CLE({0, ..., n}, 0, s). Each maximum in line L5 also records which cycle node vv gave it, so that line L7 can undo the contraction.

One child of the root. For the single-root version, run CLE nn times. In run mm, delete every root arc except 0→m0 \to m. Return the best of the nn trees. Each run gives the best tree in which the root has the single child mm, so the best of them is the best single-root tree. Deleting the extra root arcs from the unconstrained tree does not work.

Example

Take John saw Mary, words 1 to 3, with the scores (row hh, column dd)

h\dh \backslash d 1 John 2 saw 3 Mary
0 root 9 10 9
1 John 20 3
2 saw 30 30
3 Mary 11 0

Line L1. The best head of John is saw (30), of saw is John (20), and of Mary is saw (30).

Line L2. John and saw head each other: the cycle C={1,2}C = \{1, 2\}, with S=30+20=50S = 30 + 20 = 50.

Line L5. Contract CC into cc. The scores into cc:

  • from the root: through John, 9−30+50=299 - 30 + 50 = 29; through saw, 10−20+50=4010 - 20 + 50 = 40. So w′(0,c)=40w'(0, c) = 40, entering at saw.
  • from Mary: through John, 11−30+50=3111 - 30 + 50 = 31; through saw, 0−20+50=300 - 20 + 50 = 30. So w′(3,c)=31w'(3, c) = 31, entering at John.

The scores out of cc: w′(c,3)=max⁡(s(1,3),s(2,3))=max⁡(3,30)=30w'(c, 3) = \max(s(1, 3), s(2, 3)) = \max(3, 30) = 30, leaving from saw. The root arc w′(0,3)=9w'(0, 3) = 9 stays.

Line L6. In the graph on {0,3,c}\{0, 3, c\}, the best head of cc is the root (40 against 31) and the best head of Mary is cc (30 against 9). There is no cycle, and the score is 40+30=7040 + 30 = 70.

Lines L7 and L8. The arc 0→c0 \to c came through saw, so saw takes the root as head and the cycle arc John →\to saw is dropped. The arc c→3c \to 3 came from saw, so Mary takes saw. John got no head from L7 and keeps saw. The result is the head list [-1, 2, 0, 2] with score 10+30+30=7010 + 30 + 30 = 70, the same as the value of the contracted problem. This tree is projective, so the Eisner algorithm finds it too.

A non-projective answer. With four words and the scores s(0,2)=s(2,4)=s(4,1)=s(2,3)=10s(0, 2) = s(2, 4) = s(4, 1) = s(2, 3) = 10 and 0 for all other arcs, CLE returns [-1, 4, 0, 2, 2] with score 40. The arc 4→14 \to 1 passes over word 2, the head of 4, so the tree is not projective, and the best projective tree scores less. The tests check both facts.

Correctness

Line L1 gives an upper bound: every word gets its best entering arc, and no tree can score more than the sum of these. If these arcs have no cycle, they form a tree, and the bound is met. If there is a cycle CC, a short exchange argument shows that some best tree contains all arcs of CC but one: take a best tree, find the first node of CC on its path from the root, and give every other node of CC its cycle arc; the result is still a tree and does not score less, since each new arc is the best into its node. The trees with this form correspond one to one to the trees of the contracted graph, and the rescoring of line L5 makes the scores equal: a tree that enters CC at vv from uu scores w(u,v)+(S−w(best[v],v))w(u, v) + (S - w(best[v], v)) plus its other arcs, which is w′(u,c)w'(u, c) plus the same arcs. So the best tree of the contracted graph, mapped back, is a best tree of the original graph. Induction on the number of nodes completes the proof, which is in the correctness proof. The single-root version is correct because the nn runs cover all trees with one root child, each run exactly.

Proof: Chu-Liu-Edmonds returns a maximum spanning arborescence, and the parser returns a best dependency treefull

Let GG be a directed graph with node set VV, a root ρ∈V\rho \in V and real arc scores w(u,v)w(u, v), in which every node other than ρ\rho has at least one entering arc and no arc enters ρ\rho. An arborescence of GG is a set TT of arcs that gives every v≠ρv \ne \rho exactly one entering arc, its head hT(v)h_T(v), such that the chain v,hT(v),hT(hT(v)),…v, h_T(v), h_T(h_T(v)), \ldots reaches ρ\rho. Its score is w(T)=∑v≠ρw(hT(v),v)w(T) = \sum_{v \ne \rho} w(h_T(v), v). The claim is that CLE(V,ρ,w)\mathrm{CLE}(V, \rho, w) returns an arborescence of largest score when one exists. For the parser, V={0,…,n}V = \{0, \ldots, n\}, ρ=0\rho = 0, the graph is complete, and the arborescences are exactly the dependency trees.

Lemma 1 (no cycle). Let B={best[v]→v:v≠ρ}B = \{best[v] \to v : v \ne \rho\} be the arcs of line L1. If BB has no cycle, BB is a maximum arborescence.

Proof. Each v≠ρv \ne \rho has one head in BB. Follow the heads from vv. The nodes are finite and no node repeats, because a repeat would be a cycle of BB; the only node without a head is ρ\rho, so the chain ends at ρ\rho. So BB is an arborescence. Any arborescence TT has w(hT(v),v)≤w(best[v],v)w(h_T(v), v) \le w(best[v], v) for each vv, so w(T)≤w(B)w(T) \le w(B). □\square

Now let CC be a cycle of BB, found in line L2. Then ρ∉C\rho \notin C, because ρ\rho has no head in BB. Write S=∑v∈Cw(best[v],v)S = \sum_{v \in C} w(best[v], v) and, for v∈Cv \in C, δ(v)=S−w(best[v],v)\delta(v) = S - w(best[v], v), the score of the arcs of CC other than the one into vv.

Lemma 2 (exchange). Some maximum arborescence contains all the arcs of CC but one.

Proof. Let TT be a maximum arborescence. Let v0v_0 be a node of CC whose path in TT from ρ\rho contains no other node of CC. Such a node exists: take any node of CC, its path in TT from ρ\rho, and the first node of CC on that path. Let T′T' be TT with the head of every v∈Cv \in C, v≠v0v \ne v_0, changed to best[v]best[v]. Each node still has one head. Every node reaches ρ\rho in T′T': the path from ρ\rho to v0v_0 in TT uses no node of CC other than v0v_0, so no head on it changed; each node of CC reaches v0v_0 along the cycle backwards, through heads best[⋅]best[\cdot] that are in T′T'; and a node x∉Cx \notin C follows its chain in TT, whose heads did not change until the chain meets CC, if it does. So T′T' is an arborescence. Each changed head became the best head of its node, so w(T′)≥w(T)w(T') \ge w(T), and T′T' is maximum. T′T' contains every arc of CC except possibly the one into v0v_0; it cannot contain that one too, since then CC would be a cycle in T′T'. □\square

Let AC\mathcal{A}_C be the set of arborescences of GG that contain all arcs of CC but one. Let G′G' be the graph of line L5, on V′=(V∖C)∪{c}V' = (V \setminus C) \cup \{c\}, with the scores

w′(u,c)=max⁡v∈C(w(u,v)+δ(v)),w′(c,d)=max⁡v∈Cw(v,d),w′(u,d)=w(u,d)w'(u, c) = \max_{v \in C} \big(w(u, v) + \delta(v)\big), \qquad w'(c, d) = \max_{v \in C} w(v, d), \qquad w'(u, d) = w(u, d)

for u,d∉Cu, d \notin C, where a maximum is over the vv for which the arc exists. Note w(u,v)−w(best[v],v)+S=w(u,v)+δ(v)w(u, v) - w(best[v], v) + S = w(u, v) + \delta(v). Every node of V′V' other than ρ\rho has an entering arc in G′G': a node d∉Cd \notin C keeps its entering arcs, with those from CC merged into one arc from cc, and cc has an entering arc because some arc enters CC from outside (otherwise no node of CC could reach ρ\rho in GG, and GG would have no arborescence; in the complete graph of the parser the root arcs always exist).

Lemma 3 (contraction). (a) Every T∈ACT \in \mathcal{A}_C maps to an arborescence T′T' of G′G' with w′(T′)≥w(T)w'(T') \ge w(T). (b) Every arborescence T′T' of G′G' is mapped by lines L7 and L8 to some T∈ACT \in \mathcal{A}_C with w(T)=w′(T′)w(T) = w'(T').

Proof. (a) Let T∈ACT \in \mathcal{A}_C omit the arc of CC into v0v_0, and let u=hT(v0)u = h_T(v_0). Then u∉Cu \notin C: otherwise every node of CC would have its head in CC, and the chains from the nodes of CC would never leave CC and never reach ρ\rho. Replace the nodes of CC by cc: the arc u→v0u \to v_0 becomes u→cu \to c, each arc v→dv \to d with v∈Cv \in C, d∉Cd \notin C becomes c→dc \to d, and the arcs inside CC disappear. Every node of V′V' other than ρ\rho gets one head, and chains to ρ\rho in TT map to chains in T′T', so T′T' is an arborescence. Its score is at least w(u,v0)+δ(v0)+∑w(u, v_0) + \delta(v_0) + \sum of the other arcs, because each w′w' is a maximum over the choices that include the one TT made; and w(T)w(T) is exactly w(u,v0)+δ(v0)w(u, v_0) + \delta(v_0) plus the same other arcs. (b) Let T′T' be an arborescence of G′G' and let u→cu \to c be its arc into cc. Line L7 replaces it by u→v0u \to v_0 for the v0∈Cv_0 \in C that gave the maximum w′(u,c)w'(u, c), replaces each c→dc \to d by v→dv \to d for the vv that gave the maximum w′(c,d)w'(c, d), and keeps the other arcs. Line L8 gives every v∈C∖{v0}v \in C \setminus \{v_0\} its head best[v]best[v]. Every node of VV other than ρ\rho now has one head. Every node reaches ρ\rho: a node outside CC follows its chain in T′T', reading cc as a passage through CC, which works because each node of CC reaches v0v_0 along the cycle and v0v_0 goes to uu. So TT is an arborescence in AC\mathcal{A}_C, and its score is w(u,v0)+δ(v0)w(u, v_0) + \delta(v_0) plus the other arcs, which equals w′(T′)w'(T') by the choice of the maximizers. □\square

Theorem 4. CLE(V,ρ,w)\mathrm{CLE}(V, \rho, w) returns a maximum arborescence of GG.

Proof. By induction on ∣V∣|V|. If line L2 finds no cycle, Lemma 1 applies. Otherwise ∣V′∣=∣V∣−∣C∣+1<∣V∣|V'| = |V| - |C| + 1 < |V| because ∣C∣≥2|C| \ge 2, so by induction line L6 returns a maximum arborescence T′∗T'^\ast of G′G'. By Lemma 3(b) the returned TT is an arborescence with w(T)=w′(T′∗)w(T) = w'(T'^\ast). Let T∗T^\ast be a maximum arborescence of GG in AC\mathcal{A}_C, which exists by Lemma 2. By Lemma 3(a) it maps to an arborescence of G′G' of score at least w(T∗)w(T^\ast), so w(T∗)≤w′(T′∗)=w(T)w(T^\ast) \le w'(T'^\ast) = w(T). Hence TT is maximum. □\square

Termination. Each call either returns at line L3 or makes one recursive call on a graph with fewer nodes, and every line does finite work. So there are at most ∣V∣−1|V| - 1 nested calls.

Corollary 5 (the parser). With V={0,…,n}V = \{0, \ldots, n\}, ρ=0\rho = 0 and w=sw = s on all arcs h→dh \to d, d≠0d \ne 0, h≠dh \ne d, CLE returns a highest scoring dependency tree. In the single-root version, run mm keeps only the root arc 0→m0 \to m; its arborescences are exactly the dependency trees whose only root child is mm, every node still has an entering arc, and Theorem 4 gives the best of them. Every single-root tree is counted in exactly one run, so the best of the nn results is a best single-root tree. □\square

Complexity

Time. Lines L1 to L5 and L7 to L8 touch each arc once, which is O(∣V∣2)O(|V|^2) for a dense graph. Each contraction removes at least one node, since a cycle has at least two nodes, so there are at most nn levels of recursion, on graphs of n+1,n,…n + 1, n, \ldots nodes. The total is O(n3)O(n^3) in the worst case, for example when every level finds a cycle of two nodes. The best case is Θ(n2)\Theta(n^2): reading the score matrix already costs that, and if the best heads form a tree, the algorithm stops after one level. Tarjan (1977) organizes the contractions so that the whole run takes O(n2)O(n^2) for dense graphs, which matches the input size. The single-root version by nn runs multiplies the time by nn.

Space. The score matrix of each level is a new graph, and the recursion keeps all levels until it returns, so the simple form uses O(n3)O(n^3) extra space in the worst case. Overwriting the scores in place and storing only the cycle of each level, as Tarjan's form does, brings it down to O(n2)O(n^2).

Properties

  • Exact over all trees. It returns a tree of largest score among all (n+1)n−1(n + 1)^{n - 1} trees, projective or not; the tests compare it with a search over all trees for small nn.
  • Deterministic. Ties in line L1 are broken by the first head in the order of the nodes.
  • Arc-factored only. The proof needs the score of a tree to be the sum of independent arc scores. With second-order scores, non-projective parsing is NP-hard (McDonald and Pereira 2006; McDonald and Satta 2007).
  • Recursive. Each contraction calls the algorithm on a smaller graph.
  • Not online. The best head of each word depends on words to its right.
  • Sums are a determinant. The sum over all trees of the product of arc weights exp⁡s(h,d)\exp s(h, d) is the determinant of a Laplacian minor, by the matrix-tree theorem, and its derivatives give the arc marginals. The code computes both exactly with fractions, with and without the single-root rule, and the tests check them against a sum over all trees.

Variants and improvements

  • Tarjan's implementation. O(n2)O(n^2) for dense graphs, and O(mlog⁡n)O(m \log n) for mm arcs; the version of Gabow, Galil, Spencer and Tarjan takes O(m+nlog⁡n)O(m + n \log n).
  • The root constraint in one run. Faster methods than nn separate runs exist for the single-root version; Zmigrod, Vieira and Cotterell (2020) give an O(n2)O(n^2) method for dependency parsing.
  • K best trees. Camerini, Fratta and Maffioli give an algorithm for the kk best arborescences, used for reranking.
  • Training. McDonald et al. (2005) trained the arc scores with an online large-margin method, with CLE as the decoder in each update. The matrix-tree theorem gives the marginals needed for conditional training of a log-linear model over trees (Koo, Globerson, Carreras and Collins 2007), and the same holds for neural arc scorers such as the biaffine parser.
  • Approximate second order. McDonald and Pereira (2006) take the best projective second-order tree from the Eisner chart and then change heads one at a time, as long as the score rises and the result stays a tree.

When to use it

Use MST parsing when the arc scores are arc-factored and the trees may have crossing arcs, as in languages with free word order or in treebanks with many non-projective arcs, and when an exact decoder is wanted. With a neural arc scorer it is the standard decoder. When the trees must be projective, use the Eisner algorithm. When the score must depend on pairs of arcs, exact non-projective search is NP-hard, and approximate search or a transition-based parser such as the swap system is the usual choice.

Pitfalls

  • The root as a dependent. The root must have no entering arc. Leave out the column of the root, or give it the score minus infinity.
  • Minimum or maximum. Edmonds' algorithm is often stated for the minimum arborescence. Negate the scores, or take maxima everywhere; rescoring by subtraction must then use the maximum form of line L5.
  • Several root children. The unconstrained answer may attach several words to the root. If the treebank requires one, use the single-root version; removing the extra arcs afterwards gives a tree that is not the best single-root tree.
  • Forgetting the map back. The arcs into and out of cc must remember which cycle node gave their maximum. Without this record, the expansion attaches the wrong word.
  • Nested cycles. A contracted node can lie on a new cycle at the next level. The recursion handles this, but an implementation that contracts only once does not; the tests include such a graph.
  • Ties in floating point. With nearly equal scores, the cycle found can change with rounding; the score of the result is still optimal up to rounding, but the tree may differ between runs on different machines.

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.

mst_dependency_parsing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mst-dependency-parsing/. The authors are listed in prov/Z4H7TB.jsonl.

"""Graph-based dependency parsing with the Chu-Liu-Edmonds algorithm.

The words are 1..n and 0 is the artificial root. scores[h][d] is the score of
the arc h -> d in an (n + 1) x (n + 1) matrix; column 0 and the diagonal are
not read. A tree is a head list heads with heads[0] = -1 and heads[d] the head
of word d. The score of a tree is the sum of its arc scores.

mst_parse() returns a maximum spanning arborescence rooted at 0, so the tree
can be non-projective. This plain recursive version takes O(n^3) time; Tarjan's
implementation takes O(n^2) on a dense graph. With single_root=True the root
gets exactly one child: the code solves one problem per possible root child.

partition_function() and arc_marginals() use the matrix-tree theorem with exact
Fractions, for weights w[h][d] > 0 (for example exp of the scores, or small
integers in the tests).
"""

from fractions import Fraction
from typing import Dict, List, Sequence, Tuple

Arc = Tuple[int, int]


def _check(m: Sequence[Sequence]) -> int:
    n = len(m) - 1
    if n < 0 or any(len(row) != n + 1 for row in m):
        raise ValueError("the matrix must be (n + 1) x (n + 1)")
    return n


def _find_cycle(head: Dict[int, int]):
    """Return the list of nodes of a cycle in the graph v -> head[v], or None."""
    color: Dict[int, int] = {}
    for start in head:
        if start in color:
            continue
        path = []
        v = start
        while v in head and v not in color:
            color[v] = 1
            path.append(v)
            v = head[v]
        if v in color and color[v] == 1:
            return path[path.index(v):]
        for u in path:
            color[u] = 2
    return None


def chu_liu_edmonds(nodes: List[int], root: int, w: Dict[Arc, object]) -> Dict[int, int]:
    """Return a maximum spanning arborescence of the graph (nodes, w) rooted at root.

    w maps an arc (h, d) to its score; every node other than root must have at
    least one entering arc. The result maps each non-root node to its head.
    """
    best: Dict[int, int] = {}
    for d in nodes:  # @line L1
        if d == root:
            continue
        cands = [(h, d) for h in nodes if (h, d) in w]
        if not cands:
            raise ValueError(f"node {d} has no entering arc")
        best[d] = max(cands, key=lambda a: w[a])[0]
    cycle = _find_cycle(best)  # @line L2
    if cycle is None:
        return best  # @line L3
    in_cycle = set(cycle)
    c = max(nodes) + 1  # the new node that stands for the cycle  # @line L4
    cycle_score = sum(w[(best[v], v)] for v in cycle)
    w2: Dict[Arc, object] = {}
    enter: Dict[int, int] = {}  # for an arc (u, c): the cycle node it enters
    leave: Dict[int, int] = {}  # for an arc (c, v): the cycle node it leaves
    for (h, d), s in w.items():  # @line L5
        if h in in_cycle and d in in_cycle:
            continue
        if d in in_cycle:
            s2 = s - w[(best[d], d)] + cycle_score
            if (h, c) not in w2 or s2 > w2[(h, c)]:
                w2[(h, c)], enter[h] = s2, d
        elif h in in_cycle:
            if (c, d) not in w2 or s > w2[(c, d)]:
                w2[(c, d)], leave[d] = s, h
        else:
            w2[(h, d)] = s
    nodes2 = [v for v in nodes if v not in in_cycle] + [c]
    sub = chu_liu_edmonds(nodes2, root, w2)  # @line L6
    heads: Dict[int, int] = {}
    for d, h in sub.items():  # @line L7
        if d == c:
            heads[enter[h]] = h
        elif h == c:
            heads[d] = leave[d]
        else:
            heads[d] = h
    for v in cycle:  # @line L8
        if v not in heads:
            heads[v] = best[v]
    return heads  # @line L9


def mst_parse(scores: Sequence[Sequence], single_root: bool = False) -> Tuple[object, List[int]]:
    """Return (score, heads) of a highest scoring dependency tree, projective or not."""
    n = _check(scores)
    if n == 0:
        return 0, [-1]
    nodes = list(range(n + 1))
    full = {(h, d): scores[h][d] for h in nodes for d in range(1, n + 1) if h != d}
    if not single_root:
        options = [full]
    else:
        options = []
        for m in range(1, n + 1):
            options.append({a: s for a, s in full.items() if a[0] != 0 or a[1] == m})
    best_score, best_heads = None, None
    for w in options:
        sol = chu_liu_edmonds(nodes, 0, w)
        heads = [-1] + [sol[d] for d in range(1, n + 1)]
        s = tree_score(scores, heads)
        if best_score is None or s > best_score:
            best_score, best_heads = s, heads
    return best_score, best_heads


def tree_score(scores: Sequence[Sequence], heads: Sequence[int]):
    total = 0
    for d in range(1, len(heads)):
        total = total + scores[heads[d]][d]
    return total


def is_tree(heads: Sequence[int]) -> bool:
    """Return True if every word reaches the root 0 by following heads, with no cycle."""
    n = len(heads) - 1
    if n < 0 or heads[0] != -1:
        return False
    for d in range(1, n + 1):
        if not 0 <= heads[d] <= n or heads[d] == d:
            return False
    for d in range(1, n + 1):
        x, steps = d, 0
        while x != 0:
            x, steps = heads[x], steps + 1
            if steps > n:
                return False
    return True


# The matrix-tree theorem (Koo, Globerson, Carreras and Collins 2007).


def _det_and_inverse(a: List[List[Fraction]]):
    """Return (det a, inverse of a) by Gauss-Jordan elimination over Fractions."""
    n = len(a)
    m = [list(row) + [Fraction(int(i == j)) for j in range(n)] for i, row in enumerate(a)]
    det = Fraction(1)
    for col in range(n):
        piv = next((r for r in range(col, n) if m[r][col] != 0), None)
        if piv is None:
            return Fraction(0), None
        if piv != col:
            m[col], m[piv] = m[piv], m[col]
            det = -det
        p = m[col][col]
        det *= p
        m[col] = [x / p for x in m[col]]
        for r in range(n):
            if r != col and m[r][col] != 0:
                f = m[r][col]
                m[r] = [x - f * y for x, y in zip(m[r], m[col])]
    return det, [row[n:] for row in m]


def _laplacian(w: Sequence[Sequence], single_root: bool):
    """The n x n matrix of Koo et al.: rows and columns are the words 1..n.

    Without single_root, L[d][d] = sum of w[h][d] over all heads h (root included)
    and L[h][d] = -w[h][d]. With single_root, the root weights leave the
    diagonal and the first row becomes w[0][d].
    """
    n = len(w) - 1
    L = [[Fraction(0)] * n for _ in range(n)]
    for d in range(1, n + 1):
        for h in range(0, n + 1):
            if h == d:
                continue
            if h > 0:
                L[h - 1][d - 1] -= Fraction(w[h][d])
            if h > 0 or not single_root:
                L[d - 1][d - 1] += Fraction(w[h][d])
    if single_root:
        L[0] = [Fraction(w[0][d]) for d in range(1, n + 1)]
    return L


def partition_function(w: Sequence[Sequence], single_root: bool = False) -> Fraction:
    """Return Z = sum over all trees of the product of w[h][d] over their arcs."""
    n = _check(w)
    if n == 0:
        return Fraction(1)
    det, _ = _det_and_inverse(_laplacian(w, single_root))
    return det


def arc_marginals(w: Sequence[Sequence], single_root: bool = False) -> List[List[Fraction]]:
    """Return mu[h][d], the total weight of the trees that contain h -> d, divided by Z.

    mu[h][d] = w[h][d] times the derivative of log Z with respect to w[h][d], and
    d log det L / d L[a][b] = (L^-1)[b][a].
    """
    n = _check(w)
    L = _laplacian(w, single_root)
    det, inv = _det_and_inverse(L)
    if det == 0:
        raise ValueError("the total weight of the trees is 0")
    mu = [[Fraction(0)] * (n + 1) for _ in range(n + 1)]
    for d in range(1, n + 1):
        for h in range(0, n + 1):
            if h == d:
                continue
            # (row, column, coefficient) of each entry of L that contains w[h][d]
            entries = []
            if single_root:
                if h == 0:
                    entries.append((0, d - 1, 1))
                else:
                    if d - 1 != 0:
                        entries.append((d - 1, d - 1, 1))
                    if h - 1 != 0:
                        entries.append((h - 1, d - 1, -1))
            else:
                entries.append((d - 1, d - 1, 1))
                if h > 0:
                    entries.append((h - 1, d - 1, -1))
            g = sum(c * inv[b][a] for a, b, c in entries)
            mu[h][d] = Fraction(w[h][d]) * g
    return mu
test_mst_dependency_parsing.py 133 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mst-dependency-parsing/. The authors are listed in prov/Z4H7TB.jsonl.

import itertools
import random
from fractions import Fraction as F

import pytest

from mst_dependency_parsing import (
    arc_marginals,
    chu_liu_edmonds,
    is_tree,
    mst_parse,
    partition_function,
    tree_score,
)

JOHN_SAW_MARY = [
    [0, 9, 10, 9],
    [0, 0, 20, 3],
    [0, 30, 0, 30],
    [0, 11, 0, 0],
]


def all_trees(n):
    out = []
    for hs in itertools.product(range(n + 1), repeat=n):
        heads = [-1] + list(hs)
        if is_tree(heads):
            out.append(heads)
    return out


TREES = {n: all_trees(n) for n in range(1, 6)}


def root_children(heads):
    return sum(1 for h in heads[1:] if h == 0)


def product_weight(w, heads):
    p = F(1)
    for d in range(1, len(heads)):
        p *= w[heads[d]][d]
    return p


def test_tree_counts_by_enumeration_and_matrix_tree():
    assert [len(TREES[n]) for n in range(1, 6)] == [1, 3, 16, 125, 1296]
    for n in range(1, 8):
        ones = [[1] * (n + 1) for _ in range(n + 1)]
        assert partition_function(ones) == (n + 1) ** (n - 1)
        assert partition_function(ones, single_root=True) == n ** (n - 1)


def test_example_john_saw_mary():
    score, heads = mst_parse(JOHN_SAW_MARY)
    assert (score, heads) == (70, [-1, 2, 0, 2])
    # The greedy choice of the best head per word has the cycle John <-> saw.
    best_in = {d: max(range(4), key=lambda h: JOHN_SAW_MARY[h][d] if h != d else -1) for d in (1, 2, 3)}
    assert best_in == {1: 2, 2: 1, 3: 2}


@pytest.mark.parametrize("single_root", [False, True])
def test_against_brute_force(single_root):
    rng = random.Random(5)
    for n in range(1, 6):
        pool = [t for t in TREES[n] if not single_root or root_children(t) == 1]
        for _ in range(25 if n < 5 else 8):
            s = [[rng.randint(-10, 10) for _ in range(n + 1)] for _ in range(n + 1)]
            best = max(tree_score(s, t) for t in pool)
            score, heads = mst_parse(s, single_root=single_root)
            assert score == best
            assert is_tree(heads) and tree_score(s, heads) == score
            if single_root:
                assert root_children(heads) == 1


def test_finds_non_projective_tree():
    n = 4
    s = [[0] * (n + 1) for _ in range(n + 1)]
    s[0][2] = s[2][4] = s[4][1] = s[2][3] = 10
    assert mst_parse(s) == (40, [-1, 4, 0, 2, 2])


def test_general_graph_with_nested_cycles():
    # Two cycles; after the first contraction a second cycle appears.
    w = {(0, 1): 1, (1, 2): 10, (2, 1): 10, (2, 3): 9, (3, 4): 10, (4, 3): 10, (4, 1): 9, (0, 3): 2}
    heads = chu_liu_edmonds([0, 1, 2, 3, 4], 0, w)
    total = sum(w[(h, d)] for d, h in heads.items())
    best = None
    for hs in itertools.product(range(5), repeat=4):
        cand = [-1] + list(hs)
        if is_tree(cand) and all((cand[d], d) in w for d in range(1, 5)):
            t = sum(w[(cand[d], d)] for d in range(1, 5))
            best = t if best is None else max(best, t)
    assert total == best


def test_ties_and_negative_scores():
    rng = random.Random(9)
    for _ in range(40):
        n = rng.randint(1, 5)
        s = [[rng.choice([-3, -1, 0, 0, 2]) for _ in range(n + 1)] for _ in range(n + 1)]
        score, heads = mst_parse(s)
        assert score == max(tree_score(s, t) for t in TREES[n])


@pytest.mark.parametrize("single_root", [False, True])
def test_partition_and_marginals_against_brute_force(single_root):
    rng = random.Random(13)
    for n in range(1, 5):
        w = [[F(rng.randint(1, 6), rng.randint(1, 3)) for _ in range(n + 1)] for _ in range(n + 1)]
        pool = [t for t in TREES[n] if not single_root or root_children(t) == 1]
        z = sum(product_weight(w, t) for t in pool)
        assert partition_function(w, single_root=single_root) == z
        mu = arc_marginals(w, single_root=single_root)
        for d in range(1, n + 1):
            for h in range(n + 1):
                if h == d:
                    continue
                exact = sum(product_weight(w, t) for t in pool if t[d] == h) / z
                assert mu[h][d] == exact
            assert sum(mu[h][d] for h in range(n + 1) if h != d) == 1


def test_small_inputs():
    assert mst_parse([[0]]) == (0, [-1])
    assert mst_parse([[0, 4], [0, 0]]) == (4, [-1, 0])
    with pytest.raises(ValueError):
        mst_parse([[0, 1]])

History

Chu and Liu (1965) and Edmonds (1967) found the optimum branching algorithm independently, and Tarjan (1977) gave fast implementations. In parsing, Eisner's (1996) cubic chart had made projective arc-factored parsing exact, and transition-based parsers handled non-projective trees with pseudo-projective transformations. McDonald, Pereira, Ribarov and Hajič (2005) observed that dropping projectivity turns the arc-factored problem into a maximum spanning arborescence, which can be solved in O(n2)O(n^2), and showed good results on Czech. McDonald and Pereira (2006) and McDonald and Satta (2007) then showed that non-projective parsing becomes NP-hard as soon as the scores look at pairs of arcs. In 2007 several groups, among them Koo, Globerson, Carreras and Collins, used the matrix-tree theorem for the partition function. With neural arc scores, as in the biaffine parser of Dozat and Manning (2017), the arborescence decoder remains in common use.

References

  1. Ryan McDonald, Fernando Pereira, Kiril Ribarov and Jan Hajič, Non-projective dependency parsing using spanning tree algorithms, HLT-EMNLP 2005, the reduction to the maximum spanning arborescence, the Chu-Liu-Edmonds algorithm in the maximum form, and online large-margin training
  2. Sandra Kübler, Ryan McDonald and Joakim Nivre, Dependency Parsing, Synthesis Lectures on Human Language Technologies, Morgan and Claypool, 2009, Chapter 4, Graph-Based Parsing (arc-factored models and the maximum spanning tree algorithm)
  3. Jack Edmonds, Optimum branchings, Journal of Research of the National Bureau of Standards 71B(4) (1967), 233-240, the contraction of cycles of best entering arcs
  4. Y. J. Chu and T. H. Liu, On the shortest arborescence of a directed graph, Scientia Sinica 14 (1965), 1396-1400, the same algorithm, found independently
  5. Robert E. Tarjan, Finding optimum branchings, Networks 7(1) (1977), 25-35, the O(n^2) implementation for dense graphs
  6. Terry Koo, Amir Globerson, Xavier Carreras and Michael Collins, Structured prediction models via the matrix-tree theorem, EMNLP-CoNLL 2007, the partition function and the arc marginals of non-projective trees, with and without one child of the root

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