Algorithmcore
Eisner algorithm
Also called Eisner projective parsing.
An O(n^3) dynamic program over complete and incomplete spans that finds the best projective dependency tree under arc-factored scores.
- Solves
- Dependency parsing
- Time
- Θ(n^3) worst · best
- Space
- Θ(n^2) extra
- Where
- n = the number of words of the sentence
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jason Eisner, 1996
The Eisner algorithm finds the best projective dependency tree of a sentence when the score of a tree is the sum of the scores of its arcs. It is a dynamic program over spans of the sentence, like CYK, but each span keeps its head word at one of its two ends instead of anywhere inside. That one change brings the time from the of lexicalized CKY down to for words. A span is complete when its head has all its dependents inside it, and incomplete when it is a single arc whose far end may still take dependents. Eisner described the method in 1996. It is the decoder of first-order and second-order projective graph-based parsers, and with sums in place of maxima it gives the partition function and the arc marginals that training needs.
In plain words
A projective tree can be cut into pieces that are blocks of neighbouring words. Each piece has its main word at its left end or at its right end, and the rest of the piece hangs below that main word. Two kinds of pieces are enough. A finished piece is a word together with everything it governs on one side. An open piece is a word and one dependent, at the two ends of the block, with the words between them already attached on the correct sides. The algorithm builds the best piece of each kind for every block, from short blocks to long ones. An open piece joins two finished pieces that meet in the middle and adds one arrow. A finished piece joins an open piece with a finished piece. The best whole sentence is the best finished piece that starts at the root.
The problem
The words are and 0 is the artificial root, at the left edge. The input is a matrix of arc scores for and with ; the scores are real numbers of any sign. For labeled parsing, take and keep the best label of each arc. The score of a dependency tree with head function is . The output is a projective tree of largest score, as a head list. In the main version the root may have any number of children; the single-root version, required by Universal Dependencies, gives the root exactly one child.
The algorithm
For there are four tables. The arrow gives the side of the head:
- : the best complete right span, a projective tree on the positions rooted at .
- : the best complete left span, a projective tree on rooted at .
- , for : the best incomplete right span, a tree on rooted at that contains the arc .
- , for : the best incomplete left span, a tree on rooted at that contains the arc .
Each table entry is a largest score, or "none" when no tree of that kind exists. In the pseudocode CR, CL, IR and IL stand for , , and , and max skips the terms that are "none".
EISNER(s, n) ▷ arc scores s[h][d], words 1 … n, root 0- 1
for i <- 0 to n do CR[i, i] <- 0; CL[i, i] <- 0 - 2
for k <- 1 to n do ▷ the span length j - i - 3
for i <- 0 to n - k do - 4
j <- i + k; m <- max over i <= r < j of CR[i, r] + CL[r + 1, j] - 5
if i > 0 then IL[i, j] <- m + s[j][i] ▷ the arc j -> i - 6
IR[i, j] <- m + s[i][j] ▷ the arc i -> j - 7
CL[i, j] <- max over i <= r < j of CL[i, r] + IL[r, j] - 8
CR[i, j] <- max over i < r <= j of IR[i, r] + CR[r, j] - 9
return CR[0, n] and the tree read from the back pointers
Each maximum also stores its best split point as a back pointer. Line L9 reads the tree from them, top down from , with an explicit stack: a complete span splits at its pointer into an incomplete span and a complete span, and an incomplete span adds its arc and splits into two complete spans. Line L5 skips , since no arc enters the root.
One child of the root. For the single-root version, line L4 uses only when . Then : the root takes as its only dependent so far. Line L8 for uses one such span and a complete span of , so the root gets exactly one child.
Example
Take John saw Mary, words 1 to 3, with the arc scores (row , column )
| 1 John | 2 saw | 3 Mary | |
|---|---|---|---|
| 0 root | 9 | 10 | 9 |
| 1 John | 20 | 3 | |
| 2 saw | 30 | 30 | |
| 3 Mary | 11 | 0 |
The four tables, span by span. A dash means "none".
| span | ||||
|---|---|---|---|---|
| dash | 9 | dash | 9 | |
| 30 | 20 | 30 | 20 | |
| 0 | 30 | 0 | 30 | |
| dash | 40 | dash | 40 | |
| 31 | 23 | 31 | 50 | |
| dash | 49 | dash | 70 |
Some of the entries in detail:
- : , so . This is the root with the arc to saw, which already has John on its left.
- : John heads saw, which heads Mary.
- .
The back pointers give , then the arc with , which holds the arc , and , which holds the arc . The tree is root saw, saw John, saw Mary, with score 70 and head list [-1, 2, 0, 2]. It has one root child, so the single-root version returns the same tree. The best head of each word alone would give the cycle John saw; the spans cannot express a cycle.
Correctness
Each table entry is the best score over a set of projective trees on an interval with the head at one end. The proof rests on one fact about projective trees: the subtree of every word covers an interval. Take a tree counted by , and remove the arc . The subtree of is an interval that ends at , say , and the rest is a tree rooted at on . So the tree is a complete right span on , a complete left span on , and the arc; its score is the sum of the three parts. Conversely, every such pair of spans and the arc make a projective tree of the right kind. In the same way, a tree counted by with splits at the child of whose subtree contains : the part with , its children up to , and the left side of is an incomplete span on , and with its right descendants is a complete span on . The parts are independent, so the best tree uses the best parts, and lines L4 to L8 compute every entry from shorter spans by induction on the length. The answer is the best projective tree on all positions rooted at 0. The full proof, including the single-root version and the reading of the tree, is in the correctness proof.
Proof: The Eisner algorithm returns a best projective dependency tree, and it terminatesfull
The positions are , with the root at 0, and is the score of the arc . For , a right tree on is a set of arcs that makes a projective tree on the positions with root ; a left tree on is the same with root , and it is allowed only when or , since no arc may enter position 0. A right tree on with is incomplete if it contains the arc , and a left tree is incomplete if it contains . The score of a set of arcs is the sum of their scores. Let , , and be the four sets of trees. The claim is that the tables CR, CL, IR and IL computed by lines L1 to L8 hold the largest score in the matching set, or "none" when the set is empty.
Lemma 1 (yields are intervals). In a projective tree on an interval , the subtree of every position is an interval.
Proof. Let be a position and let with and in the subtree of . Suppose is not in it. The path from up to and the path from up to stay in the subtree, so there is an arc of the tree whose endpoints lie on different sides of and both in the subtree of : walk from to through , and take the first arc that steps over . The head of that arc is in the subtree of , and by projectivity it dominates , so is in the subtree of , a contradiction.
Lemma 2 (incomplete spans). For , a set is in if and only if for some with , and . The split and the parts are unique. The same holds for , , with the arc .
Proof. Let . By Lemma 1 the subtree of is an interval; it contains , does not contain , and lies in , so it is for a unique with . The arcs inside it form a tree rooted at on . Removing 's subtree and the arc leaves a tree rooted at on . Both are projective, because a subset of the arcs of a projective tree that forms a tree on an interval keeps every arc projective: the words between the ends of an arc are dominated by its head in , and they lie in the same interval, so the chain to that head stays inside the part. Conversely, let and be as stated. Then is a tree on rooted at : every position has one head and the chain from each position reaches . The arcs of and are still projective. The arc is projective because every position strictly between and is in or in and so is dominated by . Uniqueness: is the left end of the subtree of , which determines. The left case is the mirror image; the condition keeps the arc from entering the root.
Lemma 3 (complete spans). For , a set is in if and only if for some with , and , with and the parts unique. For , the split is , and .
Proof. Let . The position is below ; let be the child of on the chain from to . By Lemma 1 the subtree of is an interval containing and , and since is not in it, it is for some ; it ends at because is the right end of the whole span. The positions of the subtree of that are form, with their arcs, a tree on rooted at ; this is a set of positions closed under taking heads up to . Indeed, if a position of the subtree had a head , the arc would pass over , so by projectivity would dominate , while is itself below ; that is impossible. The other arcs form a tree on rooted at that contains . Both are projective as in Lemma 2, so and . Conversely, the union of such and is a tree on rooted at , and its arcs are projective: an arc of spans only positions of , which it dominates inside , and an arc of spans only positions of . Uniqueness: is the child of whose subtree contains . The left case is the mirror image.
Theorem 4 (the tables). After lines L1 to L8, for all , each table entry holds the largest score of its set of trees, or "none" when the set is empty; with the back pointers, each entry that is not "none" names a tree of that score.
Proof. By induction on . For , the only tree on is the empty set of arcs, with score 0, which is line L1. Let and assume the claim for all shorter spans. Line L4 runs after every span of length less than has its final values, because the loop of line L2 goes through the lengths in increasing order and the spans used in lines L4, L7 and L8 are strictly shorter, with two exceptions: in line L7 (the term ) and in line L8 (the term ). Both are entries of the same span computed in lines L5 and L6 just before. The complete spans and that go with them have length 0. By Lemma 2, the score of a tree in is for its unique parts, and every choice of parts gives a tree. So the largest score is , because the parts can be chosen independently for each . By the induction hypothesis the inner maxima are and , which is line L6. Line L5 is the same for the left case, and it is skipped for , where the set is empty. Lemma 3 gives lines L7 and L8 in the same way. A split whose part is "none" contributes no tree, which is why max skips such terms. The back pointer stores a maximizing , and the tree built from it and from the trees of the parts has the stored score.
Corollary 5 (the answer). is the largest score of a projective dependency tree of the sentence, and line L9 returns such a tree.
Proof. A projective dependency tree over the words rooted at 0 is exactly an element of . The set is not empty (attach every word to the root), so the entry is a number. Theorem 4 gives the rest. Reading the tree follows the back pointers from ; each step replaces a span by strictly shorter spans and adds at most one arc, and Lemmas 2 and 3 show that the arcs added form the tree whose score is the table value.
One child of the root. In the single-root version, line L4 uses only when . Call a right tree on single if position 0 has exactly one child. A tree in is single exactly when its part has no arcs, that is, . A tree in , , splits by Lemma 3 into and , and the root's children are those in ; so it is single exactly when is single. Line L8 for reads only the restricted entries of IR, so by the same induction is the best score of a projective tree whose root has exactly one child, and such a tree exists (a chain ).
Termination. Every loop has fixed bounds, every maximum is over at most terms, and the reading of the tree replaces each span by strictly shorter spans, so it stops. Each incomplete span it visits adds one arc, and each complete span of positive length it visits leads to one incomplete span, so it visits spans. The tests check the result against a search over all trees for small , in both versions.
Complexity
Time. For a span of length , lines L4, L7 and L8 each try split points, and there are spans of length . The total number of terms is , each one addition and one comparison on the word RAM. So the time is for every input, since the loops do not depend on the scores. Reading the tree takes . With labels, choosing the best label of each arc first takes more.
Space. The four tables and their four tables of back pointers have entries each, so the space is , back pointers included. Only the score , without the tree, still needs the tables, because every span is read by longer spans.
Properties
- Exact. It returns a tree of largest score among all projective trees, not an approximation.
- Deterministic. Ties are broken by the first split point in increasing order.
- No spurious ambiguity. Each projective tree has exactly one decomposition into spans. So with in place of the same loops sum over the trees, each tree once: with all weights 1 they count the projective trees, 1, 3, 12, 55, 273 for to 5 and 1430715 for , which the tests check.
- Semiring algorithm. With log weights and log-sum-exp it gives the log of the partition function over projective trees, the first half of the inside-outside computation of arc marginals.
- Not online. The long spans need the whole sentence.
- Arc-factored only. The score of a span must not depend on what lies outside it; this is what restricts the plain algorithm to first-order scores.
Variants and improvements
- Second order. McDonald and Pereira (2006) add a sibling item, so that the score of an arc can depend on the previous dependent of the same head on the same side. The time stays .
- Higher orders. Items that also record a grandparent or more siblings give third-order parsers in time.
- Inside and outside. Replacing max by log-sum-exp gives the inside scores, and a second pass gives the outside scores; their product is the marginal probability of each arc, as in the inside-outside algorithm. This trains a projective conditional model of trees.
- Labels and features. With arc-factored labeled scores, the labels are chosen per arc before the chart. Neural scorers such as the biaffine parser feed their arc scores to this chart when the output must be projective.
- The same chart as a transition system. Kuhlmann, Gómez-Rodríguez and Satta (2011) show that exact search over the computations of the arc-hybrid system with arc-factored scores is a cubic chart over items much like this one.
- Non-projective trees. Without the projective constraint, Chu-Liu-Edmonds finds the best tree in .
When to use it
Use the Eisner algorithm when the trees must be projective and the scores are arc-factored, or second order with the sibling extension: for English and other treebanks that are almost all projective, for projective conditional training, or to get a projective output from a neural scorer. For languages or schemes with many crossing arcs, use the maximum spanning arborescence. For very long inputs or when cubic time is too slow, transition-based parsers take a linear number of steps, at the price of exact search.
Pitfalls
- The root as a left dependent. The incomplete left span with would put an arc into the root. Line L5 must skip it.
- The single-root rule. Without it, the best tree may give the root several children. Taking the best tree and then deleting extra root arcs does not give the best single-root tree; restrict the root spans as above.
- Ties and the back pointers. If the back pointers store the wrong split when scores tie, the tree read out can score less than the table value. Store the split together with the maximum, in the same comparison.
- Spurious counts. A chart in which a tree has two decompositions gives the right maximum but wrong sums. The two-type split of this page has one decomposition per tree, so the counting check is a good test.
- Underflow in the sum version. A product of arc probabilities underflows for long sentences. Use log weights; the tests show a case where the plain sum is 0.0 and the log version is exact.
- Not for non-projective gold trees. Training a projective parser on a treebank with crossing arcs needs a policy for those trees, for example projectivizing them first.
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/eisner-algorithm/. The authors are listed in prov/JTW3A2.jsonl.
"""Eisner's algorithm: the best projective dependency tree under arc-factored scores.
The words are 1..n and 0 is the artificial root. scores[h][d] is the score of
the arc h -> d; the matrix is (n + 1) x (n + 1), and column 0 and the diagonal
are not read. A tree is a head list heads of length n + 1 with heads[0] = -1 and
heads[d] the head of word d. The score of a tree is the sum of the scores of its
n arcs.
eisner() returns a best projective tree and its score. With single_root=True
the root gets exactly one child, as in Universal Dependencies. eisner_inside()
runs the same recursion in any semiring of nlslog: with COUNTING and all weights
1 it counts the projective trees, with LOG and log weights it gives the log of
the partition function, the sum over all projective trees of exp(score).
The scores can be ints, Fractions or floats. No item is stored as None, so
exact arithmetic never meets an infinity.
"""
from typing import List, Optional, Sequence, Tuple
from nlslog import Semiring
LEFT, RIGHT = 0, 1 # LEFT: the head is the right end j; RIGHT: the head is the left end i
def _check(scores: Sequence[Sequence]) -> int:
n = len(scores) - 1
if n < 0 or any(len(row) != n + 1 for row in scores):
raise ValueError("scores must be an (n + 1) x (n + 1) matrix")
return n
def _better(a, b) -> bool:
return b is None or (a is not None and a > b)
def eisner(scores: Sequence[Sequence], single_root: bool = False) -> Tuple[object, List[int]]:
"""Return (best score, heads) over the projective trees of words 1..n.
Ties are broken by the first split point r in increasing order.
"""
n = _check(scores)
if n == 0:
return 0, [-1]
# C[d][i][j] and I[d][i][j]: best complete and incomplete spans; bc and bi: split points.
C = [[[None] * (n + 1) for _ in range(n + 1)] for _ in range(2)]
I = [[[None] * (n + 1) for _ in range(n + 1)] for _ in range(2)]
bc = [[[0] * (n + 1) for _ in range(n + 1)] for _ in range(2)]
bi = [[[0] * (n + 1) for _ in range(n + 1)] for _ in range(2)]
for i in range(n + 1): # @line L1
C[LEFT][i][i] = 0
C[RIGHT][i][i] = 0
for k in range(1, n + 1): # @line L2
for i in range(n - k + 1): # @line L3
j = i + k # @line L4
best, arg = None, i
r_max = i if (single_root and i == 0) else j - 1
for r in range(i, r_max + 1):
a, b = C[RIGHT][i][r], C[LEFT][r + 1][j]
if a is not None and b is not None and _better(a + b, best):
best, arg = a + b, r
if best is not None:
if i > 0: # @line L5
I[LEFT][i][j] = best + scores[j][i]
bi[LEFT][i][j] = arg
I[RIGHT][i][j] = best + scores[i][j] # @line L6
bi[RIGHT][i][j] = arg
best, arg = None, i
for r in range(i, j): # @line L7
a, b = C[LEFT][i][r], I[LEFT][r][j]
if a is not None and b is not None and _better(a + b, best):
best, arg = a + b, r
C[LEFT][i][j], bc[LEFT][i][j] = best, arg
best, arg = None, j
for r in range(i + 1, j + 1): # @line L8
a, b = I[RIGHT][i][r], C[RIGHT][r][j]
if a is not None and b is not None and _better(a + b, best):
best, arg = a + b, r
C[RIGHT][i][j], bc[RIGHT][i][j] = best, arg
heads = [-1] * (n + 1)
# Read the tree from the back pointers with an explicit stack.
stack = [("C", RIGHT, 0, n)]
while stack:
kind, d, i, j = stack.pop()
if i == j:
continue
if kind == "C":
r = bc[d][i][j]
if d == LEFT:
stack.append(("C", LEFT, i, r))
stack.append(("I", LEFT, r, j))
else:
stack.append(("I", RIGHT, i, r))
stack.append(("C", RIGHT, r, j))
else:
r = bi[d][i][j]
if d == LEFT:
heads[i] = j
else:
heads[j] = i
stack.append(("C", RIGHT, i, r))
stack.append(("C", LEFT, r + 1, j))
return C[RIGHT][0][n], heads # @line L9
def eisner_inside(weights: Sequence[Sequence], sr: Semiring, single_root: bool = False):
"""Return the semiring sum over all projective trees of the product of their arc weights.
weights[h][d] is the weight of the arc h -> d in the semiring sr. Every
projective tree has exactly one derivation in the recursion, so nothing is
counted twice.
"""
n = _check(weights)
if n == 0:
return sr.one
zero = sr.zero
C = [[[zero] * (n + 1) for _ in range(n + 1)] for _ in range(2)]
I = [[[zero] * (n + 1) for _ in range(n + 1)] for _ in range(2)]
for i in range(n + 1):
C[LEFT][i][i] = sr.one
C[RIGHT][i][i] = sr.one
for k in range(1, n + 1):
for i in range(n - k + 1):
j = i + k
acc = zero
r_max = i if (single_root and i == 0) else j - 1
for r in range(i, r_max + 1):
acc = sr.plus(acc, sr.times(C[RIGHT][i][r], C[LEFT][r + 1][j]))
if i > 0:
I[LEFT][i][j] = sr.times(acc, weights[j][i])
I[RIGHT][i][j] = sr.times(acc, weights[i][j])
acc = zero
for r in range(i, j):
acc = sr.plus(acc, sr.times(C[LEFT][i][r], I[LEFT][r][j]))
C[LEFT][i][j] = acc
acc = zero
for r in range(i + 1, j + 1):
acc = sr.plus(acc, sr.times(I[RIGHT][i][r], C[RIGHT][r][j]))
C[RIGHT][i][j] = acc
return C[RIGHT][0][n]
def tree_score(scores: Sequence[Sequence], heads: Sequence[int]):
"""Return the sum of scores[heads[d]][d] over the words d = 1..n."""
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):
seen = 0
x = d
while x != 0:
x = heads[x]
seen += 1
if seen > n:
return False
return True
def is_projective(heads: Sequence[int]) -> bool:
"""Return True if each head dominates every word strictly between it and its dependent."""
n = len(heads) - 1
for d in range(1, n + 1):
h = heads[d]
lo, hi = min(h, d), max(h, d)
for k in range(lo + 1, hi):
x: Optional[int] = k
while x != h and x != 0:
x = heads[x]
if x != h:
return False
return True
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_eisner_algorithm.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/eisner-algorithm/. The authors are listed in prov/JTW3A2.jsonl.
import itertools
import math
import random
from fractions import Fraction as F
import pytest
from eisner_algorithm import eisner, eisner_inside, is_projective, is_tree, tree_score
from nlslog import COUNTING, LOG, PROB, log_sum
# John saw Mary, words 1..3; the matrix is scores[h][d].
JOHN_SAW_MARY = [
[0, 9, 10, 9],
[0, 0, 20, 3],
[0, 30, 0, 30],
[0, 11, 0, 0],
]
def all_trees(n):
"""Brute force: every head list of n words that forms a tree rooted at 0."""
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)}
PROJ = {n: [t for t in TREES[n] if is_projective(t)] for n in TREES}
def root_children(heads):
return sum(1 for h in heads[1:] if h == 0)
def random_scores(rng, n, lo=-10, hi=10):
return [[rng.randint(lo, hi) for _ in range(n + 1)] for _ in range(n + 1)]
def test_tree_counts():
assert [len(TREES[n]) for n in range(1, 6)] == [1, 3, 16, 125, 1296]
assert [len(PROJ[n]) for n in range(1, 6)] == [1, 3, 12, 55, 273]
single = [sum(1 for t in PROJ[n] if root_children(t) == 1) for n in range(1, 6)]
assert single == [1, 2, 7, 30, 143]
def test_counting_semiring_gives_projective_counts():
for n in range(1, 6):
ones = [[1] * (n + 1) for _ in range(n + 1)]
assert eisner_inside(ones, COUNTING) == len(PROJ[n])
assert eisner_inside(ones, COUNTING, single_root=True) == sum(
1 for t in PROJ[n] if root_children(t) == 1
)
ones = [[1] * 11 for _ in range(11)]
# Projective trees over n words rooted at 0: 1, 3, 12, 55, 273, 1428, 7752, 43263, 246675, 1430715.
assert eisner_inside(ones, COUNTING) == 1430715
def test_example_john_saw_mary():
score, heads = eisner(JOHN_SAW_MARY)
assert score == 70
assert heads == [-1, 2, 0, 2]
@pytest.mark.parametrize("single_root", [False, True])
def test_against_brute_force(single_root):
rng = random.Random(7)
for n in range(1, 6):
for _ in range(30 if n < 5 else 12):
s = random_scores(rng, n)
pool = [t for t in PROJ[n] if not single_root or root_children(t) == 1]
best = max(tree_score(s, t) for t in pool)
score, heads = eisner(s, single_root=single_root)
assert score == best
assert is_tree(heads) and is_projective(heads)
assert tree_score(s, heads) == score
if single_root:
assert root_children(heads) == 1
def test_exact_fractions():
rng = random.Random(11)
n = 4
s = [[F(rng.randint(-20, 20), rng.randint(1, 7)) for _ in range(n + 1)] for _ in range(n + 1)]
score, heads = eisner(s)
assert score == max(tree_score(s, t) for t in PROJ[n])
assert isinstance(score, F)
def test_best_projective_can_lose_to_a_non_projective_tree():
# The non-projective tree 0 -> 2, 2 -> 4, 4 -> 1, 2 -> 3 gets the high scores.
n = 4
s = [[0] * (n + 1) for _ in range(n + 1)]
s[0][2] = s[2][4] = s[4][1] = s[2][3] = 10
nonproj = [-1, 4, 0, 2, 2]
assert is_tree(nonproj) and not is_projective(nonproj)
score, heads = eisner(s)
assert tree_score(s, nonproj) == 40
assert score == max(tree_score(s, t) for t in PROJ[n]) < 40
assert max(tree_score(s, t) for t in TREES[n]) == 40
def test_log_partition_function():
rng = random.Random(3)
for n in range(1, 6):
s = [[rng.uniform(-2, 2) for _ in range(n + 1)] for _ in range(n + 1)]
logz = eisner_inside(s, LOG)
assert logz == pytest.approx(log_sum(tree_score(s, t) for t in PROJ[n]), abs=1e-9)
def test_log_space_avoids_underflow():
n = 10
s = [[-100.0] * (n + 1) for _ in range(n + 1)]
probs = [[math.exp(x) for x in row] for row in s]
# Each tree has probability exp(-1000), which is 0.0 in double precision.
assert eisner_inside(probs, PROB) == 0.0
assert eisner_inside(s, LOG) == pytest.approx(-1000.0 + math.log(1430715), abs=1e-9)
def test_small_inputs():
assert eisner([[0]]) == (0, [-1])
assert eisner([[0, 5], [0, 0]]) == (5, [-1, 0])
with pytest.raises(ValueError):
eisner([[0, 1]])
History
Before 1996, projective dependency parsing with lexical scores was done with lexicalized phrase structure charts, whose items carry a head word anywhere inside the span and take time. Eisner (1996), comparing three probabilistic models of dependency structure, parsed with spans whose heads sit at their ends, which gives . McDonald, Crammer and Pereira (2005) used the algorithm as the decoder of a discriminative first-order parser trained online with large margins, and McDonald and Pereira (2006) extended it to second-order scores. It has remained the standard exact decoder for projective trees, also for neural arc scorers.
References
- Jason M. Eisner, Three new probabilistic models for dependency parsing, an exploration, COLING 1996, the parsing algorithm over spans whose heads are at their ends
- 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, the Eisner algorithm and its second-order extension)
- Ryan McDonald, Koby Crammer and Fernando Pereira, Online large-margin training of dependency parsers, ACL 2005, the use of the Eisner algorithm as the decoder of a first-order projective parser
- Ryan McDonald and Fernando Pereira, Online learning of approximate dependency parsing algorithms, EACL 2006, the second-order extension with sibling items, still in cubic time
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 JTW3A2 Edit this page History Report an error Markdown