Coreference Resolution › Implementation
Language AI HandbookAll chapters 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

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!