Coreference Resolution
Learn how resolvers group mentions into entity clusters, score antecedents, prune candidate pairs, and evaluate partitions with MUC, B-cubed, and CEAF.
Language AI HandbookAll chapters Coreference Resolution
Coreference resolution is the part of natural language processing that decides when two expressions in a document point to the same thing. The decision sounds small, almost clerical: mark that this name and that pronoun belong together. Its consequences are not small. When a downstream system uses clusters to combine evidence, it can associate facts about different mentions with the same entity. A relation extractor can aggregate evidence across sentences, a summarizer can avoid repeating itself, a question answering system can follow a chain of references, and a compliance checker can attribute an action to the right person. When the decision is wrong, the same machinery quietly transfers an action, an attribute, or a stance from one entity to another.
Read this report:
Dr. Alvarez briefed Dr. Bhatt on the reactor design. She had flagged the cooling loop in March. Alvarez asked Bhatt to sign off on the design. Bhatt refused. The regulator approved the design on Friday.
Who flagged the cooling loop? Either Dr. Alvarez or Dr. Bhatt could be the referent on this wording alone. Our example annotates the pronoun as Bhatt, using the later refusal to sign off as a cue. A reader could defend the other interpretation, so treat that annotation as an assumption of the example.
Suppose a resolver attaches She to Dr. Alvarez, the subject of the previous sentence. The wrong link places one Bhatt mention in Alvarez’s cluster. In a downstream report that assigns actions through those clusters, the decision can turn “Bhatt flagged the cooling loop” into “Alvarez flagged the cooling loop.”
A downstream error like this is easy to miss. The resulting sentence reads fluently even though it attributes the action to a different person. A reader who does not already know the document has no reason to stop and check which "she" did what.
Two mentions are coreferent when they refer to the same entity in a discourse. A coreference resolver groups the document’s detected mentions into entity clusters. A resolver may receive the mention boundaries as inputs or detect them from the document.
The resolver connects three kinds of objects.
- A mention is a span of text identified by token or character offsets. The half-open token span (0, 2) contains “Dr. Alvarez” in our example.
- An entity is what the mention refers to: a person in the world of the document. Entities are not in the text.
- A cluster is a set of mentions that a system claims refer to the same entity. It is a hypothesis about an entity, not the entity itself.
The offsets locate a mention in the document. The entity is the person or thing that the mention refers to, and the cluster records which other mentions the resolver assigns to that entity.
The distinction also explains why coreference evaluation is harder than it first looks. If the task were only to label spans, accuracy would be a natural metric. But the output is a set of sets, and two different partitions can both be partly correct in ways that simple accuracy cannot express. One system can split one true entity into two clusters, another can merge two true entities into one, and a third can do both in different places. A useful metric has to say something about all three cases, and the standard metrics do not agree on what that something should be.
The chapter covers candidate generation, antecedent scoring, clustering, and evaluation. The implementation compares three deterministic linkers on six supplied person spans. Holding those spans fixed lets you check how a single changed link affects the partition, its scores, and the entity a downstream system would associate with the flagging event.
What Coreference Is and Is Not
Before we can build a resolver, we need a precise picture of the object it produces. Coreference is often introduced with a handful of pronoun examples, which makes it sound simpler than it is. Pronouns are only one kind of mention, and identity of reference is only one kind of discourse dependency. The boundaries of the task matter because they determine what the model is asked to predict, what the annotation contains, and what the evaluation can possibly reward.
Mentions and Entity Clusters
With gold mentions supplied, a resolver only has to group their spans. The official CoNLL-2012 setting required predicted mentions from the document and other permitted input annotations. For example, two nonoverlapping spans can each name the same person.
The span notation is half-open in the usual way: (0, 2) covers tokens 0 and 1, not token 2. That convention is boring until it is violated. An off-by-one in a token span can turn "Dr. Alvarez" into "Dr." or into "Dr. Alvarez briefed", and every downstream comparison then measures a different object than the one the annotator marked. The implementation later checks token slices against the original string.
Mentions come in several syntactic shapes, and each brings its own problems:
- Proper names: "Dr. Alvarez". Easy to detect, easy to match by string, hard to disambiguate when two people share a name.
- Pronouns: "she", "her", "they". Require agreement and salience reasoning.
- Definite descriptions: "the engineer", "the lead". Require world knowledge and discourse context to link.
- Demonstratives: "this", "that". Can refer to entities, events, or whole propositions.
- Nominal predicates such as "an engineer" in "Alvarez is an engineer". OntoNotes treats copular attributes as properties of the subject's referent and omits them from coreference chains.
A name-matching rule can use spelling and known aliases. Agreement can narrow the possible referents of a pronoun. A definite description such as "the engineer" may pick out someone introduced by name, so resolving it can require context about the person's role. A mention detector that proposes every noun phrase will include nominal predicates as candidates.
Corpora define which expressions count as mentions. The OntoNotes coreference annotations include noun phrases and some verb headwords linked to event mentions, subject to the corpus guidelines. Under exact-span scoring, a prediction with different boundaries is counted as a mismatch.
Coreference, Anaphora, and Bridging
Coreference is identity of reference. Anaphora is a broader relation: one expression's interpretation depends on another expression. Not all anaphora is coreference.
Consider:
I bought a car last month. The steering wheel already needs replacing.
"The steering wheel" in this example depends on "a car" for its interpretation. The phrases refer to two distinct objects. Connecting them through a part-whole relation is bridging. An identity partition keeps the car and wheel in separate groups. A part-whole edge records the relation between those groups.
Rösiger et al. (2018) evaluate bridging by scoring links between bridging noun phrases and their antecedents. A coreference score restricted to identity links leaves the car-to-wheel relation outside the evaluation.
A demonstrative can also refer back to a clause.
The reactor passed inspection. That surprised the board.
"That" can pick out the reactor’s passing of the inspection or the fact that the reactor passed. An annotation scheme that includes events can group two mentions of the same event. To score a clause-content link against a reference, its annotations must mark the clause content as the antecedent.
Coreference groups mentions that share a referent. Bridging connects distinct referents. When a demonstrative refers to the content of a clause, the clause supplies the antecedent. A benchmark restricted to identity links between mentions of people and objects leaves bridging and links to clause content outside its score.
Coreference versus Entity Linking
This chapter covers coreference within a document. Entity Linking and Knowledge Graph Construction covers how a linker maps mentions or document clusters to nodes in a knowledge base.
They are different questions:
- A coreference resolver decides that "Dr. Alvarez" in sentence 1 and "Alvarez" in sentence 3 are the same person. It does not know, or need to know, whether that person exists in Wikidata.
- An entity linker decides that the resulting entity corresponds to a specific KB node. It relies on the cluster to have enough context, but it also has to handle the case where the document's entity has no KB node at all (an unlinkable mention, or NIL).
Document clusters and knowledge-base assignments can contain independent errors. A linker can assign nodes to individual mentions. Suppose a resolver has grouped mentions of two different people into one cluster. A linker that assigns exactly one node to each input cluster then assigns a single node to both sets of mentions.
Named entity recognition, from Named Entity Recognition, is a third and narrower task: it labels spans with types. Types are useful features for coreference, since "Dr. Alvarez" and "she" agree in type and number while "Dr. Alvarez" and "the reactor" do not. But a type label is not an identity decision: two PERSON mentions can be two different people, and the model must decide. Type agreement can rule out a link, but it cannot establish one. That asymmetry is why NER helps coreference without solving it.
Nonreferential and Degenerate Mentions
Consider what the following expressions denote in context.
- Pleonastic it: "It is raining." There is no entity.
- Existential there: "There are three reasons to worry."
- Generic you: "You can't certify a reactor without a stress test." The pronoun applies to anyone performing the certification. A speaker could say this to a particular person.
- Idiom chunks: "They finally kicked the bucket" does not involve a bucket.
- Mention-versus-word: "The word bank has two senses" mentions a word, not a financial institution.
Linking a pleonastic it to a nearby noun phrase introduces a spurious member into its cluster. Mention detection can prevent that attachment by rejecting the span. In span-ranking systems, this rejection is folded into the mention score: a span that is not a mention should get a low score and be pruned. In pipeline systems, it is a separate classification step, often implemented as a sequence labeler in the style of the BIO tagging we covered in BIO Tagging.
The examples also show why a purely syntactic detector is not enough. "It is raining" and "It surprised the board" have the same pronoun in subject position, but the second can refer to an earlier event or proposition. A detector that keys on the word "it" cannot distinguish them. An encoder can represent the surrounding words at inference time. Training annotations tell a supervised model which contextual patterns to associate with a referential use. The cost of getting this wrong is asymmetric: a missed referential mention loses information, while a spurious nonreferential mention can create a false link and contaminate a cluster.
Split Antecedents
Alvarez met Bhatt at the lab. They reviewed the cooling loop together.
"They" refers to a group that includes Alvarez and Bhatt. An identity partition can give that group its own cluster. Representing the two people as members of the group takes an additional relation, such as a set-valued antecedent. Check whether the annotation supplies that relation before scoring split antecedents. A decoder limited to one identity link per mention needs a richer output representation to encode group membership.
Speaker-Grounded Pronouns
In dialogue, the speaker and addressee of a turn help determine who I and you refer to.
A: I flagged the cooling loop in March. B: I remember. I signed off anyway.
A uses “I” once, and B uses it twice. The identity partition can group B’s two occurrences together and leave A’s occurrence in its own cluster. Turn structure and speaker or addressee information help infer those assignments. When moving from written text to transcripts, check whether the annotation convention changed too. See Dialogue Acts and Conversation Structure.
Mention density can shift with genre. In OntoGUM (Zhu et al., 2021), the conversation slice has 1,027 mentions in 5,701 tokens, compared with 1,803 mentions in 14,094 tokens in the news slice. Compare the two rates before transferring a mention budget calibrated on news.
Singleton Policy
A singleton is a mention with no coreferent partner in the document: an entity that is mentioned exactly once.
Whether singletons count is a corpus policy, and it changes the meaning of every score you compute:
- The OntoNotes coreference data used by CoNLL-2012 omit singleton mentions from the annotations. The shared-task paper reports that most participant systems filtered out predicted singleton clusters.
- Downstream applications usually care a great deal about singletons, because "this mention introduces a new entity" is exactly the decision that prevents an overmerge.
Evaluating only annotated chains gives no credit for recovering omitted singletons. Attaching an unannotated or ambiguous mention changes the response partition and can still hurt a score. Use a dataset with the mention coverage your application needs.
Task Formulations
There are two broad architectures, and they differ in what they score.
The first treats coreference as a pipeline: find the mentions, decide which pairs are coreferent, and assemble the decisions into clusters. The second treats it as a single ranking problem: enumerate spans, score each span as a mention, and score each mention against candidate antecedents. The distinction is partly historical and partly practical. Pipelines are easier to inspect. End-to-end models are easier to optimize as a single system. Neither removes the hard parts, which are candidate generation, ambiguous pronouns, and evaluation.
Mention Detection Then Clustering
The classical pipeline has three stages: detect mentions, score pairs of mentions for coreference, then cluster from those decisions. Soon et al. (2001) used hand-built features such as string match, sentence distance, and gender and number agreement. Aone and Bennett (1995) used grammatical role as a cue in their classifier for anaphor and antecedent pairs. Later variants ranked existing clusters for each active mention (Rahman and Ng, 2009).
The pipeline's weakness is error propagation. A missed mention is gone forever, and a bad pairwise decision is baked into the clustering. Its strength is modularity: you can inspect, evaluate, and replace each stage, and the mention detector's errors are visible rather than hidden inside a joint objective. If the detector misses pronouns, you can measure that. If the pair scorer confuses names, you can measure that too. For an end-to-end model, report mention detection and candidate recall alongside the final clustering metrics to locate errors.
Span Ranking End to End
The modern formulation, introduced by Lee, He, Lewis, and Zettlemoyer (2017), declines to separate detection from resolution. It assigns mention scores to candidate spans, prunes them, and scores antecedents for each retained span. The mention score and the antecedent scores are trained jointly on the coreference objective alone, so the model learns what a mention is in order to link it rather than against a separate detection target.
The single model scored 67.2 average F1 on the English CoNLL-2012 test set in Lee et al. (2017), 1.5 points above the highest previously published result listed in their Table 1 (65.7).
The conceptual move is worth stating plainly. Instead of asking "is this span a mention?" and then "is this pair coreferent?", the model asks "how useful is this span for predicting a coreference link?" A span that looks like a mention but has no plausible antecedent may receive a lower mention score, because the joint objective has no reason to promote it. The mention score is not a separate classifier. It is a learned gate that controls which spans enter the ranking.
Clustering from Pairwise Decisions
Both architectures produce pairwise scores, and something must turn those into clusters. The standard move is:
- For each mention , take the highest-scoring candidate antecedent , where the candidate set also contains a special null antecedent .
- If the winner is , add no antecedent edge. In a graph over supplied mentions, can begin a cluster that later mentions join.
- Otherwise add a link from to .
- Compute connected components over the link graph. Transitivity does the rest.
Local choices can introduce cluster errors. In the first-order decoder, a single link can connect two groups that each contain other mentions.
The mention order defines which earlier spans are eligible. With those sets and their scores fixed, each local argmax is independent of the order in which it is computed. A decoder that scores partial clusters or applies global constraints can select different edges. Connected components use only the selected edges, so an edge with probability 0.51 connects its endpoints in the same way as one with probability 0.99.
Candidate Generation and Search Cost
Let us be concrete about why this task is expensive, because the arithmetic explains most architectural choices in the literature.
A resolver cannot score every possible pair of spans in a long document. The number of spans grows linearly with document length once a maximum width is fixed, but the number of span pairs grows quadratically. That quadratic is the central engineering constraint. Every pruning trick in the literature is a way of avoiding a part of it, and every pruning trick introduces a new way to lose the correct answer before the expensive scorer ever sees it.
Enumerating Spans
Take a document of tokens. Set to the smaller of the proposed positive width cap and . The number of contiguous spans of width at most , before any other restrictions, is
For and this is spans. For it is . The count is linear in document length once is fixed, which is the reassuring part. The width cap excludes any mention longer than tokens. A long outer name can fall outside the cap while a shorter name nested inside it remains a candidate.
A span of width can start at any of positions. Summing over widths gives the total. Wider spans have fewer possible starts, which accounts for the subtraction term. For a fixed cap , doubling a long document roughly doubles the number of spans before pruning.
The Antecedent Search
For exhaustive scoring, order the candidates and allow each mention to consider every earlier one. Each distinct pair supplies one candidate, with the earlier mention as a possible antecedent of the later mention.
With , there are about candidate links. A simple scorer can concatenate two span vectors and their elementwise product. At 1,000 entries per span vector, the concatenated pair feature has 3,000 entries, so materializing the complete pair tensor would store about floats before scoring. Streaming or limiting candidate links avoids materializing that tensor.
When an implementation materializes a feature vector for every pair, the allocation scales with the number of pairs times the feature dimension. That tensor can exceed the size of the encoder activations.
Coarse-to-Fine Pruning
Lee et al. (2017) prune both spans and antecedents. Lee et al. (2018) select antecedents with a cheaper bilinear score before applying the higher-cost scorer. The following fixed budgets illustrate the two-stage design.
- Span pruning. Score the width-limited spans and keep at most for the example. The fixed cap here is 250. Lee et al. (2017) set the cap proportional to document length and also suppress crossing spans.
- Antecedent pruning. For each retained span, run a cheap scorer over preceding spans and keep at most candidate antecedents. Lee et al. (2017) instead use a proximity cap of 250 earlier spans, and Lee et al. (2018) use the learned coarse scorer.
- Fine scoring. Run the expensive scorer only on the surviving pairs.
With retained spans in order, the number of non-null fine scores is at most . A coarse scorer that looks at all retained pairs can still evaluate pairs. At , the maximum number of pairs in either pass is 31,125. With both caps fixed, neither pass grows once the span cap is reached. The number of width-limited spans proposed before pruning still grows as .
The two-stage design is a bet that a cheap scorer can preserve the right candidates often enough for the expensive scorer to do useful work. A long-distance pronoun with a weak lexical match may be pruned by the cheap scorer precisely because the cheap scorer lacks the context that makes the link plausible.
What Pruning Costs You
Pruning is not free, and the cost is not visible in the final number.
For an eligible gold anaphor, measure whether any earlier gold antecedent survives pruning. The resulting candidate recall bounds direct correct-antecedent selection from those candidates. If every gold antecedent is missing, the marginal objective can use as its training target. With a fixed null logit, that loss pushes down the surviving nongold logits.
At inference, pruning can remove every gold antecedent for a mention. An antecedent scorer restricted to those candidates can then choose a wrong earlier link or the null option. Checking candidate recall helps isolate that search error. Error analysis that does not separate the two will spend time tuning the scorer to fix a problem that lives in the candidate generator.
Scoring Mentions and Antecedents
This section follows the span-ranking formulation, because it makes the moving parts explicit.
The model has two kinds of decisions. The mention score decides which spans are worth considering. The pairwise score decides which earlier span, if any, is the antecedent of a given mention. Both are learned, and both are trained through the same final objective. That shared objective is what makes the model end-to-end, and it is also what makes the mention score hard to interpret in isolation.
The Mention Score
Each span gets a vector representation built from the encoder states at its boundaries, the attention-weighted representation of its head word, and a small set of hand features (width, whether it is a pronoun, and so on). For a simplified linear scorer, the mention score is
The raw score ranks spans for pruning. The downstream clustering loss trains it without a separate mention-detection target.
In the original Lee et al. (2017) model, a feed-forward network computes the mention score. Its attention over words in the span supplies a weighted representation of the span's head. The linear formula above illustrates how a vector can be turned into a single ranking score. Boundary states contribute contextual information from the span's first and last positions. The head representation captures what the span is about. Hand features capture properties that are cheap to compute and expensive to learn, such as whether the span is a pronoun or how wide it is. The linear score then combines these signals into a single ranking value.
The Pairwise Score
For a mention and a candidate antecedent , the score combines both spans and their interaction:
where is elementwise multiplication and is concatenation. The elementwise term in this simplified compatibility score can express agreement: "same head word" or "both singular" are conjunctions of features from the two spans.
Without the elementwise term, the model could learn that certain spans are good antecedents and certain spans are good mentions, but it could not easily learn that a particular combination is good. A product term gives the scorer explicit pair interactions. In Lee et al. (2017), the pair network uses the two spans, their elementwise product, and pair features. The complete non-null link score adds the earlier and later spans' two mention scores to that compatibility score.
The Null Antecedent
A mention may have no antecedent, and the model needs a way to say so. The standard trick is to define a special candidate with score
which costs no parameters and acts as the reference point. Then
where is the set of antecedents that survived pruning. Two things follow immediately:
- Retained choices. A normalized probability of 0.7 gives 70 percent of the model's mass to that choice within the retained candidate set plus null. The unnormalized score is a logit.
- The fixed null logit contributes one to a positive normalizer when the other logits are finite. If there are no non-null candidates, as for the first mention, .
The null logit sets a reference level. A candidate with positive logit receives more probability than null in that softmax row. Score differences set probability ratios, so rescaling the logits can change confidence.
Marginal Likelihood over Retained Gold Antecedents
Training does not require the model to pick a specific gold antecedent. Any mention in the same gold cluster that precedes and survived pruning is acceptable. So the loss marginalizes over the gold set:
When earlier gold antecedents survive, contains those antecedents. Under the null-target policy of Lee et al. (2017), it is when none survive or the span has no earlier gold partner to begin with. This also lets the model use null for a proposed span that is not a gold mention.
Either earlier mention from the correct cluster is a valid target for the local decision. Summing their probabilities gives credit to both choices. Other links still determine whether the final partition matches the gold clusters.
When No Gold Antecedent Survives
A mention can genuinely lack an earlier gold antecedent. A different case occurs when earlier gold antecedents exist but pruning removes all of them. With null fallback the latter case uses in the loss and supplies no positive gradient for a gold link.
There are three policies, and they are not equivalent:
- Skip the mention. Exclude from the loss. This is clean but changes the effective training set and silently drops exactly the hard, long-distance cases you care about.
- Use the null target. The inner sum is . When its logit is fixed, only the available non-null logits receive direct gradients from this term. This treatment depends on the pruning policy.
- Force-keep one gold antecedent. Guarantee at least one gold antecedent survives pruning, for example by always retaining the nearest gold antecedent. This keeps the gradient meaningful at the cost of a slightly different candidate distribution at train and test time.
Published implementations pick one of these and document it, and reimplementations sometimes pick a different one without noticing. When two papers report the same architecture with different numbers, this is one of the places to look. Read the code, not the diagram.
Skipping changes which mentions contribute to training. Null fallback lowers the remaining nongold logits relative to the fixed reference. Force-keeping a gold antecedent can create training candidate sets that inference cannot construct.
From Links to Clusters
Transitivity and Error Propagation
Connected components mean the following: if the model links and , then , , and end up in one cluster regardless of whether the model ever considered the pair . This is a feature, since it lets a chain of mentions share one entity, and a hazard, since one bad link fuses two entities permanently. There is no subsequent step that can undo it.
Each mention is a graph node, and each chosen antecedent adds an edge. The resolver takes the connected components as its partition. One spurious edge between components can combine every mention on either side.
Local Scores Are Not Cluster Confidence
The model assigns to candidate within the surviving choices for mention . Cluster correctness is an event about the entire set of mentions.
Consider a chain of nine links, each with local probability 0.6, joining ten mentions:
PythonIn [3]Expand
p_link = 0.6
chain = {n: p_link**n for n in (1, 3, 5, 9)}ConsoleOut [4]Expand
1 link(s): independence-based joint = 0.6 3 link(s): independence-based joint = 0.216 5 link(s): independence-based joint = 0.07776 9 link(s): independence-based joint = 0.01008
If each selected link had correctness probability 0.6 and the correctness events were independent, all nine would be correct with probability . The local model probabilities need separate validation as estimates of correctness. Even correct selected links do not exclude a missing cluster member or an incorrect attachment from elsewhere.
A cluster verifier can use the minimum link score or the product of selected link scores as features. Define its target, such as exact agreement with a reference cluster, and calibrate the resulting probability on held-out examples. Under a model that factorizes antecedent choices given the document, you can also sample one choice per span, including null, then cluster the sampled links. The fraction of samples containing the exact same cluster estimates its probability under that model. Calibration against reference clusters is a separate test.
Changing the pruning budget can change the softmax denominator and therefore the local probability for a pair, even when its logit stays fixed. Report the candidate settings when comparing local probabilities.
Long-Document Coreference
Long documents break the standard formulation in two different places, and mixing them up leads to bad engineering decisions.
A full-document dense attention layer evaluates a quadratic number of token pairs. The resolver's own search is also quadratic when it scores all span pairs. Restricting the resolver's search does not affect the encoder computation.
The Three Costs
Separate them explicitly:
- Encoding cost. Producing contextual representations for tokens. Dense self-attention scores position pairs per head and layer. At , one explicitly stored matrix contains entries, which occupy 0.2 GB at two bytes per entry. Twelve such matrices in one layer occupy 2.4 GB. Retaining the matrices from all 12 layers simultaneously would use 28.8 GB in total for these matrices alone. This is an accounting example. Actual peak memory depends on kernel implementation, tensor lifetime, batching, and other activations.
- Span scoring cost. span scores per document, which is linear in and usually cheap.
- Pair scoring cost. The fine scorer evaluates at most pairs after pruning. A separate coarse pass over all retained spans can still evaluate up to pairs.
A resolver can be bounded while the encoder is not. When someone says "our model handles arbitrarily long documents," ask which of the three costs they are talking about. A bounded entity memory answers only the third. A sliding window bounds encoding and direct local candidate search within each window. A sparse or hierarchical encoder changes the first cost but leaves the candidate search unchanged.
Windowing
One long-document strategy resolves mentions within chunks and then stitches the resulting clusters. A direct local edge requires both mentions in the same window. Overlapping windows can still merge distant mentions into a cluster through a shared mention.
Overlap allows some pairs on opposite sides of a chunk boundary to be scored together. A window of tokens with stride overlaps its neighbor by tokens for . The maximum achievable distance between any two positions in a single window is when the document has tokens and a window starts at position zero. This equals when and when the first window is truncated. For a particular earlier token, the farthest visible later token lies at the end of the latest window that contains that earlier token. Both distance and position relative to the window grid determine visibility.
For this calculation, windows start at and the final windows are truncated at the document end. Count each pair once by its earlier token. For , dividing by the number of distinct pairs gives the probability of joint visibility under a uniform draw.
PythonIn [5]Expand
def jointly_visible_pairs(tokens, width, stride):
"""Count unordered position pairs sharing at least one fixed-grid window."""
if not 1 <= stride <= width:
raise ValueError("Expected stride between 1 and width")
return sum(
min(tokens, (earlier // stride) * stride + width) - earlier - 1
for earlier in range(tokens)
)
def visible_fraction(tokens, width, stride):
if tokens < 2:
raise ValueError("A distinct token pair requires at least two tokens")
return jointly_visible_pairs(tokens, width, stride) / math.comb(tokens, 2)
windowing = pd.DataFrame(
[
{
"window": width,
"stride": stride,
"overlap": width - stride,
"visible_pair_fraction_T10000": round(
visible_fraction(10_000, width, stride), 4
),
}
for width, stride in [(512, 512), (512, 256), (512, 128), (1024, 512)]
]
)| window | stride | overlap | visible_pair_fraction_T10000 | |
|---|---|---|---|---|
| 0 | 512 | 512 | 0 | 0.0505 |
| 1 | 512 | 256 | 256 | 0.0754 |
| 2 | 512 | 128 | 384 | 0.0875 |
| 3 | 1024 | 512 | 512 | 0.1476 |
The table measures a geometric limit of fixed windows under uniform sampling. Real mentions occupy spans and their candidate antecedents have a different distance distribution. On annotated documents, measure the fraction of gold links whose two full spans share a window, broken down by distance. A separate entity memory or cross-window linking step can give access to pairs outside this local search.
Bounded Entity Memory
Toshniwal et al. (2020) first encode the document and propose mention spans. Their bounded models process the proposals left to right and score each against up to active entity slots. A proposal can join an existing cluster, start a new cluster, or be ignored as invalid or because of capacity. When memory is full, admitting a new cluster requires evicting an existing one. For proposals, this takes at most slot comparisons, compared with comparisons for exhaustive span pairing.
At spans and , that is about 64 million slot interactions instead of roughly 500 billion span pairs.
PythonIn [7]Expand
memory_span_width = 10
memory_table = []
for T in (1_000, 10_000, 100_000):
M = memory_span_width * T - memory_span_width * (memory_span_width - 1) // 2
memory_table.append(
{
"tokens": T,
"candidate_spans": M,
"all_pairs": math.comb(M, 2),
"slot_interaction_upper_bound_K64": M * 64,
}
)
memory_table = pd.DataFrame(memory_table)| tokens | candidate_spans | all_pairs | slot_interaction_upper_bound_K64 | |
|---|---|---|---|---|
| 0 | 1000 | 9955 | 49546035 | 637120 |
| 1 | 10000 | 99955 | 4995451035 | 6397120 |
| 2 | 100000 | 999955 | 499954501035 | 63997120 |
A fixed slot budget supports streaming resolution when encoder working memory and input handling also support it.
- Encoder cost. A layer's contextual representations require storage for vectors of width when materialized. Dense self-attention computes quadratically many query-key scores, and storing the full score matrix uses quadratic space. Tiled attention can avoid materializing that matrix.
- It does not guarantee retrieval quality. If the slot holding the correct antecedent was evicted at token 40,000, no scoring function recovers it at token 90,000. Quality depends on the eviction policy, the number of slots, and the training procedure, none of which the bound constrains.
- Entity retention. When the slots fill, the eviction policy determines which entity records remain available for later mentions.
Distance Slices
For a distance diagnostic, group gold anaphors by the distance to their nearest earlier gold cluster mate. State whether distance is measured in tokens or sentences. In each group, report how many anaphors were retained, how many retained anaphors still had any earlier gold candidate, and how often the fine scorer chose a gold link when one was available. Report group sizes and document lengths. These measurements can locate losses a distance curve alone leaves ambiguous.
Evaluation
Evaluation is where coreference punishes casual readers. The three standard metrics measure different things, disagree on the same output, and are usually averaged into a single number that hides the disagreement.
The disagreement is not a bug in the metrics. Each metric encodes a different view of what a coreference partition is for. MUC cares about links between mentions. B-cubed cares about mentions and their local cluster membership. CEAF cares about entities as whole objects. A system that splits an entity and a system that merges two entities can look better or worse depending on which view you adopt.
The Mention Universe
Every metric here is defined over a set of mentions. Gold mentions and system mentions are not the same set. So before you can score anything, you must decide what happens to mentions that appear on only one side.
A supplied-gold setting gives the resolver the reference spans in advance. A predicted-mention setting also measures the effects of missed and extra mentions. Restricting a score to the intersection of detected and gold mentions answers a different question. With unmatched mentions included, the effect depends on the metric. An unmatched singleton adds no direct MUC links, while a missed mention contributes zero to its B³ recall term under the convention below.
The CoNLL-2012 shared task used predicted mentions. Pradhan et al. (2014) later published a reference implementation for scoring predicted partitions. For comparisons, use the scorer and version reported for the benchmark, including its rules for unmatched mentions.
The teaching B³ scorer uses these conventions for unmatched mentions.
- Precision is averaged over response mentions. A response mention with no key partner contributes a precision of zero.
- Recall is averaged over key mentions. A key mention with no response partner contributes a recall of zero.
- An empty response gives precision zero. An empty key gives recall zero. With both sides empty, the scorer returns two zeros and an empty detail table.
Mention-Level Precision and Recall
Before any clustering metric, measure mention detection on its own:
Exact matching requires identical document positions and span endpoints. In the head-based example below, each match pairs two mentions that have the same head token occurrence. “Dr. Alvarez” (0,2) can therefore match “Alvarez” (1,2), because token 1 is the head in both spans. A benchmark can specify its own head-selection and one-to-one alignment rules.
There is also a ceiling effect to keep in mind. If the key excludes singletons, mention recall is measured against a partially annotated target: a system cannot earn credit for recovering a singleton absent from that key. The extra span can reduce precision when the scorer counts it as a false positive.
MUC
MUC (Vilain et al., 1995) is link-based. It asks: of the links the key requires, how many did the response supply, and of the links the response supplies, how many does the key endorse?
Recall, per key entity :
The numerator counts, for each response cluster, the number of links it correctly establishes inside : a cluster containing 3 of 's mentions supplies 2 correct links. Precision is the mirror image, with the roles swapped:
Two properties follow directly from the terms:
- Singleton terms. A size-one cluster contributes zero direct MUC links. Attaching its mention to another cluster can still reduce precision by introducing a link between distinct reference clusters.
- An isolated split. If the key contains one three-mention cluster, splitting it into a pair and a singleton yields recall and precision . In a larger example, the overall precision can change because the split removes a supplied link from the pooled counts.
B-Cubed
B³ (Bagga and Baldwin, 1998) is mention-based. Each response mention contributes a precision term, and each key mention contributes a recall term. The terms use the overlap of the response cluster and the key cluster , treating a missing counterpart as empty.
The corpus precision averages the per-mention precision terms over response mentions. Recall averages the recall terms over reference mentions. Each mention has equal weight in its corresponding mean. A ten-mention cluster therefore contributes ten times the total weight of a singleton cluster.
CEAF
CEAF (Luo, 2005) is entity-based. It aligns key entities with response entities one-to-one, maximizing total similarity, and scores the alignment. The standard similarity for entity-based CEAF is the Dice coefficient:
Let be a one-to-one matching of key and response clusters that maximizes the total similarity . Clusters may be left unmatched.
The denominators sum each side’s self-similarities. For CEAF, every nonempty cluster has Dice self-similarity one, so and count response and key clusters. An unmatched cluster adds no similarity to the numerator. Luo’s mention-based CEAF uses , so its self-similarities sum to mention counts. Identical nonempty partitions score one under either variant. The teaching CEAF helper returns zero on a side with no clusters.
The CoNLL Average
For each language, CoNLL-2012 defined its score as the mean of three F1 values.
To rank closed-track submissions overall, the organizers averaged the English, Chinese, and Arabic scores. A language without a submission contributed zero. If only one component changes, the per-language mean changes by one third of that amount. Different combinations of component scores can yield the same average. Reporting each component makes those differences visible.
A Wrong Attachment and a Wrong Split
Now let us compute. Our running document has six person mentions. The gold annotation puts Alvarez in one cluster and Bhatt in the other, and it decides that "She" in sentence 2 is Bhatt:
PythonIn [9]Expand
# Gold clusters over mention ids. (0,3) = Alvarez; (1,2,4,5) = Bhatt.
GOLD = {0: {0, 3}, 1: {1, 2, 4, 5}}
GOLD_LABELS = {0: "Alvarez", 1: "Bhatt"}Three systems, generated later by code, will produce three different partitions:
- Wrong attachment. "She" moves from Bhatt’s cluster to Alvarez’s cluster. Clusters:
{0,2,3}and{1,4,5}. - Wrong split: "She" is left as a singleton. Clusters:
{0,3},{1,4,5}, and{2}. - Correct:
{0,3}and{1,2,4,5}.
For the wrong attachment, the counts are as follows.
- MUC recall: Alvarez needs 1 link and gets it (2 mentions of the key inside one response cluster). Bhatt needs 3 links and gets 2 (3 of its 4 mentions sit together). So .
- MUC precision: response cluster
{0,2,3}has 2 links, of which 1 is endorsed by the key. Response cluster{1,4,5}has 2 links, both endorsed. So . - B³: mention 2 ("She") sits in a 3-mention cluster with precision and recall . Mentions 0 and 3 have precision and recall . Mentions 1, 4, 5 have precision and recall . Averaging gives precision and recall .
- CEAF: the best alignment is Alvarez→
{0,2,3}with and Bhatt→{1,4,5}with . The sum is , so .
The same attachment yields about 0.83 on CEAF and 0.75 on MUC.
The code below computes all of this, so you can check the arithmetic yourself rather than trusting the prose.
Slices, Singletons, Genres, and Bias
Aggregate scores hide the things that matter most.
- Document length and distance. Report per-bucket. A model can be near-perfect under 100 tokens and near-chance past 1,000.
- Genre. In OntoGUM, pronouns account for 728 of 1,027 mentions in conversation and 340 of 1,803 mentions in news. Report the genre and mention mix alongside each score.
- Annotation differences. Whether singletons are marked, how split antecedents are represented, and whether nominal mentions count all shift the score. Comparisons across corpora are comparisons across conventions.
- Pronoun bias. Zhao et al. (2018) paired Winograd-style sentences with pro- and anti-stereotypical occupation references in WinoBias. Their three baseline systems favored pro-stereotypical resolutions by an average 21.1 F1 points. The combined intervention reduced the gaps for the neural and feature-rich systems. Neither retrained system had a statistically significant gap in the reported test comparisons (Table 3). The feature-rich system still had a significant 1.9-point gap on Type 1 examples in the development set (Table 2).
Bamman, Lewke, and Mansoor (2020) provide a literary coreference benchmark with excerpts from 100 works of English-language fiction.
Worked Example
Before writing code, trace a tiny case completely by hand.
For the hand calculation, tokenize both periods separately. The tokens in Ana met Bo. She left. are Ana(0) met(1) Bo(2) .(3) She(4) left(5) .(6), so .
Step 1. Enumerate spans with . The three widths contribute 7, 6, and 5 spans, for in total.
Step 2: prune to top-3 mentions using a toy mention scorer. Suppose it returns "Ana" 0.91, "Bo" 0.88, "She" 0.85, and assigns everything else below 0.15. The retained spans are the three single-token mentions. The span "Ana met" is gone, so no mention can ever have it as an antecedent.
Step 3: prune antecedents. "Ana" has none. "Bo" has one candidate ("Ana"). "She" has two ("Ana", "Bo").
Step 4: score pairs. Suppose the fine scorer returns and , with by definition. Then
Step 5. Select the highest-scoring option. "She" links to "Ana". For this trace, let the score of linking "Bo" to "Ana" be , so "Bo" selects null at score zero. "Ana" has only the null option.
The figure shows the three probabilities for "She" before the resolver emits a single link.
PythonIn [10]Expand
worked_scores = {"Ana": 1.7, "Bo": 0.4, "null": 0.0}
_denom = sum(math.exp(v) for v in worked_scores.values())
antecedent_labels = list(worked_scores)
antecedent_probs = np.array(
[math.exp(worked_scores[k]) / _denom for k in antecedent_labels]
)VisualizationOut [11]Expand

Step 6. Compute connected components. The only selected edge connects Ana and She. The components are {Ana, She} and {Bo}.
The whole trace is six steps, and each one can break:
- If "Bo" had been pruned in step 2, the resolver could never link to it.
- If the mention scorer had retained "met Bo" instead of "She", no antecedent decision could recover the missing pronoun span.
- The decision in step 5 is greedy. A different threshold could leave "She" as a singleton.
That is the entire task at toy scale, and it scales up without changing shape.
Implementation
The code runs three deterministic linkers on supplied person spans and scores the resulting clusters.
The point of the implementation is not to compete with a neural resolver. It is to make the mechanics visible. Each resolver represents a different source of evidence: string matching, recency, and a learned feature. Each one is simple enough to trace, and the differences between their outputs are large enough to see in a six-mention document.
Document, Tokens, and Offsets
Every span in this chapter is a token span. Character offsets are derived from the token offsets, and checked against the original string, because an off-by-one in offsets silently corrupts every downstream comparison.
PythonIn [12]Expand
DOC = (
"Dr. Alvarez briefed Dr. Bhatt on the reactor design. "
"She had flagged the cooling loop in March. "
"Alvarez asked Bhatt to sign off on the design. "
"Bhatt refused. "
"The regulator approved the design on Friday."
)
TOKENS = [(m.start(), m.end(), m.group()) for m in re.finditer(r"\S+", DOC)]
ABBREV = {"Dr.", "Mr.", "Ms.", "Mrs.", "Prof."}
SENT_OF = []
_sent = 0
for _s, _e, _t in TOKENS:
SENT_OF.append(_sent)
if _t[-1] in ".!?" and _t not in ABBREV:
_sent += 1
# Offset check: every token's character span must reproduce its text.
for _s, _e, _t in TOKENS:
assert DOC[_s:_e] == _t, (_s, _e, _t)
assert len(SENT_OF) == len(TOKENS)The abbreviation set is doing real work: without it, "Dr." would end a sentence and the sentence boundaries would be wrong. That is the same problem we handled properly with statistical models in Sentence Segmentation; here a lookup table is enough.
Mentions and Gold Clusters
PythonIn [13]Expand
def char_span(tok_start, tok_end):
"""Character offsets for a nonempty half-open token span."""
if not 0 <= tok_start < tok_end <= len(TOKENS):
raise ValueError("Expected an in-range, nonempty token span")
return TOKENS[tok_start][0], TOKENS[tok_end - 1][1]
def surface(tok_start, tok_end):
cs, ce = char_span(tok_start, tok_end)
return DOC[cs:ce]
MENTIONS = [
{"id": 0, "start": 0, "end": 2, "kind": "name"},
{"id": 1, "start": 3, "end": 5, "kind": "name"},
{"id": 2, "start": 9, "end": 10, "kind": "pron"},
{"id": 3, "start": 17, "end": 18, "kind": "name"},
{"id": 4, "start": 19, "end": 20, "kind": "name"},
{"id": 5, "start": 26, "end": 27, "kind": "name"},
]
for m in MENTIONS:
m["text"] = surface(m["start"], m["end"])
m["head"] = TOKENS[m["end"] - 1][2].strip(".,").lower()
m["sent"] = SENT_OF[m["start"]]
m["chars"] = char_span(m["start"], m["end"])
assert surface(0, 2) == "Dr. Alvarez"
assert surface(9, 10) == "She"
assert surface(26, 27) == "Bhatt"| id | tokens | text | head | sentence | char_offsets | |
|---|---|---|---|---|---|---|
| 0 | 0 | [0,2) | Dr. Alvarez | alvarez | 0 | 0-11 |
| 1 | 1 | [3,5) | Dr. Bhatt | bhatt | 0 | 20-29 |
| 2 | 2 | [9,10) | She | she | 1 | 53-56 |
| 3 | 3 | [17,18) | Alvarez | alvarez | 2 | 96-103 |
| 4 | 4 | [19,20) | Bhatt | bhatt | 2 | 110-115 |
| 5 | 5 | [26,27) | Bhatt | bhatt | 3 | 143-148 |
The lexical rule uses the last token of the span, lowercases it, and strips leading or trailing periods and commas. This gives the intended head for these names. A phrase such as "the chief engineer at the plant" needs a different head selection. Real systems learn the head or use a dependency parse, as in Dependency Syntax and Universal Dependencies.
A Frozen Rule-Based Resolver
PythonIn [15]Expand
class DSU:
def __init__(self, n):
self.parent = list(range(n))
def find(self, x):
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]]
x = self.parent[x]
return x
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra != rb:
self.parent[rb] = ra
def clusters_from_links(n, links):
dsu = DSU(n)
for a, b in links:
dsu.union(a, b)
groups = {}
for i in range(n):
groups.setdefault(dsu.find(i), set()).add(i)
return {f"C{k}": v for k, v in enumerate(groups.values())}
def head_match_links(mentions):
"""Hard rule: a name links to the most recent earlier name with the same head."""
links = []
for m in mentions:
if m["kind"] != "name":
continue
earlier = [
a
for a in mentions
if a["kind"] == "name"
and a["end"] <= m["start"]
and a["head"] == m["head"]
]
if earlier:
nearest = max(
earlier, key=lambda a: (a["end"], a["start"], a["id"])
)
links.append((nearest["id"], m["id"]))
return linksThe lexical rule links repeated instances of "Bhatt" in this fixture. Shared spelling can also link different people. The rule treats the candidate with the latest end offset as nearest, breaking ties by start offset and then mention ID.
PythonIn [16]Expand
def recency_links(mentions):
"""Head matching, plus: a pronoun links to the nearest preceding mention."""
links = head_match_links(mentions)
for m in mentions:
if m["kind"] != "pron":
continue
preceding = [a for a in mentions if a["end"] <= m["start"]]
if preceding:
nearest = max(
preceding, key=lambda a: (a["end"], a["start"], a["id"])
)
links.append((nearest["id"], m["id"]))
return links
def previous_sentence_first_mention_id(mentions, m):
"""Return the earliest mention ID in the preceding sentence."""
prev = [
a
for a in mentions
if a["end"] <= m["start"] and a["sent"] == m["sent"] - 1
]
if not prev:
return None
return min(prev, key=lambda a: a["start"])["id"]Recency selects Bhatt for the pronoun in sentence 2 because Bhatt is the nearest preceding supplied mention. A closer mention introduced in a subordinate clause can change that choice regardless of its grammatical role.
A Tiny Learned Scorer
Now replace the pronoun heuristic with something learned. The model is deliberately a probe, with a single feature: is the candidate the first mention of the sentence before the pronoun's sentence?
PythonIn [17]Expand
# Six synthetic feature-label pairs with a positive label assigned to every first mention.
# Feature: 1 if the candidate is the previous sentence's first mention, else 0.
TRAIN_X = np.array([[1.0], [1.0], [1.0], [0.0], [0.0], [0.0]])
TRAIN_Y = np.array([1.0, 1.0, 1.0, 0.0, 0.0, 0.0])
w = np.zeros(1)
b = 0.0
LR, L2, STEPS = 0.5, 0.01, 2000
for _ in range(STEPS):
z = TRAIN_X @ w + b
p = 1.0 / (1.0 + np.exp(-z))
grad_w = TRAIN_X.T @ (p - TRAIN_Y) / len(TRAIN_Y) + L2 * w
grad_b = float(np.mean(p - TRAIN_Y))
w -= LR * grad_w
b -= LR * grad_bConsoleOut [18]Expand
weight on previous-sentence first-mention feature: 4.5857 bias: -2.2929
In the source document Dr. Alvarez is mention 0, the first mention of the preceding sentence. Dr. Bhatt is mention 1 and starts later in the same sentence. The feature equals 1 for Dr. Alvarez and 0 for Dr. Bhatt. The fitted weight is about 4.5857 and the bias is about -2.2929, so the resulting logits are about 2.2929 and -2.2929, respectively. The probe therefore chooses Dr. Alvarez for “She.” The synthetic labels encode the first-mention cue by construction.
PythonIn [19]Expand
def learned_linker(mentions):
"""Head matching, plus a learned pronoun linker with no null antecedent."""
links = head_match_links(mentions)
for m in mentions:
if m["kind"] != "pron":
continue
cands = [a for a in mentions if a["end"] <= m["start"]]
if not cands:
continue
first_mention_id = previous_sentence_first_mention_id(mentions, m)
feats = np.array(
[[1.0 if a["id"] == first_mention_id else 0.0] for a in cands]
)
scores = feats @ w + b
best = cands[int(np.argmax(scores))]
links.append((best["id"], m["id"]))
return linksThe probe picks an earlier candidate whenever one exists. Without a null option, the model always takes the highest score among those candidates.
PythonIn [20]Expand
SYSTEMS = {
"Rules only": clusters_from_links(
len(MENTIONS), head_match_links(MENTIONS)
),
"Rules + recency": clusters_from_links(
len(MENTIONS), recency_links(MENTIONS)
),
"Rules + learned": clusters_from_links(
len(MENTIONS), learned_linker(MENTIONS)
),
}
def describe(clusters):
return {
name: sorted(MENTIONS[i]["text"] for i in ids)
for name, ids in clusters.items()
}ConsoleOut [21]Expand
Rules only: C0: ['Alvarez', 'Dr. Alvarez'] C1: ['Bhatt', 'Bhatt', 'Dr. Bhatt'] C2: ['She'] Rules + recency: C0: ['Alvarez', 'Dr. Alvarez'] C1: ['Bhatt', 'Bhatt', 'Dr. Bhatt', 'She'] Rules + learned: C0: ['Alvarez', 'Dr. Alvarez', 'She'] C1: ['Bhatt', 'Bhatt', 'Dr. Bhatt']
The three systems produce distinct partitions of the same six mentions. Head matching leaves “She” as a singleton. Recency reproduces the example’s gold annotation. The learned probe attaches “She” to Dr. Alvarez because the synthetic labels favor the preceding sentence’s first mention.
The positive training examples all contain the same cue. The probe reproduces that pattern on the running example and shares the limitations of its synthetic training data.
What the Failure Costs Downstream
List the cluster IDs present in each sentence. This shows how an attribution step that uses the pronoun’s cluster could assign the flagging event.
PythonIn [22]Expand
def clusters_by_sentence(clusters):
"""List the cluster IDs mentioned in each sentence."""
out = []
for sent in sorted(set(SENT_OF)):
names = sorted(
{
cname
for cname, ids in clusters.items()
if any(MENTIONS[i]["sent"] == sent for i in ids)
}
)
out.append({"sentence": sent, "entities": names})
return pd.DataFrame(out)
sentence_clusters = {
"Gold (rules + recency)": clusters_by_sentence(SYSTEMS["Rules + recency"]),
"Wrong attachment (rules + learned)": clusters_by_sentence(
SYSTEMS["Rules + learned"]
),
}ConsoleOut [23]Expand
Gold (rules + recency)
sentence entities
0 [C0, C1]
1 [C1]
2 [C0, C1]
3 [C1]
4 []
Wrong attachment (rules + learned)
sentence entities
0 [C0, C1]
1 [C0]
2 [C0, C1]
3 [C1]
4 []The tables use zero-based sentence indices, so row 1 corresponds to the second sentence, “She had flagged the cooling loop in March.” The recency partition assigns that sentence’s only person mention to Bhatt’s cluster C1. The learned partition assigns it to Alvarez’s cluster C0. An attribution rule that attaches the flagging event to that cluster would therefore attribute the action to different people. The code only collects the cluster IDs mentioned in each sentence. For a sentence containing multiple clusters, assigning semantic roles requires a separate step.
Scoring the Three Systems
PythonIn [24]Expand
def f1(p, r):
return 0.0 if p + r == 0 else 2 * p * r / (p + r)
def muc_detail(key, resp, side):
num = den = 0
rows = []
if side == "recall":
for kid in sorted(key):
k = key[kid]
matched = sum(
len(k & resp[rid]) - 1 for rid in resp if len(k & resp[rid]) > 1
)
rows.append(
{
"entity": f"key {kid}",
"links_needed": len(k) - 1,
"links_matched": matched,
}
)
num += matched
den += len(k) - 1
else:
for rid in sorted(resp):
r = resp[rid]
matched = sum(
len(r & key[kid]) - 1 for kid in key if len(r & key[kid]) > 1
)
rows.append(
{
"entity": rid,
"links_supplied": len(r) - 1,
"links_endorsed": matched,
}
)
num += matched
den += len(r) - 1
return num, den, pd.DataFrame(rows)
def muc(key, resp):
num_r, den_r, _ = muc_detail(key, resp, "recall")
num_p, den_p, _ = muc_detail(key, resp, "precision")
r = num_r / den_r if den_r else 1.0
p = num_p / den_p if den_p else 1.0
return p, rThe teaching implementation returns 1.0 for a precision or recall denominator of zero. This choice affects the result on documents consisting entirely of singletons. Use the official scorer when reproducing published scores.
PythonIn [25]Expand
def b3(key, resp):
"""Teaching B³ with zero for a mean over an empty mention side."""
key_members = {m: cluster for cluster in key.values() for m in cluster}
response_members = {
m: cluster for cluster in resp.values() for m in cluster
}
rows = []
for m in sorted(response_members):
r = response_members[m]
k = key_members.get(m, set())
rows.append(
{
"mention": m,
"side": "P",
"cluster_size": len(r),
"overlap": len(r & k),
"value": len(r & k) / len(r),
}
)
for m in sorted(key_members):
k = key_members[m]
r = response_members.get(m, set())
rows.append(
{
"mention": m,
"side": "R",
"cluster_size": len(k),
"overlap": len(r & k),
"value": len(r & k) / len(k),
}
)
detail = pd.DataFrame(
rows, columns=["mention", "side", "cluster_size", "overlap", "value"]
)
p = (
float(detail.loc[detail["side"] == "P", "value"].mean())
if response_members
else 0.0
)
r = (
float(detail.loc[detail["side"] == "R", "value"].mean())
if key_members
else 0.0
)
return p, r, detail
def ceaf_e(key, resp):
ks = [key[k] for k in sorted(key)]
rs = [resp[k] for k in sorted(resp)]
n = max(len(ks), len(rs))
pad_k = ks + [set()] * (n - len(ks))
pad_r = rs + [set()] * (n - len(rs))
best, best_perm = -1.0, ()
for perm in permutations(range(n)):
total = 0.0
for i, j in enumerate(perm):
inter = len(pad_k[i] & pad_r[j])
if inter:
total += 2 * inter / (len(pad_k[i]) + len(pad_r[j]))
if total > best:
best, best_perm = total, perm
p = best / len(rs) if rs else 0.0
r = best / len(ks) if ks else 0.0
return p, r, best, best_permThe teaching CEAF helper pads to a square matrix and enumerates its assignments. It returns the first maximizing permutation, including when every overlap is zero. Use an optimal assignment solver for larger partitions.
PythonIn [26]Expand
RESULTS = []
for name, clusters in SYSTEMS.items():
p_muc, r_muc = muc(GOLD, clusters)
p_b3, r_b3, _ = b3(GOLD, clusters)
p_ce, r_ce, _, _ = ceaf_e(GOLD, clusters)
RESULTS.append(
{
"system": name,
"muc_p": p_muc,
"muc_r": r_muc,
"muc_f1": f1(p_muc, r_muc),
"b3_f1": f1(p_b3, r_b3),
"ceaf_f1": f1(p_ce, r_ce),
}
)
RESULTS[-1]["conll_avg"] = (
RESULTS[-1]["muc_f1"] + RESULTS[-1]["b3_f1"] + RESULTS[-1]["ceaf_f1"]
) / 3
system_labels = [r["system"] for r in RESULTS]
mucs = [r["muc_f1"] for r in RESULTS]
b3s = [r["b3_f1"] for r in RESULTS]
ceafs = [r["ceaf_f1"] for r in RESULTS]
averages = [r["conll_avg"] for r in RESULTS]| system | muc_p | muc_r | muc_f1 | b3_f1 | ceaf_f1 | conll_avg | |
|---|---|---|---|---|---|---|---|
| 0 | Rules only | 1.00 | 0.75 | 0.8571 | 0.8571 | 0.7429 | 0.8190 |
| 1 | Rules + recency | 1.00 | 1.00 | 1.0000 | 1.0000 | 1.0000 | 1.0000 |
| 2 | Rules + learned | 0.75 | 0.75 | 0.7500 | 0.7636 | 0.8286 | 0.7807 |
Read the table carefully:
- The reference partition scores 1.0 on each metric.
- Both errors leave MUC recall at . The split supplies only supported links, so MUC precision stays at 1. The wrong attachment supplies an unsupported link, so MUC precision falls to .
- B³ recall is also for both. The split keeps B³ precision at 1. The mixed cluster in the wrong attachment lowers B³ precision to .
- CEAF assigns a greater total matching similarity to the split () than to the wrong attachment (). The split adds a response cluster. In this fixture the larger denominator yields lower F1 for the split ( versus ).
- The gains on MUC and B³ outweigh the loss on CEAF, so the split has the higher average in this fixture.
The split leaves the flagger and the refuser unconnected. The wrong attachment can cause a downstream system to credit Alvarez with Bhatt’s action. The consequences depend on how that system uses the clusters.
Checking the Arithmetic
For the wrong attachment, the printout gives per-cluster MUC counts, per-mention B³ terms, and the optimal CEAF assignment and total similarity.
PythonIn [28]Expand
wrong_attachment = SYSTEMS["Rules + learned"]
num_r, den_r, muc_recall_rows = muc_detail(GOLD, wrong_attachment, "recall")
num_p, den_p, muc_prec_rows = muc_detail(GOLD, wrong_attachment, "precision")
p_muc, r_muc = muc(GOLD, wrong_attachment)
p_b3, r_b3, b3_rows = b3(GOLD, wrong_attachment)
p_ce, r_ce, ceaf_sum, ceaf_perm = ceaf_e(GOLD, wrong_attachment)ConsoleOut [29]Expand
MUC recall : 3/4 → 0.7500
entity links_needed links_matched
key 0 1 1
key 1 3 2
MUC precision: 3/4 → 0.7500
entity links_supplied links_endorsed
C0 2 1
C1 2 2
B-cubed: P=0.7778 R=0.7500
mention side cluster_size overlap value
0 P 3 2 0.666667
1 P 3 3 1.000000
2 P 3 1 0.333333
3 P 3 2 0.666667
4 P 3 3 1.000000
5 P 3 3 1.000000
0 R 2 2 1.000000
1 R 4 3 0.750000
2 R 4 1 0.250000
3 R 2 2 1.000000
4 R 4 3 0.750000
5 R 4 3 0.750000
CEAF_e: sum(phi)=1.6571 alignment=(0, 1)
P=0.8286 R=0.8286The printed counts reproduce the hand calculation for the wrong attachment above.
VisualizationOut [30]Expand

Mention-Level Precision and Recall
Clustering metrics assume the mention set is roughly right. Measure that separately.
PythonIn [31]Expand
GOLD_MENTION_SET = {(m["start"], m["end"]) for m in MENTIONS}
def mention_pr(gold, pred):
tp = len(gold & pred)
p = tp / len(pred) if pred else 0.0
r = tp / len(gold) if gold else 0.0
return p, r
mention_cases = {
"exact spans": GOLD_MENTION_SET,
"missed pronoun": GOLD_MENTION_SET - {(9, 10)},
"extra nominal mention": GOLD_MENTION_SET | {(31, 33)},
}
mention_table = pd.DataFrame(
[
{
"case": name,
"precision": round(mention_pr(GOLD_MENTION_SET, pred)[0], 4),
"recall": round(mention_pr(GOLD_MENTION_SET, pred)[1], 4),
}
for name, pred in mention_cases.items()
]
)ConsoleOut [32]Expand
case precision recall
exact spans 1.0000 1.0000
missed pronoun 1.0000 0.8333
extra nominal mention 0.8571 1.0000
The extra span for 'extra nominal mention' is:
'the design'The reference contains only person mentions in this fixture. Adding the design gives six exact matches out of seven predicted spans, for precision and recall 1. Removing the pronoun gives precision 1 and recall .
Boundary conventions matter too. Suppose the key contains Dr. Alvarez at (0,2) and the system proposes Alvarez at (1,2):
PythonIn [33]Expand
def head_match_pr(gold, pred):
"""One-to-one final-token matching of nonempty spans in one document."""
gold_heads = Counter(end - 1 for _, end in gold)
pred_heads = Counter(end - 1 for _, end in pred)
matches = sum((gold_heads & pred_heads).values())
precision = matches / len(pred) if pred else 0.0
recall = matches / len(gold) if gold else 0.0
return precision, recall
gold_one, pred_one = {(0, 2)}, {(1, 2)}
exact_one = mention_pr(gold_one, pred_one)
head_one = head_match_pr(gold_one, pred_one)ConsoleOut [34]Expand
exact match : P=0.00 R=0.00 head match : P=1.00 R=1.00
Both spans share the head token at index 1. Counting matching head occurrences with multiplicity lets each mention match at most once, even when several spans share a head. A corpus scorer also needs document IDs, and a clustering metric needs a defined alignment when more than one pairing is possible.
The Cost of the Search
PythonIn [35]Expand
W = 10
M_MAX = 250
K_ANT = 250
def span_count(T, width=W):
effective_width = np.minimum(T, width)
return effective_width * T - effective_width * (effective_width - 1) // 2
def candidate_pair_bound(mentions, antecedent_cap):
return sum(min(index, antecedent_cap) for index in range(mentions))
cost_rows = []
for T in (35, 1_000, 10_000, 100_000):
M = int(span_count(T))
candidate_pairs = math.comb(M, 2)
fine_bound = candidate_pair_bound(min(M, M_MAX), K_ANT)
cost_rows.append(
{
"tokens": T,
"spans_W10": int(M),
"unpruned_pairs": candidate_pairs,
"fine_pair_bound": fine_bound,
"pair_count_ratio": round(candidate_pairs / fine_bound, 1),
"attention_entries_T2": T * T,
}
)
cost_table = pd.DataFrame(cost_rows)
Ts = np.unique(np.rint(np.logspace(2, 5, 60)).astype(int))
span_grid = span_count(Ts)
pair_curve = span_grid * (span_grid - 1) // 2
pruned_budget = candidate_pair_bound(M_MAX, K_ANT)ConsoleOut [36]Expand
tokens spans_W10 unpruned_pairs fine_pair_bound pair_count_ratio attention_entries_T2
35 305 46360 31125 1.5 1225
1000 9955 49546035 31125 1591.8 1000000
10000 99955 4995451035 31125 160496.4 100000000
100000 999955 499954501035 31125 16062795.2 10000000000At 100,000 tokens, width 10 gives about 500 billion possible span pairs. After keeping at most 250 spans, the fine scorer has at most 31,125 pairs, about 16 million times fewer. Encoder time, cheap scores, and top-candidate selection still contribute to runtime.
VisualizationOut [37]Expand

Local Scores versus Cluster Confidence
PythonIn [38]Expand
confidence = pd.DataFrame(
[
{"links": n, "min_edge": p_link, "independent_product": product}
for n, product in chain.items()
]
)ConsoleOut [39]Expand
links min_edge independent_product
1 0.60000 0.60000
3 0.60000 0.21600
5 0.60000 0.07776
9 0.60000 0.01008The table and figure use the same chain of nine links across ten mentions. Each link has value 0.6, so the minimum remains 0.6 while the product falls to about 0.0101. A reliability assessment would compare predicted cluster probabilities with observed correctness on held-out clusters.
PythonIn [40]Expand
conf_links = confidence["links"].to_numpy()
conf_product = confidence["independent_product"].to_numpy()
conf_min_edge = confidence["min_edge"].to_numpy()VisualizationOut [41]Expand

Limitations and Impact
The gold annotation in our running example picks one possible referent. Cluster metrics measure agreement with that choice. A defensible alternative interpretation can therefore lower the score. The OntoNotes authors describe double annotation and adjudication for coreference. In their analysis of annotator disagreements, the CoNLL-2012 organizers identify pronouns with unclear antecedents as examples of genuine ambiguity.
An entity partition can group textual mentions of the same referent. Representing related entities through bridging or plural references to several individual antecedents requires additional structure. Event mentions can form clusters when they refer to the same event. Quoted pronouns can share a cluster with explicit mentions of their speaker, and speaker IDs can supply context for resolving them.
The metrics weight errors differently. In our six-mention example, MUC and B-cubed preferred leaving the pronoun unlinked, while entity-based CEAF preferred the incorrect attachment. Lee et al. (2017) report 67.2 average F1 on the English CoNLL-2012 test set. To evaluate how the resulting clusters affect an application, measure the application's decisions on its own data. To compare coreference systems, use a fixed scorer and mention convention and report the distribution of genres and document lengths.
WinoBias exposes a gap for the occupations and sentence templates in its paired evaluation. A corpus-wide score can hide that gap because it pools cases across conditions. For an application that resolves pronouns about people, evaluate matched examples from the settings that matter to the application and report performance by condition.
Applications that use explicit clusters can combine facts across sentences, deduplicate referents in summaries, or gather evidence about a queried entity. Clusters can also provide inputs for Entity Linking and Knowledge Graph Construction. A wrong attachment can assign an action to the wrong party. A split can leave evidence about one party in disconnected groups. Measure each error against the downstream decision.
Practically, that asymmetry suggests a design principle that the benchmark does not encode: tune for precision on merges when the downstream use is attributional, and accept more singletons. Enforce type and number constraints as hard filters where the annotation supports it. Check the mention universe before you compare numbers. Among gold mentions with at least one earlier gold cluster mate, log the fraction with any earlier gold antecedent surviving the search. Report mention-proposal losses separately. Report by distance and by document length. And when you consume a cluster downstream, carry an explicit confidence computed for the cluster, not the local link probability that happened to build it.
A language model can produce coreference judgments in text. An evaluation must define how the output maps to mention boundaries and entity clusters. Keep the prompt, decoding settings, parser and scorer fixed when comparing systems.
Further Reading
- Lee, He, Lewis, and Zettlemoyer (2017). End-to-end Neural Coreference Resolution. EMNLP. https://aclanthology.org/D17-1018/
- Lee, He, and Zettlemoyer (2018). Higher-Order Coreference Resolution with Coarse-to-Fine Inference. NAACL. https://aclanthology.org/N18-2108/
- Pradhan et al. (2012). CoNLL-2012 Shared Task: Modeling Unrestricted Coreference in OntoNotes. https://aclanthology.org/W12-4501/
- Pradhan, Luo, Recasens, Hovy, Ng, and Strube (2014). Scoring Coreference Partitions of Predicted Mentions: A Reference Implementation. ACL. https://aclanthology.org/P14-2006/
- Luo (2005). On Coreference Resolution Performance Metrics. HLT/EMNLP. https://aclanthology.org/H05-1004/
- Toshniwal et al. (2020). Learning to Ignore: Long Document Coreference with Bounded Memory Neural Networks. EMNLP. https://aclanthology.org/2020.emnlp-main.685/
- Bamman, Lewke, and Mansoor (2020). An Annotated Dataset of Coreference in English Literature. LREC. https://aclanthology.org/2020.lrec-1.6/
- Xia, Sedoc, and Van Durme (2020). Incremental Neural Coreference Resolution in Constant Memory. EMNLP. https://aclanthology.org/2020.emnlp-main.695/
- Zhao, Wang, Yatskar, Ordonez, and Chang (2018). Gender Bias in Coreference Resolution: Evaluation and Debiasing Methods. NAACL. https://aclanthology.org/N18-2003/
- Zhu, Pradhan, and Zeldes (2021). OntoGUM: Evaluating Contextualized SOTA Coreference Resolution on 12 More Genres. ACL-IJCNLP. https://aclanthology.org/2021.acl-short.59/
- Rösiger, Riester, and Kuhn (2018). Bridging resolution: Task definition, corpus resources and rule-based experiments. COLING. https://aclanthology.org/C18-1298/
- Soon, Ng, and Lim (2001). A Machine Learning Approach to Coreference Resolution of Noun Phrases. Computational Linguistics. https://aclanthology.org/J01-4004/
- Aone and Bennett (1995). Evaluating Automated and Manual Acquisition of Anaphora Resolution Strategies. ACL. https://aclanthology.org/P95-1017/
- Rahman and Ng (2009). Supervised Models for Coreference Resolution. EMNLP. https://aclanthology.org/D09-1101/
- Weischedel et al. OntoNotes: A Large Training Corpus for Enhanced Processing. See §6, Coreference. https://www.cs.cmu.edu/~./hovy/papers/09OntoNotes-GALEbook.pdf
Summary
Coreference resolution groups mentions into clusters that represent shared identity.
- Scope. An identity partition can group mentions of the same person, speaker, or event. Bridging and links from groups to their members need additional relations.
- Search. At fixed width , the number of candidate spans grows linearly in document length. Testing every pair of spans takes comparisons. With fixed span and antecedent caps, fine scoring has a fixed maximum. Candidate recall indicates how often the caps leave a possible gold link.
- Scoring. A mention score decides what counts as a mention. A pairwise score combines two span representations and their elementwise product. The null antecedent has score zero and participates in the same softmax as the retained links.
- Training. The loss marginalizes over all retained gold antecedents, so any correct link is rewarded. When pruning removes every gold antecedent, the implementation must choose a fallback, and the choice changes what the model learns.
- Clustering. Greedy antecedent selection plus connected components gives clusters. Transitivity propagates a single bad link across an entire entity, and no later step can undo it.
- Confidence. The local softmax distributes probability across each mention’s retained antecedents and null. Calibrated confidence in a final cluster requires evidence about cluster correctness.
- Long documents. Separate encoder cost, span cost, and pair cost. Windowing bounds what can be jointly visible. Bounded entity memory bounds the resolution state, not the encoder and not retrieval quality.
- Evaluation. MUC counts links. B³ gives each mention equal weight. CEAF matches entities and normalizes by the chosen self-similarity totals. In the six-mention example, two metrics favor the split while CEAF favors the wrong attachment.
- Conventions. The mention universe, the singleton policy, the span matcher, and the CEAF normalization all change the number. State them, and use the published reference implementation when comparing to published results.
The next chapter turns from who is mentioned to how the clauses about them connect, which is where discourse relations pick up what coreference leaves unresolved.
Quiz
Ready to test your understanding? Take this quick quiz to reinforce what you've learned about coreference resolution.
Coreference Resolution
Join the discussionAsk a question or share what you learned.
Keep exploring
Reference
Citation details
Cite or share this article.


Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!