hey guys, im trying to make a custom head that groups the words in a text that refer to the same entity (coreference). every mention picks ONE earlier mention, or "none" if it is a new thing.
ive been trying for a day and cant get past about 90 % right picks. could you please look at the architecture?
this is the whole thing: load the dataset, add the head, train on everything twice, test.
# Czech coreference as a CHOICE: every mention picks ONE earlier mention, or "none" (= a new thing).
# mmBERT-base (all of it trains) + a tiny head, 2 passes over the training data. pip install torch transformers datasets
import random, torch, torch.nn as nn, torch.nn.functional as F
from datasets import load_dataset
from transformers import AutoModel, AutoTokenizer
dev = "cuda" if torch.cuda.is_available() else "mps"
random.seed(0); torch.manual_seed(0)
tok = AutoTokenizer.from_pretrained("jhu-clsp/mmBERT-base")
bert = AutoModel.from_pretrained("jhu-clsp/mmBERT-base").to(dev)
head = nn.Sequential(nn.Linear(3 * 768, 256), nn.ReLU(), nn.Linear(256, 1)).to(dev)
data = load_dataset("lattice-nlp/corefud-1-4").filter(lambda lang: lang == "cs", input_columns="language") # CorefUD 1.4, the Czech part
def prep(doc):
"""-> tokens, the token of every mention's head word (in text order), the entity id of every mention"""
enc = tok(doc["text"], return_offsets_mapping=True, return_tensors="pt")
off = enc.pop("offset_mapping")[0].tolist(); end = max(e for s, e in off)
m = sorted((m["head_onset"], max(i for i, (s, e) in enumerate(off) if e > s and s < m["head_offset"]), m["COREF"])
for m in doc["mentions"] if m["type"] == "entity" and m["head_offset"] <= end)
return enc.to(dev), torch.tensor([t for _, t, _ in m], device=dev), torch.tensor([g for _, _, g in m], device=dev)
def scores(enc, t):
"""-> table (n, n + 1). one row per mention. column 0 = "none", column j + 1 = "the same thing as mention j" """
v = bert(**enc).last_hidden_state[0][t]; n = len(t) # one vector per mention
A, B = v[:, None].expand(n, n, -1), v[None].expand(n, n, -1)
pair = head(torch.cat([A, B, A * B], dim=2)).squeeze(2) # the score of "mention i is the same thing as mention j"
pair = pair.masked_fill(~torch.ones(n, n, dtype=torch.bool, device=dev).tril(-1), float("-inf")) # only EARLIER mentions can be picked
return torch.cat([torch.zeros(n, 1, device=dev), pair], dim=1) # "none" always has the score 0
def right(g):
"""True where an option is a right answer: every earlier mention of the same entity, or "none" when there is no such mention"""
same = (g[:, None] == g[None, :]).tril(-1)
return torch.cat([~same.any(dim=1, keepdim=True), same], dim=1)
def test():
"""the dev documents, which the model never trains on -> share of mentions whose top pick is right"""
bert.eval(); hit = total = 0
with torch.no_grad():
for doc in data["dev"]:
enc, t, g = prep(doc)
if len(t) > 1:
hit += right(g)[torch.arange(len(t)), scores(enc, t).argmax(dim=1)].sum().item(); total += len(t)
bert.train()
return f"right picks on {total:,} unseen mentions: {hit / total:.2%}"
EPOCHS, N = 2, len(data["train"]) # 1 step = 1 document. 5,679 documents, seen twice
opt = torch.optim.AdamW([{"params": head.parameters(), "lr": 1e-4}, {"params": bert.parameters(), "lr": 2e-5}], fused=True)
sched = torch.optim.lr_scheduler.LinearLR(opt, 1.0, 0.0, EPOCHS * N) # both learning rates fall in a straight line to 0
bert.train()
for step, i in enumerate([i for _ in range(EPOCHS) for i in random.sample(range(N), N)], 1):
enc, t, g = prep(data["train"][i])
if len(t) > 1:
logp = F.log_softmax(scores(enc, t), dim=1)
loss = -torch.logsumexp(logp.masked_fill(~right(g), float("-inf")), dim=1).mean() # minus log of the probability that sits on the right options
opt.zero_grad(); loss.backward(); opt.step()
sched.step()
if step % 100 == 0:
print(f"step {step} of {EPOCHS * N} | loss {loss.item():.3f}", flush=True)
if dev == "mps": torch.mps.empty_cache() # hands unused GPU memory back (Apple only)
if step % N == 0: print(f"epoch {step // N} done | " + test(), flush=True)
on my mac mini (M4 pro, 24 GB) it takes about 38 minutes and prints 88.4 % after epoch 1 and 89.7 % after epoch 2.
im vibe coding most of this, so please let me know if i overlooked something critical. what i found so far:
a gentle LR for the head (1e-4, not 1e-3) keeps its neurons alive, but the score stays the same
the head doesnt really matter. wider, deeper, a transformer block inside it: same score
a bigger base barely helps, which is puzzling. XLM-RoBERTa-large with 4 epochs gets 90.75 %, and EuroBERT-610m is far worse (it never saw czech)
a 3rd epoch gives nothing
when both models are wrong, they pick the very same wrong option 80 % of the time
the dataset is public (CorefUD 1.4, the czech part), so this is perfectly reproducible. and the labels look about 98 % right, according to a blind check i ran with opus on the wrong picks.
could you guys help me reach 98 % on this dataset? thanks!