Algorithm Search⌘K

Algorithmresearch

Biaffine dependency parser

Also called deep biaffine attention parser.

Score each head-dependent pair by a biaffine product of BiLSTM vectors, then decode the best tree under those arc scores.

Time
O(n^2 k + n k (k + r) + n^3) worstΘ(n^2 k + n k (k + r)) best
Space
Θ(n^2 + n k) extra
Where
k = the size of the head and dependent vectors; n = the number of words; r = the size of the encoder vectors
Properties
deterministicofflinerecursive
Origin
Timothy Dozat, Christopher D. Manning, 2017

The biaffine dependency parser of Dozat and Manning (2017) is a graph-based parser. A bidirectional LSTM reads the sentence and gives one vector for each word and for the root. Two small feedforward layers turn each vector into a head view aia_i and a dependent view eie_i, and a biaffine function s(h,d)=ah⊤Ued+ah⊤us(h, d) = a_h^\top U e_d + a_h^\top u scores every possible arc h→dh \to d at once, as one matrix product. In training, each word chooses its head by a softmax over all other words and the root, with a cross-entropy loss. At test time the parser takes the tree with the highest total arc score: the best head of each word when these heads already form a tree, and otherwise the maximum spanning arborescence of MST parsing. A second biaffine classifier then gives each arc its label. The parser is simple, fast on a GPU, and was the most accurate on the standard English and Chinese benchmarks when it appeared.

In plain words

First, a network reads the whole sentence in both directions, so each word gets a list of numbers that knows about its context. From that list, two small layers make two short lists for each word: one that says what the word is like as a head, and one that says what it is like as a child. To score "word h is the head of word d", the parser multiplies h's head list, a learned table, and d's child list. Every word looks at all the others and gives each a chance to be its head. In training, the parser learns to give the true head the highest chance. To parse, each word takes its best head; if this makes a loop, a spanning tree method fixes it. Then each word picks the best label for the link to its head.

The problem

The input is a sentence w1⋯wnw_1 \cdots w_n, and the encoder output vectors r0,r1,…,rnr_0, r_1, \ldots, r_n, with r0r_0 for the root. The output is a labeled dependency tree, with crossing arcs allowed. The root may have several children; if the treebank needs one root child, the decoder must add that constraint.

The code on this site takes the network outputs, the vectors rir_i and the weights, as given. It implements the views, the arc and label scores, the head loss with its gradients in UU and uu, and the decoder; it does not train a network or run an LSTM.

The algorithm

Views and scores. For each i=0,…,ni = 0, \ldots, n,

ai=ReLU(Wari+ba),ei=ReLU(Weri+be),a_i = \mathrm{ReLU}(W_a r_i + b_a), \qquad e_i = \mathrm{ReLU}(W_e r_i + b_e),
s(h,d)=ah⊤Ued+ah⊤u.s(h, d) = a_h^\top U e_d + a_h^\top u.

In matrix form, with the views as the rows of AA and EE, the score matrix is S=AUE⊤+Au1⊤S = A U E^\top + A u \mathbf{1}^\top. The first term is a bilinear form, as in multiplicative attention. The second depends on the head only and adds a constant to row hh: it is a prior on how likely hh is to take dependents at all. Labels have their own views ai′,ei′a'_i, e'_i, and for each label ll,

sl(h,d)=ah′⊤Uled′+wl⊤[ed′;ah′]+cl.s_l(h, d) = a'^\top_h U_l e'_d + w_l^\top [e'_d; a'_h] + c_l.

Training. For each word dd, p(h∣d)p(h \mid d) is the softmax of the column s(⋅,d)s(\cdot, d) over h≠dh \ne d, and the head loss is −∑dlog⁡p(h∗(d)∣d)-\sum_d \log p(h^\ast(d) \mid d). The label loss is the cross-entropy of the label softmax at the gold head. The losses ignore the tree constraint: each word is a separate classification.

  1. BIAFFINE-PARSE(r_0, ..., r_n, weights)
  2. 1a_i <- ReLU(W_a r_i + b_a), e_i <- ReLU(W_e r_i + b_e) for each i
  3. 2S[h][d] <- a_h . (U e_d) + a_h . u for all h, d
  4. 3head(d) <- the h != d with the largest S[h][d], for d = 1..n
  5. 4if the heads form a tree then go to L6
  6. 5head <- the maximum spanning arborescence of S rooted at 0 (Chu-Liu-Edmonds)
  7. 6label(d) <- the label l with the largest s_l(head(d), d), for d = 1..n
  8. 7return head, label

Example

A cycle repaired. For two words with the scores (row hh, column dd)

d=1d = 1 d=2d = 2
h=0h = 0 1 0
h=1h = 1 10
h=2h = 2 10

each word prefers the other as its head, so line L3 gives the heads 2 and 1, a cycle with no root. Line L5 contracts the cycle: entering it from the root costs least through word 1, with score 1−10+20=111 - 10 + 20 = 11, against 0−10+20=100 - 10 + 20 = 10 through word 2. The tree is 0→1→20 \to 1 \to 2, with score 11, the best of the 3 trees. If instead S[0][1]=5S[0][1] = 5 and S[2][1]=1S[2][1] = 1, line L3 gives the heads 0 and 1 directly, a tree, and line L5 is skipped.

The head prior. If uu is changed by δ\delta, every entry of row hh changes by the same amount ah⊤δa_h^\top \delta. So the prior moves a head up or down for all dependents at once; the tests check that uu adds a constant to each row.

Correctness

The decoder returns a best tree. If the best heads of line L3 form a tree, this tree has the largest total score of all head lists, so of all trees. Otherwise, Chu-Liu-Edmonds returns a maximum spanning arborescence rooted at 0, by the correctness proof on the MST parsing page. The tests compare the decoder with a search over all trees, (n+1)n−1(n + 1)^{n - 1} of them, for n≤5n \le 5, and check that the cycle repair is needed in some cases.

Scores and log probabilities give the same tree. ∑dlog⁡p(head(d)∣d)=∑dS[head(d)][d]−∑dlog⁡Zd\sum_d \log p(\mathrm{head}(d) \mid d) = \sum_d S[\mathrm{head}(d)][d] - \sum_d \log Z_d, and each normalizer ZdZ_d does not depend on the tree. So the tree with the best total score also has the best total log probability. The tests check this for n≤4n \le 4.

The gradient. With qd(h)=p(h∣d)−[h=h∗(d)]q_d(h) = p(h \mid d) - [h = h^\ast(d)], the gradient of the head loss in S[h][d]S[h][d] is qd(h)q_d(h), so the gradients in UU and uu are ∑d∑hqd(h) ahed⊤\sum_d \sum_h q_d(h)\, a_h e_d^\top and ∑d∑hqd(h) ah\sum_d \sum_h q_d(h)\, a_h. The tests compare them with finite differences. The proofs are in the correctness proof.

Proof: The biaffine decoder returns a tree of maximum total arc score, which also maximizes the total head log probability, and the head loss has the gradient p minus the gold indicatorfull

The words are 1,…,n1, \ldots, n and 0 is the root. SS is an (n+1)×(n+1)(n + 1) \times (n + 1) matrix of real arc scores; S[h][d]S[h][d] is the score of the arc h→dh \to d, for h≠dh \ne d and d≥1d \ge 1. A head list (head(1),…,head(n))(\mathrm{head}(1), \ldots, \mathrm{head}(n)) with head(d)≠d\mathrm{head}(d) \ne d has the score σ(head)=∑d=1nS[head(d)][d]\sigma(\mathrm{head}) = \sum_{d = 1}^n S[\mathrm{head}(d)][d]. It is a tree when following heads from every word reaches 0.

Lemma 1 (the best heads). Let head∘(d)\mathrm{head}^\circ(d) be a head h≠dh \ne d with the largest S[h][d]S[h][d]. Then σ(head∘)≥σ(head)\sigma(\mathrm{head}^\circ) \ge \sigma(\mathrm{head}) for every head list, so if head∘\mathrm{head}^\circ is a tree, it is a tree of maximum score.

Proof. The score is a sum of nn terms, the dd-th of which depends only on head(d)\mathrm{head}(d), and head∘(d)\mathrm{head}^\circ(d) maximizes each term on its own. Every tree is a head list, so the bound holds over trees too. □\square

Lemma 2 (the repair). If head∘\mathrm{head}^\circ is not a tree, Chu-Liu-Edmonds on the complete graph with weights S[h][d]S[h][d] (h≠dh \ne d, d≥1d \ge 1) returns a spanning arborescence rooted at 0 of maximum weight, that is, a tree of maximum score.

Proof. A head list is a tree exactly when its arcs form a spanning arborescence rooted at 0: each word has one head, 0 has none, and every word reaches 0. Chu-Liu-Edmonds returns a maximum-weight spanning arborescence; this is proved on the MST parsing page. The complete graph has one, for instance all words attached to 0. □\square

Theorem 3 (the decoder). The decoder stops and returns a tree of maximum score among all (n+1)n−1(n + 1)^{n - 1} trees.

Proof. Line L3 takes nn maxima over finite sets. The tree test of line L4 follows at most nn heads from each word. If the test succeeds, Lemma 1 gives optimality; otherwise Lemma 2 does, and Chu-Liu-Edmonds stops, because each contraction removes at least one node and the recursion ends on a graph with no cycle among its best entering arcs. □\square

Lemma 4 (scores and log probabilities). Let log⁡p(h∣d)=S[h][d]−log⁡Zd\log p(h \mid d) = S[h][d] - \log Z_d with Zd=∑h′≠deS[h′][d]Z_d = \sum_{h' \ne d} e^{S[h'][d]}. Then for every tree TT, ∑dlog⁡p(headT(d)∣d)=σ(T)−∑dlog⁡Zd\sum_d \log p(\mathrm{head}_T(d) \mid d) = \sigma(T) - \sum_d \log Z_d, so a tree maximizes the total log probability exactly when it maximizes the total score.

Proof. Sum the definition over dd. The second term, ∑dlog⁡Zd\sum_d \log Z_d, does not depend on TT. □\square

Lemma 5 (the head prior). s(h,d)=ah⊤Ued+ah⊤us(h, d) = a_h^\top U e_d + a_h^\top u. The term ah⊤ua_h^\top u adds the same number to every entry of row hh. It does not change which dependent a fixed head scores highest, but it changes the softmax over heads in each column.

Proof. The term depends on hh only. □\square

Lemma 6 (the gradient). Let ℓ=−∑d=1nlog⁡p(h∗(d)∣d)\ell = -\sum_{d = 1}^n \log p(h^\ast(d) \mid d) for gold heads h∗h^\ast, and qd(h)=p(h∣d)−[h=h∗(d)]q_d(h) = p(h \mid d) - [h = h^\ast(d)] for h≠dh \ne d. Then

∂ℓ∂S[h][d]=qd(h),∂ℓ∂U=∑d∑h≠dqd(h) ahed⊤,∂ℓ∂u=∑d∑h≠dqd(h) ah.\frac{\partial \ell}{\partial S[h][d]} = q_d(h), \qquad \frac{\partial \ell}{\partial U} = \sum_{d} \sum_{h \ne d} q_d(h)\, a_h e_d^\top, \qquad \frac{\partial \ell}{\partial u} = \sum_{d} \sum_{h \ne d} q_d(h)\, a_h.

Proof. The term of word dd is −S[h∗(d)][d]+log⁡∑h≠deS[h][d]-S[h^\ast(d)][d] + \log \sum_{h \ne d} e^{S[h][d]}, and only it depends on the column dd. Its derivative in S[h][d]S[h][d] is p(h∣d)−[h=h∗(d)]p(h \mid d) - [h = h^\ast(d)]. Since S[h][d]=∑i,jah,iUijed,j+∑iah,iuiS[h][d] = \sum_{i, j} a_{h, i} U_{ij} e_{d, j} + \sum_i a_{h, i} u_i, the derivatives of S[h][d]S[h][d] in UijU_{ij} and uiu_i are ah,ied,ja_{h, i} e_{d, j} and ah,ia_{h, i}, and the chain rule gives the result. □\square

The tests check Theorem 3 against a search over all trees for n≤5n \le 5, with cases in which the best heads form a cycle; Lemma 4 for n≤4n \le 4; Lemma 5 on random views; and Lemma 6 against central finite differences.

Complexity

Time. The views take Θ(nkr)\Theta(n k r), the products UedU e_d take Θ(nk2)\Theta(n k^2), and the n2n^2 dot products take Θ(n2k)\Theta(n^2 k). The best heads take Θ(n2)\Theta(n^2) and the tree test O(n2)O(n^2) as written. When they do not form a tree, Chu-Liu-Edmonds takes O(n3)O(n^3) as written, or O(n2)O(n^2) with Tarjan's version. The labels take Θ(nk′r+nLk′2)\Theta(n k' r + n L k'^2) for LL labels and label views of size k′k', since only the chosen arc of each word is labeled. On a GPU, all arc scores come from one batched matrix product.

Space. Θ(n2)\Theta(n^2) for the score matrix and Θ(nk)\Theta(nk) for the views.

Properties

  • Global decoding, local training. The loss treats each word on its own, but the decoder enforces a tree. Line L5 runs only when the best heads of line L3 do not form a tree.
  • Non-projective. The decoder can return any tree. For projective output, use the Eisner algorithm on the same scores.
  • Separate head and dependent views. The same word has different vectors as head and as dependent, so s(h,d)≠s(d,h)s(h, d) \ne s(d, h) in general, which the direction of an arc requires.
  • The head prior. The term ah⊤ua_h^\top u lets the model learn that some words, such as verbs, take many dependents, apart from any particular dependent.
  • Small views. The ReLU layers reduce the encoder vectors to a small size before the biaffine product, which removes information not needed for the head choice and keeps UU small.

Variants and improvements

  • Other encoders. The BiLSTM can be replaced by ELMo or BERT vectors, or a transformer, with the same biaffine scorer.
  • Projective decoding. Use the Eisner algorithm on the score matrix when the treebank is projective.
  • Tree-level training. The matrix-tree theorem gives the sum, over all trees, of the product of the exponentiated arc scores, so the loss can be the log probability of the gold tree under a distribution over trees instead of a product of head softmaxes.
  • Higher-order scores. Scores of pairs of arcs, such as siblings and grandparents, can be added, with an approximate decoder.
  • Single root. A decoder that allows only one arc from the root can be built by running the arborescence algorithm with each root child fixed, or by a direct method.

When to use it

Use the biaffine parser when accuracy matters most and a GPU is available: it is a strong baseline for dependency parsing in many languages, and its scorer is easy to add on top of any encoder. For greedy linear-time parsing on a CPU with a small model, a transition-based parser such as the Chen-Manning parser is simpler.

Pitfalls

  • Rows and columns. The softmax for word dd runs over the column of dd, the candidate heads, not over the row. Mixing them gives a model that chooses dependents for each head.
  • Self-loops and the root column. S[d][d]S[d][d] must be excluded from the softmax and the decoder, and the root must never get a head.
  • Cycles and many roots. The best heads may form a cycle, and without the tree decoder the output is then not a tree. Several words may also take the root, which is wrong when the treebank needs one root child; then use a single-root decoder.
  • Labels before heads. The labels are chosen for the decoded heads, not the gold ones, at test time; train the label classifier at the gold head, but evaluate it at the predicted head.

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.

biaffine_dependency_parser.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/biaffine-dependency-parser/. The authors are listed in prov/XMKHK7.jsonl.

"""The scoring layer, the loss and the decoder of the biaffine parser of Dozat and Manning (2017).

The input is the list r_0, ..., r_n of BiLSTM output vectors (r_0 for the root),
taken as given. Two ReLU layers make a head view and a dependent view of each
word, and a biaffine product scores each arc:

    a_i = relu(W_ah r_i + b_ah)       (head view, k numbers)
    e_i = relu(W_ad r_i + b_ad)       (dependent view, k numbers)
    s(h, d) = a_h^T U e_d + a_h^T u   (U is k x k, u has k numbers)

The labels have their own views a'_i and e'_i (k' numbers) and, for each label l,

    s_l(h, d) = a'_h^T U_l e'_d + w_l^T [e'_d ; a'_h] + c_l.

Training uses, for each word d, the cross-entropy of the softmax of s(., d) over
the heads h != d, and the cross-entropy of the label softmax at the gold head.
Decoding takes the best head of each word; when these heads do not form a tree,
it takes the maximum spanning arborescence by Chu-Liu-Edmonds. Each word then
takes its best label for its head.

The module takes the network outputs as given; it implements one forward pass
of the scoring layer, the loss with its gradients in U and u, and the decoder.
It does not train a network.
"""

import math
from typing import Dict, List, Sequence, Tuple

from nlslog import argmax, log_softmax

Vector = List[float]
Matrix = List[List[float]]


def matvec(W: Matrix, x: Sequence[float]) -> Vector:
    return [math.fsum(w * a for w, a in zip(row, x)) for row in W]


def dot(x: Sequence[float], y: Sequence[float]) -> float:
    return math.fsum(a * b for a, b in zip(x, y))


def relu_layer(W: Matrix, b: Sequence[float], x: Sequence[float]) -> Vector:
    return [max(0.0, v + c) for v, c in zip(matvec(W, x), b)]


def biaffine(a: Sequence[float], U: Matrix, e: Sequence[float], u: Sequence[float]) -> float:
    """a^T U e + a^T u."""
    return dot(a, matvec(U, e)) + dot(a, u)


def arc_scores(A: Sequence[Vector], E: Sequence[Vector], U: Matrix, u: Sequence[float]) -> Matrix:
    """S[h][d] = s(h, d) for h, d in 0..n. Column 0 and the diagonal are not used."""
    m = len(A)
    Ue = [matvec(U, E[d]) for d in range(m)]
    return [[dot(A[h], Ue[d]) + dot(A[h], u) for d in range(m)] for h in range(m)]


def label_scores(Ah: Sequence[Vector], Ed: Sequence[Vector], Us: Sequence[Matrix], ws: Sequence[Vector], cs: Sequence[float], h: int, d: int) -> Vector:
    """[s_l(h, d) for each label l]."""
    cat = list(Ed[d]) + list(Ah[h])
    return [dot(Ah[h], matvec(U, Ed[d])) + dot(w, cat) + c for U, w, c in zip(Us, ws, cs)]


def head_log_probs(S: Matrix, d: int) -> Dict[int, float]:
    """log p(h | d) for each h != d, the softmax of the column S[.][d]."""
    hs = [h for h in range(len(S)) if h != d]
    return dict(zip(hs, log_softmax([S[h][d] for h in hs])))


def head_loss_and_grads(A: Sequence[Vector], E: Sequence[Vector], U: Matrix, u: Sequence[float], gold: Sequence[int]):
    """Sum over d of -log p(gold(d) | d), and its gradients in U and u.

    With q_d(h) = p(h | d) - [h = gold(d)], the gradient of the loss in S[h][d]
    is q_d(h), so d/dU = sum_d sum_h q_d(h) a_h e_d^T and d/du = sum_d sum_h q_d(h) a_h.
    """
    S = arc_scores(A, E, U, u)
    k = len(u)
    gU = [[0.0] * k for _ in range(k)]
    gu = [0.0] * k
    loss = 0.0
    for d in range(1, len(S)):
        lp = head_log_probs(S, d)
        loss -= lp[gold[d]]
        for h, v in lp.items():
            q = math.exp(v) - (1.0 if h == gold[d] else 0.0)
            for i in range(k):
                gu[i] += q * A[h][i]
                for j in range(k):
                    gU[i][j] += q * A[h][i] * E[d][j]
    return loss, gU, gu


def is_tree(heads: Sequence[int]) -> bool:
    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 < 0 or steps > n:
                return False
    return True


def _find_cycle(head: Dict[int, int], root: int):
    for start in head:
        seen, x = [], start
        while x != root and x not in seen:
            seen.append(x)
            x = head[x]
        if x != root:
            return seen[seen.index(x):]
    return None


def chu_liu_edmonds(nodes: Sequence[int], root: int, w: Dict[Tuple[int, int], float]) -> Dict[int, int]:
    """A maximum spanning arborescence rooted at root: a map from each other node to its head."""
    best = {}
    for d in nodes:
        if d == root:
            continue
        cands = [(w[h, d], h) for h in nodes if h != d and (h, d) in w]
        best[d] = max(cands)[1]
    cyc = _find_cycle(best, root)
    if cyc is None:
        return best
    cset = set(cyc)
    c = max(nodes) + 1
    cyc_score = math.fsum(w[best[v], v] for v in cyc)
    w2, enter, leave = {}, {}, {}
    for (h, d), s in w.items():
        if h in cset and d not in cset:
            if (c, d) not in w2 or s > w2[c, d]:
                w2[c, d], leave[d] = s, h
        elif h not in cset and d in cset:
            v = s - w[best[d], d] + cyc_score
            if (h, c) not in w2 or v > w2[h, c]:
                w2[h, c], enter[h] = v, d
        elif h not in cset and d not in cset:
            w2[h, d] = s
    sub = chu_liu_edmonds([v for v in nodes if v not in cset] + [c], root, w2)
    out = {}
    for d, h in sub.items():
        if d == c:
            continue
        out[d] = leave[d] if h == c else h
    entry = enter[sub[c]]
    for v in cyc:
        out[v] = best[v]
    out[entry] = sub[c]
    return out


def decode(S: Matrix) -> Tuple[List[int], bool]:
    """Return (heads, used_cle). The best head of each word, repaired by Chu-Liu-Edmonds if needed."""
    m = len(S)
    heads = [-1] + [max((h for h in range(m) if h != d), key=lambda h: S[h][d]) for d in range(1, m)]  # @line L3
    if is_tree(heads):  # @line L4
        return heads, False
    w = {(h, d): S[h][d] for h in range(m) for d in range(1, m) if h != d}
    t = chu_liu_edmonds(list(range(m)), 0, w)  # @line L5
    return [-1] + [t[d] for d in range(1, m)], True


def parse(R: Sequence[Vector], params: dict, labels: Sequence[str]):
    """One forward pass and the decoder. Returns (heads, labels, S, used_cle)."""
    A = [relu_layer(params["W_ah"], params["b_ah"], r) for r in R]  # @line L1
    E = [relu_layer(params["W_ad"], params["b_ad"], r) for r in R]
    S = arc_scores(A, E, params["U"], params["u"])  # @line L2
    heads, used = decode(S)
    Ah = [relu_layer(params["W_lh"], params["b_lh"], r) for r in R]
    Ed = [relu_layer(params["W_ld"], params["b_ld"], r) for r in R]
    out = [None] * len(R)
    for d in range(1, len(R)):
        ls = label_scores(Ah, Ed, params["Us"], params["ws"], params["cs"], heads[d], d)  # @line L6
        out[d] = labels[argmax(ls)]
    return heads, out, S, used  # @line L7
nlslog.py 152 lines
# SPDX-License-Identifier: MIT
# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Log-space arithmetic and semirings for the natural-language-and-speech pages.

Every log is the natural log. A probability of 0 is NEG_INF (float("-inf")),
never a large negative number. A cost is -log p, so a probability of 0 is a
cost of POS_INF.

The semirings are (K, plus, times, zero, one) as on the weighted-automaton page:

    PROB      probabilities         plus = +        times = *   zero = 0       one = 1
    LOG       log probabilities     plus = log_add  times = +   zero = -inf    one = 0
    VITERBI   log probabilities     plus = max      times = +   zero = -inf    one = 0
    TROPICAL  costs -log p          plus = min      times = +   zero = +inf    one = 0
    LOG_COST  costs -log p          plus = -log_add(-a, -b), times = +, zero = +inf, one = 0
    BOOLEAN   truth values          plus = or       times = and zero = False   one = True
    COUNTING  path counts           plus = +        times = *   zero = 0       one = 1

This module holds no algorithm of any page: no forward, Viterbi, CKY, Eisner,
CTC or DTW recursion. The pages build their dynamic programs on top of it.
"""

import math
from dataclasses import dataclass
from typing import Any, Callable, Iterable, List, Sequence

NEG_INF = float("-inf")
POS_INF = float("inf")


def safe_log(p) -> float:
    """Return log p, and NEG_INF for p = 0. Raise ValueError for p < 0."""
    if p < 0:
        raise ValueError("log of a negative number")
    if p == 0:
        return NEG_INF
    return math.log(p)


def log_add(a: float, b: float) -> float:
    """Return log(exp(a) + exp(b)) = max(a, b) + log(1 + exp(-|a - b|)).

    log_add(NEG_INF, NEG_INF) is NEG_INF. No exp of a large number is taken.
    """
    if a < b:
        a, b = b, a
    if b == NEG_INF or a == POS_INF:
        return a
    return a + math.log1p(math.exp(b - a))


def log_sum(xs: Iterable[float]) -> float:
    """Return log(sum of exp(x)) over xs. An empty input gives NEG_INF."""
    xs = list(xs)
    if not xs:
        return NEG_INF
    m = max(xs)
    if m == NEG_INF or m == POS_INF:
        return m
    return m + math.log(math.fsum(math.exp(x - m) for x in xs))


def log_normalize(xs: Sequence[float]) -> List[float]:
    """Return the list x - log_sum(xs): log values whose exps sum to 1.

    Raise ValueError if every value is NEG_INF (nothing to normalize).
    """
    z = log_sum(xs)
    if z == NEG_INF:
        raise ValueError("every weight is zero")
    return [x - z for x in xs]


def log_softmax(xs: Sequence[float]) -> List[float]:
    """Return log softmax(xs): the logits xs turned into log probabilities."""
    return log_normalize(xs)


def softmax(xs: Sequence[float], temperature: float = 1.0) -> List[float]:
    """Return the probabilities exp(x / temperature) / sum, computed stably.

    The temperature must be positive. Logits of NEG_INF get probability 0.
    """
    if not temperature > 0:
        raise ValueError("the temperature must be positive")
    m = max(xs)
    if m == NEG_INF:
        raise ValueError("every logit is -inf")
    es = [math.exp((x - m) / temperature) for x in xs]
    s = math.fsum(es)
    return [e / s for e in es]


def argmax(xs: Sequence[Any]) -> int:
    """Return the first index of a largest value. Raise ValueError if xs is empty."""
    if len(xs) == 0:
        raise ValueError("argmax of an empty sequence")
    best = 0
    for i in range(1, len(xs)):
        if xs[i] > xs[best]:
            best = i
    return best


@dataclass(frozen=True)
class Semiring:
    """A semiring (K, plus, times, zero, one). idempotent is True when a plus a = a."""

    name: str
    plus: Callable[[Any, Any], Any]
    times: Callable[[Any, Any], Any]
    zero: Any
    one: Any
    idempotent: bool


def _add(a, b):
    return a + b


def _mul(a, b):
    return a * b


def _log_add_cost(a: float, b: float) -> float:
    return -log_add(-a, -b)


PROB = Semiring("probability", _add, _mul, 0, 1, False)
LOG = Semiring("log", log_add, _add, NEG_INF, 0.0, False)
VITERBI = Semiring("viterbi", max, _add, NEG_INF, 0.0, True)
TROPICAL = Semiring("tropical", min, _add, POS_INF, 0.0, True)
LOG_COST = Semiring("log-cost", _log_add_cost, _add, POS_INF, 0.0, False)
BOOLEAN = Semiring("boolean", lambda a, b: a or b, lambda a, b: a and b, False, True, True)
COUNTING = Semiring("counting", _add, _mul, 0, 1, False)


def sr_sum(sr: Semiring, xs: Iterable[Any]) -> Any:
    """Return the semiring sum of xs, and sr.zero for an empty input."""
    acc = sr.zero
    for x in xs:
        acc = sr.plus(acc, x)
    return acc


def sr_prod(sr: Semiring, xs: Iterable[Any]) -> Any:
    """Return the semiring product of xs, and sr.one for an empty input."""
    acc = sr.one
    for x in xs:
        acc = sr.times(acc, x)
    return acc
test_biaffine_dependency_parser.py 153 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/biaffine-dependency-parser/. The authors are listed in prov/XMKHK7.jsonl.

import itertools
import math
import random

from biaffine_dependency_parser import (
    arc_scores,
    biaffine,
    decode,
    head_log_probs,
    head_loss_and_grads,
    is_tree,
    label_scores,
    parse,
    relu_layer,
)


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 mat(rng, r, k):
    return [[rng.uniform(-1, 1) for _ in range(k)] for _ in range(r)]


def vec(rng, k):
    return [rng.uniform(-1, 1) for _ in range(k)]


def params(rng, dr, k, kl, n_labels):
    return {
        "W_ah": mat(rng, k, dr), "b_ah": vec(rng, k),
        "W_ad": mat(rng, k, dr), "b_ad": vec(rng, k),
        "U": mat(rng, k, k), "u": vec(rng, k),
        "W_lh": mat(rng, kl, dr), "b_lh": vec(rng, kl),
        "W_ld": mat(rng, kl, dr), "b_ld": vec(rng, kl),
        "Us": [mat(rng, kl, kl) for _ in range(n_labels)],
        "ws": [vec(rng, 2 * kl) for _ in range(n_labels)],
        "cs": vec(rng, n_labels),
    }


def tree_score(S, heads):
    return math.fsum(S[heads[d]][d] for d in range(1, len(heads)))


def test_counts():
    assert [len(TREES[n]) for n in range(1, 6)] == [1, 3, 16, 125, 1296]


def test_relu_and_biaffine():
    assert relu_layer([[1.0, -1.0], [2.0, 0.0]], [0.0, -7.0], [3.0, 1.0]) == [2.0, 0.0]
    a, e = [1.0, 2.0], [3.0, -1.0]
    U, u = [[1.0, 0.0], [2.0, 1.0]], [0.5, -1.0]
    # a^T U e = [1, 2] . [3, 5] = 13 and a^T u = -1.5
    assert biaffine(a, U, e, u) == 11.5


def test_arc_scores_and_head_prior():
    rng = random.Random(1)
    A = [vec(rng, 3) for _ in range(5)]
    E = [vec(rng, 3) for _ in range(5)]
    U, u = mat(rng, 3, 3), vec(rng, 3)
    S = arc_scores(A, E, U, u)
    S0 = arc_scores(A, E, U, [0.0] * 3)
    for h in range(5):
        for d in range(5):
            assert abs(S[h][d] - biaffine(A[h], U, E[d], u)) <= 1e-12
        # The term a_h^T u depends on the head only: it adds a constant to row h.
        diffs = [S[h][d] - S0[h][d] for d in range(5)]
        assert max(diffs) - min(diffs) <= 1e-12
    for d in range(1, 5):
        lp = head_log_probs(S, d)
        assert d not in lp and abs(math.fsum(math.exp(v) for v in lp.values()) - 1.0) <= 1e-12


def test_loss_gradients_by_finite_differences():
    rng = random.Random(2)
    k, m = 3, 5
    A = [vec(rng, k) for _ in range(m)]
    E = [vec(rng, k) for _ in range(m)]
    U, u = mat(rng, k, k), vec(rng, k)
    gold = [-1, 2, 0, 2, 3]
    loss, gU, gu = head_loss_and_grads(A, E, U, u, gold)
    eps = 1e-6
    for i in range(k):
        old = u[i]
        u[i] = old + eps
        up = head_loss_and_grads(A, E, U, u, gold)[0]
        u[i] = old - eps
        down = head_loss_and_grads(A, E, U, u, gold)[0]
        u[i] = old
        assert abs((up - down) / (2 * eps) - gu[i]) <= 1e-6
        for j in range(k):
            old = U[i][j]
            U[i][j] = old + eps
            up = head_loss_and_grads(A, E, U, u, gold)[0]
            U[i][j] = old - eps
            down = head_loss_and_grads(A, E, U, u, gold)[0]
            U[i][j] = old
            assert abs((up - down) / (2 * eps) - gU[i][j]) <= 1e-6
    assert loss > 0


def test_greedy_heads_can_form_a_cycle():
    # Each of the two words prefers the other as head; the root is a weak head.
    S = [[0.0, 1.0, 0.0], [0.0, 0.0, 10.0], [0.0, 10.0, 0.0]]
    heads, used = decode(S)
    assert used and heads == [-1, 0, 1] and tree_score(S, heads) == 11.0
    S = [[0.0, 5.0, 0.0], [0.0, 0.0, 10.0], [0.0, 1.0, 0.0]]
    assert decode(S) == ([-1, 0, 1], False)


def test_decoder_against_brute_force():
    rng = random.Random(3)
    cycles = 0
    for n in range(1, 6):
        for _ in range(30 if n < 5 else 10):
            S = [[rng.uniform(-3, 3) for _ in range(n + 1)] for _ in range(n + 1)]
            heads, used = decode(S)
            cycles += used
            assert is_tree(heads)
            best = max(tree_score(S, t) for t in TREES[n])
            assert abs(tree_score(S, heads) - best) <= 1e-9
            if n <= 4:
                # The same tree maximizes the sum of the head log probabilities,
                # because each word has its own softmax and its normalizer is a constant.
                logp = lambda t: math.fsum(head_log_probs(S, d)[t[d]] for d in range(1, n + 1))
                assert abs(logp(heads) - max(logp(t) for t in TREES[n])) <= 1e-9
    assert cycles > 0


def test_parse_forward_pass_and_labels():
    rng = random.Random(4)
    labels = ["nsubj", "obj", "root", "det"]
    for _ in range(10):
        n = rng.randint(1, 5)
        p = params(rng, 4, 3, 2, len(labels))
        R = [vec(rng, 4) for _ in range(n + 1)]
        heads, labs, S, _ = parse(R, p, labels)
        assert is_tree(heads)
        Ah = [relu_layer(p["W_lh"], p["b_lh"], r) for r in R]
        Ed = [relu_layer(p["W_ld"], p["b_ld"], r) for r in R]
        for d in range(1, n + 1):
            ls = label_scores(Ah, Ed, p["Us"], p["ws"], p["cs"], heads[d], d)
            assert labs[d] == labels[max(range(len(labels)), key=lambda l: ls[l])]
        assert abs(tree_score(S, heads) - max(tree_score(S, t) for t in TREES[n])) <= 1e-9

History

Graph-based parsing with arc scores and a maximum spanning tree decoder goes back to McDonald, Pereira, Ribarov and Hajič (2005), with arc scores from feature templates. Kiperwasser and Goldberg (2016) computed arc scores from BiLSTM vectors with a small feedforward network. Dozat and Manning (2017) replaced that network by a biaffine product of two reduced views, with a separate head prior term, and trained each word's head choice as a softmax; with careful regularization this gave the best results of the time on the English Penn Treebank and the Chinese Treebank. The biaffine scorer became a standard part of neural dependency parsers.

References

  1. Timothy Dozat and Christopher D. Manning, Deep biaffine attention for neural dependency parsing, ICLR 2017, the head and dependent MLP views, the biaffine arc scorer with its head prior term, the label classifier, the softmax training of heads, and the decoding of a well-formed tree
  2. Ryan McDonald, Fernando Pereira, Kiril Ribarov and Jan Hajič, Non-projective dependency parsing using spanning tree algorithms, HLT-EMNLP 2005, graph-based parsing with arc scores and the maximum spanning arborescence by Chu-Liu-Edmonds

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
  • at least three sources
  • a scene preset for the example