Algorithm Search⌘K

Algorithmresearch

End-to-end span-ranking coreference

Also called e2e-coref, Lee coreference model.

Score every span up to a width as a mention, prune, score each span with its candidate antecedents and a dummy of score 0, train on the marginal likelihood of gold antecedents, then link.

Time
O(n w log(n w) + n^2 w + n k) worst
Space
O(n w + n k) extra
Where
k = the number of antecedents kept per span; n = the number of tokens; w = the maximum span width
Properties
deterministicnot exactofflineiterative
Origin
Kenton Lee, Luheng He, Mike Lewis, Luke Zettlemoyer, 2017

The end-to-end span-ranking model of Lee, He, Lewis and Zettlemoyer (2017) solves coreference resolution without a parser and without a separate mention detector. It treats every span of a document up to a fixed width as a possible mention, gives each span a mention score, keeps the best spans, and lets each kept span choose one antecedent among the spans before it, or a dummy antecedent ε\varepsilon that means "no antecedent". Training maximizes the marginal likelihood of all gold antecedents, so no single gold antecedent has to be chosen. The mention-pair model classifies pairs on their own; this model ranks the candidate antecedents of a span against each other with a softmax, and it learns the mentions at the same time.

In plain words

Every short stretch of words could be a mention. The network gives each stretch a score that says how much it looks like a mention, and it keeps only the best ones, a fixed fraction of the document length. Then each kept stretch looks back at the stretches before it and gives each a score for "this one refers to the same thing as me". There is also a fixed option with score 0 that means "I start something new, or I am not a mention at all". The stretch picks its highest scoring option. Linked stretches form the groups. In training, the network is rewarded for putting probability on any correct earlier stretch, not on one fixed choice.

The problem

Input: a document of nn tokens, with speaker and genre information if the data has it. A span (a,b)(a, b) covers the tokens a+1,…,ba + 1, \ldots, b (fencepost indices, 0≤a<b≤n0 \le a < b \le n). Output: a set of disjoint clusters of spans, where the spans of a cluster refer to the same entity. Spans that are in no cluster of size two or more are not output. In the CoNLL-2012 data (Pradhan et al. 2012) singletons are not annotated, so this matches the data.

The model gives each span ii an antecedent yi∈Y(i)={ε,1,…,i−1}y_i \in Y(i) = \{\varepsilon, 1, \ldots, i - 1\}, where the spans are ordered by start and then by end. With the score s(i,ε)=0s(i, \varepsilon) = 0 and

s(i,j)=sm(i)+sm(j)+sa(i,j),s(i, j) = s_m(i) + s_m(j) + s_a(i, j),

it takes the antecedents of different spans to be independent:

P(y1,…,yN)=∏i=1Nexp⁡s(i,yi)∑y′∈Y(i)exp⁡s(i,y′).P(y_1, \ldots, y_N) = \prod_{i=1}^{N} \frac{\exp s(i, y_i)}{\sum_{y' \in Y(i)} \exp s(i, y')}.

The mention score sm(i)s_m(i) and the antecedent score sa(i,j)s_a(i, j) come from feed-forward networks (Lee et al. 2017, Section 4). The span representation joins the outputs of a bidirectional LSTM at the first and last token of the span, an attention-weighted sum of the word vectors of the span (a learned "head"), and a feature for the width. The pair network sees the two span representations, their elementwise product, and features for the speaker, the genre and the distance. Fixing the dummy score at 0 makes the scores relative: a span links to jj only if s(i,j)>0s(i, j) > 0 beats all other options.

With all O(n2)O(n^2) spans and all pairs, the model has O(n4)O(n^4) pair scores. Pruning makes it practical.

The algorithm

The code takes the mention scores and pair scores of the network as given and implements the pruning, the antecedent distribution, the loss with its gradient, and the decoder. Logs are natural logs.

  1. SPAN-RANKING-COREF(n, s_m, s_a, L, λ, K, gold clusters)
  2. 1S ← all spans (a, b) with 0 ≤ a < b ≤ n and b - a ≤ L
  3. 2sort S by s_m, highest first (ties by start, then end)
  4. 3M ← empty; for each span t of S while |M| < floor(λ n): if t crosses no span of M then add t to M
  5. 4sort M by start, then by end; call its spans 1 .. m
  6. 5for i ← 1 to m do Y(i) ← ε and the up to K nearest spans of M before i
  7. 6s(i, ε) ← 0; s(i, j) ← s_m(i) + s_m(j) + s_a(i, j) for each other j in Y(i)
  8. 7log P(y | i) ← s(i, y) - log Σ_{y' in Y(i)} exp s(i, y')
  9. 8G(i) ← the spans of Y(i) in the gold cluster of i, or ε alone if there are none
  10. 9loss ← loss - log Σ_{y in G(i)} P(y | i)
  11. 10ŷ_i ← the first y of Y(i) with the largest s(i, y), ε first
  12. 11link each i with ŷ_i ≠ ε to the cluster of ŷ_i; return the clusters of two or more spans and the loss

Two spans (a,b)(a, b) and (c,d)(c, d) cross when a<c<b<da < c < b < d or c<a<d<bc < a < d < b: they overlap and neither holds the other. This is the rule of Section 5 of the paper, written with fencepost indices. Nested spans, such as "the president of the company" and "the company", may both be kept.

The gradient of the loss with respect to the score of a pair is P(y∣i)−Q(y∣i)P(y \mid i) - Q(y \mid i), where QQ is PP restricted to G(i)G(i) and renormalized. The network then passes this into sms_m and sas_a by the chain rule: sm(k)s_m(k) gets the sum over all pairs that contain kk.

The paper gives only the maximum number KK of antecedents. The code keeps the KK nearest earlier spans. The paper sets L=10L = 10, λ=0.4\lambda = 0.4 and K=250K = 250 (Section 7), chosen for the CoNLL-2012 data; these are settings, not derived values.

Example

Take "Alice met Bob and she smiled", with n=6n = 6, L=2L = 2, λ=0.75\lambda = 0.75 and K=3K = 3. There are 11 spans of width 1 or 2. Say the network gives the mention scores Alice (0,1)(0, 1): 2.0, she (4,5)(4, 5): 1.8, "met Bob" (1,3)(1, 3): 1.6, "Alice met" (0,2)(0, 2): 1.55, Bob (2,3)(2, 3): 1.5, and −3-3 to every other span. The limit is ⌊0.75⋅6⌋=4\lfloor 0.75 \cdot 6 \rfloor = 4 spans.

Pruning takes Alice, she and "met Bob". "Alice met" crosses "met Bob" (0<1<2<30 < 1 < 2 < 3), so it is skipped. Bob is nested in "met Bob", so it is kept, and MM is full. In order, MM = Alice, "met Bob", Bob, she. The pruning kept a span that is not a mention, "met Bob"; the antecedent scores have to deal with it.

Let the pair scores be sas_a = 1.0 for (she, Alice), −2.5-2.5 for (she, Bob), and −5-5 or −4-4 for the other pairs. For "she" the four options score:

antecedent score PP
ε\varepsilon 0 0.0080
Bob 1.8+1.5−2.5=0.81.8 + 1.5 - 2.5 = 0.8 0.0178
"met Bob" 1.8+1.6−5=−1.61.8 + 1.6 - 5 = -1.6 0.0016
Alice 1.8+2.0+1.0=4.81.8 + 2.0 + 1.0 = 4.8 0.9726

"Met Bob" scores −1.4-1.4 against Alice, and Bob scores −1.9-1.9 against "met Bob" and −0.5-0.5 against Alice, so both pick ε\varepsilon. The output is one cluster, {Alice, she}. With the gold cluster {Alice, she}, the loss is log⁡(1+e−1.4)+log⁡(1+e−1.9+e−0.5)+(log⁡(1+e0.8+e−1.6+e4.8)−4.8)=0.2204+0.5631+0.0278=0.8113\log(1 + e^{-1.4}) + \log(1 + e^{-1.9} + e^{-0.5}) + (\log(1 + e^{0.8} + e^{-1.6} + e^{4.8}) - 4.8) = 0.2204 + 0.5631 + 0.0278 = 0.8113.

With K=2K = 2, "she" sees only Bob and "met Bob". It links to Bob, because 0.8>00.8 > 0. Its gold antecedent was cut off, so G(she)={ε}G(\text{she}) = \{\varepsilon\}, its loss term grows to 1.2318, and the training signal now asks "she" to start a new entity. The test file checks all these numbers.

Correctness

The proof in proofs/correctness.md shows four things. The kept spans are at most ⌊λn⌋\lfloor \lambda n \rfloor and no two of them cross. The loss is the negative log of the total probability of all full antecedent assignments that agree with the gold clusters, because the model is a product over spans and the sum of a product over a product set factorizes. The gradient is P−QP - Q as above. The decoder returns a most probable assignment, since each factor can be maximized alone, and the links form a forest because each link points to an earlier span, so the clusters are well defined. The test file checks the loss against the sum over all assignments, the gradient against central finite differences, and the decoder against all assignments.

The model itself carries no guarantee: the scores come from a trained network, and the quality of the clusters is a measurement.

Proof: Span-ranking coreference: the pruning, the marginal likelihood loss and its gradient, and the decoder are correctfull

Fix a document of nn tokens, a maximum width LL, a ratio λ>0\lambda > 0, a number K≥1K \ge 1 of antecedents, mention scores sm(i)s_m(i) for every span of width at most LL, and pair scores sa(i,j)s_a(i, j). Spans use fencepost indices: (a,b)(a, b) covers the tokens a+1,…,ba + 1, \ldots, b. Logs are natural logs. The line numbers refer to the pseudocode on the page.

Claim 1: the kept spans are a non-crossing set of at most floor(lambda n) spans

Line L3 adds a span to MM only while ∣M∣<⌊λn⌋|M| < \lfloor \lambda n \rfloor, so ∣M∣≤⌊λn⌋|M| \le \lfloor \lambda n \rfloor at the end. It adds a span only if it crosses no span already in MM. Crossing is symmetric: (a,b)(a, b) and (c,d)(c, d) cross when a<c<b<da < c < b < d or c<a<d<bc < a < d < b, and the two conditions swap when the spans swap. So when a span tt joins MM, it crosses no earlier member, and every later member was tested against tt. Hence no two members of MM cross. Also, if a span ss was skipped while MM was not full, then ss crosses some member of MM that was added before it, so a skipped span with a higher score than a kept span always crosses a kept span. Line L4 only reorders MM.

Claim 2: the loss is the negative log of a marginal over full antecedent assignments

Let m=∣M∣m = |M| and let Y(i)Y(i) be the list of line L5: the dummy ε\varepsilon and at most KK earlier spans. Line L6 sets s(i,ε)=0s(i, \varepsilon) = 0 and s(i,j)=sm(i)+sm(j)+sa(i,j)s(i, j) = s_m(i) + s_m(j) + s_a(i, j). Line L7 gives

P(y∣i)=exp⁡s(i,y)∑y′∈Y(i)exp⁡s(i,y′),P(y \mid i) = \frac{\exp s(i, y)}{\sum_{y' \in Y(i)} \exp s(i, y')},

which is positive and sums to 1 over Y(i)Y(i). The model of Lee et al. (2017) takes the antecedents of different spans to be independent, so a full assignment y=(y1,…,ym)y = (y_1, \ldots, y_m) with yi∈Y(i)y_i \in Y(i) has probability P(y)=∏iP(yi∣i)P(y) = \prod_i P(y_i \mid i). Let G(i)⊆Y(i)G(i) \subseteq Y(i) be the set of line L8. It is never empty: it holds the gold antecedents of ii among Y(i)Y(i), or ε\varepsilon alone if there are none. The set of assignments consistent with the gold clusters is the product G(1)×⋯×G(m)G(1) \times \cdots \times G(m), so

∑y∈G(1)×⋯×G(m)∏iP(yi∣i)=∏i∑yi∈G(i)P(yi∣i)\sum_{y \in G(1) \times \cdots \times G(m)} \prod_i P(y_i \mid i) = \prod_i \sum_{y_i \in G(i)} P(y_i \mid i)

by the distributive law. Taking −log⁡-\log gives the sum of line L9. Each factor is in (0,1](0, 1], so the loss is at least 0. It is 0 exactly when every span puts all its probability on G(i)G(i), which with finite scores happens only when G(i)=Y(i)G(i) = Y(i).

The code computes log⁡P(y∣i)\log P(y \mid i) with log_softmax and the inner sum with log_sum from the shared helper. Both subtract the largest value before any exp, so no exp of a positive number is taken and the result is finite whenever the scores are finite. The test file checks the identity above against the sum over all assignments, listed one by one, on random documents.

Claim 3: the gradient

Write Zi=∑y′∈Y(i)exp⁡s(i,y′)Z_i = \sum_{y' \in Y(i)} \exp s(i, y') and ZiG=∑y′∈G(i)exp⁡s(i,y′)Z_i^G = \sum_{y' \in G(i)} \exp s(i, y'). The term of span ii is ℓi=log⁡Zi−log⁡ZiG\ell_i = \log Z_i - \log Z_i^G. For y∈Y(i)y \in Y(i),

∂ℓi∂s(i,y)=exp⁡s(i,y)Zi−[y∈G(i)]exp⁡s(i,y)ZiG=P(y∣i)−Q(y∣i),\frac{\partial \ell_i}{\partial s(i, y)} = \frac{\exp s(i, y)}{Z_i} - [y \in G(i)] \frac{\exp s(i, y)}{Z_i^G} = P(y \mid i) - Q(y \mid i),

where Q(y∣i)Q(y \mid i) is P(y∣i)P(y \mid i) restricted to G(i)G(i) and renormalized. The score s(i,y)s(i, y) appears in ℓi\ell_i only. By the chain rule, ∂ℓ/∂sa(i,j)=P(j∣i)−Q(j∣i)\partial \ell / \partial s_a(i, j) = P(j \mid i) - Q(j \mid i), and ∂ℓ/∂sm(k)\partial \ell / \partial s_m(k) is the sum of P(y∣i)−Q(y∣i)P(y \mid i) - Q(y \mid i) over every pair (i,y)(i, y) with y≠εy \ne \varepsilon in which kk is either ii or yy. The dummy score is the constant 0 and has no gradient. This is what loss_and_grad returns; the test file checks every component against central finite differences with h=10−6h = 10^{-6} and tolerance 10−510^{-5}.

Claim 4: the decoder returns a most probable assignment and well-formed clusters

Since P(y)=∏iP(yi∣i)P(y) = \prod_i P(y_i \mid i) and the factors depend on different coordinates, P(y)P(y) is largest when each factor is largest. P(y∣i)P(y \mid i) is increasing in s(i,y)s(i, y) for a fixed ii, so line L10 picks a maximizer of each factor, and the tuple of the choices maximizes P(y)P(y). The test file checks this against all assignments.

Each span ii has at most one antecedent y^i\hat y_i, and y^i\hat y_i comes before ii in the order of line L4. Draw an edge from ii to y^i\hat y_i. Every edge points to an earlier span, so the edges form no cycle and the graph is a forest; each tree has exactly one span with y^=ε\hat y = \varepsilon, its first span. Line L11 walks the spans in order. When it reaches ii with y^i=j\hat y_i = j, the span jj has been processed already, so its cluster is known (or jj starts a new one), and ii joins it. By induction over the order, the cluster of each span is the tree that contains it. The output clusters are the trees with at least two spans, and they are disjoint.

Complexity

There are at most nLn L spans. Sorting them costs O(nLlog⁡(nL))O(n L \log(n L)). The crossing test in the code compares each span with the up to λn\lambda n kept spans, O(n2L)O(n^2 L) in total; a structure over the kept spans can make this faster, but it is not the bottleneck in practice. After pruning, the ⌊λn⌋\lfloor \lambda n \rfloor spans have at most KK candidates each, so scoring, the loss, the gradient and the decoding take O(nK)O(n K) pair evaluations of the network. Without pruning, all spans and all pairs give O(n4)O(n^4) pair scores (Lee et al. 2017, Section 4). The YAML uses ww for LL and kk for KK.

Properties

  • The loss is a sum of one term per span, log⁡Zi−log⁡ZiG\log Z_i - \log Z_i^G, where ZiZ_i sums exp⁡s(i,y)\exp s(i, y) over Y(i)Y(i) and ZiGZ_i^G over G(i)G(i). This is the difference of two log-sum-exp functions of the scores. It is convex in the scores when G(i)G(i) has one element, but not in general when a span has several gold antecedents, and it is not convex in the network weights.
  • The decoder is exact for the model (a theorem, proved above), but the model ignores the constraint that clusters are transitive in a global sense: each span chooses alone, and the clusters are the connected components of the choices. Exact clustering under pairwise scores is correlation clustering, which is NP-hard (Bansal, Blum and Chawla 2004); the model avoids it by its independence assumption.
  • Measured accuracy (a measurement): on the CoNLL-2012 English test set, the single model of Lee et al. (2017) scored 67.2 average F1 (MUC 75.8, B-cubed 65.0, CEAF-phi4 60.8), and an ensemble of 5 models scored 68.8. The paper reports more than 92% recall of the gold mentions after pruning with λ=0.4\lambda = 0.4.
  • Training truncates long documents: the paper keeps at most 50 sentences per document in training.

Variants and improvements

  • Higher-order inference and coarse-to-fine pruning: Lee, He and Zettlemoyer (2018, NAACL) refine the span representations with the expected antecedent and add a cheap bilinear score to prune antecedents before the full pair network.
  • Better encoders: replacing the LSTM with BERT or SpanBERT, which masks whole spans in pretraining, raised the CoNLL-2012 scores a great deal in later work; these gains are measurements of the encoder, not of the span-ranking algorithm.
  • Mention-ranking models before 2017, for example by Wiseman, Rush, Shieber and Weston (2015) and Clark and Manning (2016), used the same antecedent softmax over gold or predicted mentions from a separate detector.
  • Entity-level models score a span against a partial cluster instead of one antecedent, which brings back some transitivity at a higher cost.

When to use it

Use the span-ranking model, or one of its descendants with a pretrained encoder, as the default for English coreference in data like OntoNotes. Use the mention-pair model to explain the basic ideas, or where little training data and no neural encoder are available. For pronouns alone with parse trees, the Hobbs algorithm is a strong rule-based baseline.

Pitfalls

  • Gold antecedents cut by pruning: if KK or λ\lambda is too small, the gold set of a span becomes {ε}\{\varepsilon\}, and the loss teaches the model to say "new entity" for a mention that has an antecedent. The example above shows this with K=2K = 2.
  • Spans ordered differently: the antecedent set must follow the same span order in training and decoding. The paper orders by start and then by end.
  • Underflow and overflow: the softmax must be computed in log space. A score of 900 makes exp⁡\exp overflow in double precision; the test file has such a case.
  • Singletons: the CoNLL-2012 data has no singleton clusters, so spans with y^=ε\hat y = \varepsilon and no later link are dropped from the output. On data with singletons the output rule must change.
  • Comparing scores: the CoNLL score depends on the scorer version. Use the reference scorer of Pradhan et al. (2014).

Implementations

The code takes the mention and pair scores of the network as given and implements the pruning, the loss, its gradient and the decoding; it does not train a network.

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.

nlslog.pyI0RawGitHub
# 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
span_ranking_coreference.py 155 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/span-ranking-coreference/. The authors are listed in prov/YCRS0W.jsonl.

"""The span-ranking coreference model of Lee, He, Lewis and Zettlemoyer (2017).

The network is not trained here. The mention scores s_m(span) and the pair
scores s_a(span, antecedent) are given as numbers. This file implements the
algorithm around them:

- enumerate all spans of width at most L;
- prune to at most floor(lambda n) spans by mention score, without crossing
  spans, and keep at most K antecedents per span;
- the antecedent distribution P(y | i), with the dummy antecedent EPS of
  score 0;
- the marginal log likelihood loss of the gold antecedents and its gradient
  with respect to every s_m and s_a value;
- the decoding: the best antecedent of each span, and the clusters it implies.

Spans use fencepost indices: (a, b) covers the tokens a + 1 .. b of a document
of n tokens, with 0 <= a < b <= n. Logs are natural logs.

Tie rules: pruning sorts by score, then by start, then by end; the decoder
takes the first best antecedent in the order EPS, then nearest first.
"""

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

from nlslog import argmax, log_softmax, log_sum

Span = Tuple[int, int]
EPS = None  # the dummy antecedent: the span starts a new cluster or is not a mention


def all_spans(n: int, max_width: int) -> List[Span]:
    """All spans (a, b) with 0 <= a < b <= n and b - a <= max_width, by start, then end."""
    return [(a, b) for a in range(n) for b in range(a + 1, min(n, a + max_width) + 1)]  # @line L1


def crosses(s: Span, t: Span) -> bool:
    """True if the two spans overlap and neither contains the other."""
    (a, b), (c, d) = s, t
    return a < c < b < d or c < a < d < b


def prune(n: int, s_m: Dict[Span, float], max_width: int, lam: float) -> List[Span]:
    """Keep at most floor(lam n) spans with the highest mention scores and no crossing pair.

    Spans are taken in order of score (highest first); a span that crosses a span
    already kept is skipped. The kept spans are returned in order of start, then end.
    """
    limit = int(math.floor(lam * n + 1e-9))
    order = sorted(all_spans(n, max_width), key=lambda s: (-s_m[s], s[0], s[1]))  # @line L2
    kept: List[Span] = []
    for s in order:  # @line L3
        if len(kept) >= limit:
            break
        if not any(crosses(s, t) for t in kept):
            kept.append(s)
    return sorted(kept)  # @line L4


def candidates(spans: Sequence[Span], k: int) -> List[List[int]]:
    """For each kept span i, the indices of the up to k nearest earlier kept spans, nearest first."""
    return [list(range(i - 1, max(-1, i - 1 - k), -1)) for i in range(len(spans))]  # @line L5


def scores(spans: Sequence[Span], cands: List[List[int]], s_m: Dict[Span, float],
           s_a: Dict[Tuple[Span, Span], float]) -> List[List[float]]:
    """The scores of [EPS] + cands[i] for each span i: 0, then s_m(i) + s_m(j) + s_a(i, j)."""
    out = []
    for i, cs in enumerate(cands):
        si = spans[i]
        out.append([0.0] + [s_m[si] + s_m[spans[j]] + s_a[(si, spans[j])] for j in cs])  # @line L6
    return out


def gold_sets(spans: Sequence[Span], cands: List[List[int]],
              clusters: Sequence[Sequence[Span]]) -> List[List[int]]:
    """For each span, the positions in [EPS] + cands[i] of its gold antecedents.

    Position 0 is EPS. A span with no gold cluster, or whose gold antecedents were
    all pruned, gets [0].
    """
    cid = {}
    for c, cl in enumerate(clusters):
        for s in cl:
            cid[s] = c
    out = []
    for i, cs in enumerate(cands):
        c = cid.get(spans[i])
        g = [p + 1 for p, j in enumerate(cs) if c is not None and cid.get(spans[j]) == c]
        out.append(g if g else [0])  # @line L8
    return out


def loss_and_grad(spans, cands, s_m, s_a, clusters):
    """Return (loss, d_m, d_a): the negative marginal log likelihood and its gradient.

    loss = - sum over spans i of log sum over y in GOLD(i) of P(y | i).
    d_m maps each kept span to d loss / d s_m, and d_a each candidate pair to d loss / d s_a.
    """
    sc = scores(spans, cands, s_m, s_a)
    gold = gold_sets(spans, cands, clusters)
    loss = 0.0
    d_m = {s: 0.0 for s in spans}
    d_a = {}
    for i, row in enumerate(sc):
        logp = log_softmax(row)  # @line L7
        lg = log_sum(logp[y] for y in gold[i])
        loss -= lg  # @line L9
        gset = set(gold[i])
        for p, j in enumerate(cands[i]):
            y = p + 1
            q = math.exp(logp[y] - lg) if y in gset else 0.0  # P(y | i) given that y is gold
            g = math.exp(logp[y]) - q  # d loss / d s(i, y)
            d_a[(spans[i], spans[j])] = g
            d_m[spans[i]] += g
            d_m[spans[j]] += g
    return loss, d_m, d_a


def decode(spans, cands, s_m, s_a) -> Tuple[List, List[List[Span]]]:
    """Return (antecedent, clusters): the best antecedent of each span and the clusters.

    antecedent[i] is a span or EPS. Clusters with one span are not returned.
    """
    sc = scores(spans, cands, s_m, s_a)
    ante = []
    cluster_of: Dict[int, int] = {}
    clusters: List[List[Span]] = []
    for i, row in enumerate(sc):
        y = argmax(row)  # @line L10
        if y == 0:
            ante.append(EPS)
            continue
        j = cands[i][y - 1]
        ante.append(spans[j])
        if j not in cluster_of:  # @line L11
            cluster_of[j] = len(clusters)
            clusters.append([spans[j]])
        cluster_of[i] = cluster_of[j]
        clusters[cluster_of[j]].append(spans[i])
    return ante, clusters


def resolve(n, s_m, s_a, max_width, lam, k, clusters=None):
    """The whole pipeline: prune, list antecedents, decode, and the loss if gold clusters are given."""
    spans = prune(n, s_m, max_width, lam)
    cands = candidates(spans, k)
    ante, pred = decode(spans, cands, s_m, s_a)
    loss = None
    if clusters is not None:
        loss = loss_and_grad(spans, cands, s_m, s_a, clusters)[0]
    return spans, ante, pred, loss
test_span_ranking_coreference.py 180 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/span-ranking-coreference/. The authors are listed in prov/YCRS0W.jsonl.

import math
import random
from itertools import product

from span_ranking_coreference import (EPS, all_spans, candidates, crosses, decode, gold_sets,
                                      loss_and_grad, prune, resolve, scores)

# The example of the page: "Alice met Bob and she smiled", n = 6, L = 2, lambda = 0.75.
N = 6
ALICE, METBOB, BOB, SHE, ALICEMET = (0, 1), (1, 3), (2, 3), (4, 5), (0, 2)
SM = {s: -3.0 for s in all_spans(6, 2)}
SM.update({ALICE: 2.0, SHE: 1.8, METBOB: 1.6, ALICEMET: 1.55, BOB: 1.5})
GOLD = [[ALICE, SHE]]


def example_pairs():
    sa = {(s, t): 0.0 for s in all_spans(6, 2) for t in all_spans(6, 2)}
    sa[(SHE, ALICE)] = 1.0
    sa[(SHE, BOB)] = -2.5
    sa[(SHE, METBOB)] = -5.0
    sa[(BOB, ALICE)] = -4.0
    sa[(BOB, METBOB)] = -5.0
    sa[(METBOB, ALICE)] = -5.0
    return sa


def test_spans_and_crossing():
    assert len(all_spans(6, 2)) == 11
    assert len(all_spans(5, 5)) == 15
    assert crosses((0, 2), (1, 3)) and crosses((1, 3), (0, 2))
    assert not crosses((0, 2), (2, 3)) and not crosses((0, 3), (1, 2)) and not crosses((0, 1), (0, 2))


def test_page_example():
    spans = prune(N, SM, 2, 0.75)
    assert spans == [ALICE, METBOB, BOB, SHE]  # "Alice met" crosses "met Bob" and is skipped
    sa = example_pairs()
    cands3 = candidates(spans, 3)
    assert cands3 == [[], [0], [1, 0], [2, 1, 0]]
    row = scores(spans, cands3, SM, sa)[3]
    assert [round(x, 9) for x in row] == [0.0, 0.8, -1.6, 4.8]
    ante, pred = decode(spans, cands3, SM, sa)
    assert ante == [EPS, EPS, EPS, ALICE]
    assert pred == [[ALICE, SHE]]
    loss, _, _ = loss_and_grad(spans, cands3, SM, sa, GOLD)
    assert abs(loss - 0.811329) < 1e-6
    # K = 2: "she" no longer sees "Alice", links to "Bob", and its gold set becomes the dummy.
    cands2 = candidates(spans, 2)
    ante, pred = decode(spans, cands2, SM, sa)
    assert ante == [EPS, EPS, EPS, BOB]
    assert gold_sets(spans, cands2, GOLD)[3] == [0]
    loss, _, _ = loss_and_grad(spans, cands2, SM, sa, GOLD)
    assert abs(loss - 2.015326) < 1e-6


def brute_loss(spans, cands, s_m, s_a, clusters):
    """- log of the sum, over all full antecedent assignments consistent with gold, of their probability."""
    sc = scores(spans, cands, s_m, s_a)
    gold = gold_sets(spans, cands, clusters)
    probs = []
    for row in sc:
        z = sum(math.exp(x) for x in row)
        probs.append([math.exp(x) / z for x in row])
    total = 0.0
    for ys in product(*[range(len(r)) for r in sc]):
        if all(y in g for y, g in zip(ys, gold)):
            p = 1.0
            for i, y in enumerate(ys):
                p *= probs[i][y]
            total += p
    return -math.log(total)


def random_doc(rng, n=7, width=3):
    s_m = {s: rng.uniform(-2, 2) for s in all_spans(n, width)}
    spans = prune(n, s_m, width, 0.8)
    cands = candidates(spans, 3)
    s_a = {}
    for i, cs in enumerate(cands):
        for j in cs:
            s_a[(spans[i], spans[j])] = rng.uniform(-2, 2)
    pool = spans[:]
    rng.shuffle(pool)
    clusters = [pool[0:2], pool[2:5], [(0, n)]]  # (0, n) is wider than L, so never a candidate
    return spans, cands, s_m, s_a, clusters


def test_loss_against_enumeration():
    rng = random.Random(1)
    for _ in range(30):
        spans, cands, s_m, s_a, clusters = random_doc(rng)
        loss = loss_and_grad(spans, cands, s_m, s_a, clusters)[0]
        assert abs(loss - brute_loss(spans, cands, s_m, s_a, clusters)) < 1e-9


def test_gradient_finite_differences():
    rng = random.Random(2)
    h = 1e-6
    for _ in range(5):
        spans, cands, s_m, s_a, clusters = random_doc(rng)
        _, d_m, d_a = loss_and_grad(spans, cands, s_m, s_a, clusters)
        for s in spans:
            up, dn = dict(s_m), dict(s_m)
            up[s] += h
            dn[s] -= h
            num = (loss_and_grad(spans, cands, up, s_a, clusters)[0]
                   - loss_and_grad(spans, cands, dn, s_a, clusters)[0]) / (2 * h)
            assert abs(num - d_m[s]) < 1e-5
        for key in s_a:
            up, dn = dict(s_a), dict(s_a)
            up[key] += h
            dn[key] -= h
            num = (loss_and_grad(spans, cands, s_m, up, clusters)[0]
                   - loss_and_grad(spans, cands, s_m, dn, clusters)[0]) / (2 * h)
            assert abs(num - d_a[key]) < 1e-5


def test_pruning_properties():
    rng = random.Random(3)
    for _ in range(50):
        n = rng.randint(1, 8)
        w = rng.randint(1, 4)
        s_m = {s: rng.uniform(-1, 1) for s in all_spans(n, w)}
        kept = prune(n, s_m, w, 0.6)
        assert len(kept) <= math.floor(0.6 * n + 1e-9)
        assert kept == sorted(kept)
        assert not any(crosses(s, t) for s in kept for t in kept)
        # A span that was skipped although it scores above a kept span crosses a kept span.
        low = min((s_m[s] for s in kept), default=None)
        for s in all_spans(n, w):
            if s not in kept and low is not None and s_m[s] > low:
                assert any(crosses(s, t) for t in kept)


def test_decode_is_joint_argmax():
    rng = random.Random(4)
    for _ in range(20):
        spans, cands, s_m, s_a, _ = random_doc(rng, n=6, width=2)
        ante, pred = decode(spans, cands, s_m, s_a)
        sc = scores(spans, cands, s_m, s_a)
        best, arg = None, None
        for ys in product(*[range(len(r)) for r in sc]):
            v = sum(r[y] - math.log(sum(math.exp(x) for x in r)) for r, y in zip(sc, ys))
            if best is None or v > best + 1e-12:
                best, arg = v, ys
        got = [0 if a is EPS else cands[i].index(spans.index(a)) + 1 for i, a in enumerate(ante)]
        assert tuple(got) == arg
        # The clusters are the connected components of the antecedent links.
        seen = [s for c in pred for s in c]
        assert len(seen) == len(set(seen))
        for i, a in enumerate(ante):
            if a is not EPS:
                assert any(spans[i] in c and a in c for c in pred)


def test_large_scores_stay_finite():
    spans = [(0, 1), (1, 2)]
    cands = candidates(spans, 1)
    s_m = {(0, 1): 400.0, (1, 2): 400.0}
    s_a = {((1, 2), (0, 1)): 100.0}
    try:
        math.exp(900.0)
        raised = False
    except OverflowError:
        raised = True
    assert raised  # the plain softmax would overflow
    loss, d_m, _ = loss_and_grad(spans, cands, s_m, s_a, [[(0, 1), (1, 2)]])
    assert loss == 0.0 and d_m[(1, 2)] == 0.0
    loss, _, _ = loss_and_grad(spans, cands, s_m, s_a, [])
    assert abs(loss - 900.0) < 1e-9


def test_resolve_pipeline():
    spans, ante, pred, loss = resolve(N, SM, example_pairs(), 2, 0.75, 3, GOLD)
    assert spans == [ALICE, METBOB, BOB, SHE]
    assert pred == [[ALICE, SHE]]
    assert abs(loss - 0.811329) < 1e-6

History

Before 2017, coreference systems first found mentions with a parser or a separate detector and then linked them. Mention-ranking models such as those of Denis and Baldridge (2008), Durrett and Klein (2013) and Wiseman et al. (2015) had already replaced pairwise classification with a softmax over candidate antecedents. Lee, He, Lewis and Zettlemoyer (2017) removed the pipeline: they scored all spans, pruned them by a learned mention score, and trained the whole model from the marginal likelihood of the gold antecedents. Their model and code became the base of most neural coreference systems that followed, including those with ELMo, BERT and SpanBERT encoders.

References

  1. Kenton Lee, Luheng He, Mike Lewis and Luke Zettlemoyer, End-to-end neural coreference resolution, Proceedings of EMNLP 2017, pages 188 to 197, Section 3 (the task and the antecedent sets with the dummy), Section 4 (the span representations and the scores s_m and s_a), Section 5 (pruning with width L, ratio lambda, K antecedents and the crossing rule), Section 6 (the marginal log likelihood), Section 7 (L = 10, lambda = 0.4, K = 250), the results table on the CoNLL-2012 English test set
  2. Pradhan et al. 2012, the English data set and the official score, the mean of the MUC, B-cubed and CEAF-e F1 values
  3. Sameer Pradhan, Xiaoqiang Luo, Marta Recasens, Eduard Hovy, Vincent Ng and Michael Strube, Scoring coreference partitions of predicted mentions: a reference implementation, ACL 2014 (short papers), pages 30 to 35, the reference scorer used for the numbers on this page

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.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