How I Fine-Tuned Laya to Solve an Important Problem in Scientometrics — With Claude Code
From the publisher’s feed, collected in the ZeroLabs newsroom.
Step-by-step instructions for fine-tuning ConvAI’s 33ms “System 1” decision model on your own yes/no task, plus what happened when I pointed it at Institution Name Disambiguation and got 99.2% accuracy across 163 countries.I’ve spent the last year working on a problem almost nobody outside bibliometrics has heard of: Institution Name Disambiguation (IND). A paper lists its affiliation as free text “IIT Delhi,” “IITD,” “Indian Institute of Technology Delhi,” “Dept. of CSE, IIT, Delhi, India.” Four strings, one institution. Multiply that across tens of millions of papers and every country’s naming conventions, and any serious institution-level analysis retraction rates by university, research output by country, get quietly unreliable at the source.I’ve worked on this alongside Dr. Achal Agrawal, founder of IRW, since we started building PostPub, a platform for analyzing retraction data at scale. We published an early piece of this as a preprint, Institute Disambiguation using Author-Institution Co-Occurrence (Agrawal & Mukherjee, arXiv:2510.16407), an unsupervised clustering approach using author-affiliation co-occurrence instead of string matching. It worked, but like any clustering method it was fragile to small token differences and needed a full co-occurrence graph to do anything; it couldn’t just look at two strings in isolation and answer yes or no.The end goal, using Crossref’s Retraction Watch dataset, has always been: take a raw affiliation string, hand it to a model, and get back a clean canonical name. An LLM was the obvious candidate, and the obvious problem, expensive at scale and not accurate enough for zero-shot to trust for research-integrity analysis.Then I found Laya, an open-weight “System 1” decision model built for fast, calibrated yes/no and multiple-choice judgments instead of free-text generation. IND, reframed correctly, isn’t a generation problem; it’s a pairwise judgment: do these two strings name the same institution, yes or no. Exactly the shape of a question a System 1 model answers in milliseconds.So I fine-tuned it. Full fine-tune, on Kaggle’s free GPU tier and got 99.2% accuracy on a held-out test set spanning 17,500+ training pairs across 163+ countries, beating every baseline I could throw at it, for a training cost of basically zero.This article has two jobs: walk through, in enough detail to reproduce, how to fine-tune Laya, data format, training loop, Kaggle setup, the gotchas I hit and show what came out when I pointed that process at a real, previously unsolved problem. IND is the worked example; nothing below is specific to institution matching, so swap in your own noul, choice, or score task.Why this is harder than it soundsInstitution name disambiguation is considered an open problem in scientometrics for a reason, and it isn’t string similarity. The actual hard cases look like this:Same institution, zero shared vocabulary. “NIT Trichy” and “National Institute of Technology, Tiruchirappalli” name the same place. “Trichy” is a colloquial short form of “Tiruchirappalli”; they don’t share a single letter as strings. No similarity metric gets this right without real-world knowledge.Different institutions, nearly identical structure. Two different universities’ “Department of Computer Science” pages look structurally identical. Token overlap is high; the entities are completely different.No open benchmark. Unlike author name disambiguation (which has datasets like WhoIsWho), there is no standard, widely-adopted open dataset for institution name disambiguation specifically. Every group working on this problem is, to some extent, building and labelling its own data.That last point mattered a lot for how this project had to be scoped.The dataWe built a labelled dataset by running the full pool of raw affiliation strings from our retraction dataset through an institution resolution API from Dimension, a commercial service capable of mapping free-text affiliation strings to a canonical institution identifier and country. We’re treating its output as ground truth for this work, for a simple reason: to our knowledge, no open, manually-verified dataset exists for this exact task, and a commercial resolution engine trained on a far larger corpus than we could label by hand is the closest practical approximation available right now. And of course, a special thanks to Dimension for making this happen.That gave us:96,953 unique, resolved raw affiliation strings10,757 unique canonical institutions163 countriesFrom that pool, we built a leakage-free, institution-level split, where every institution (and every raw string belonging to it) is locked into exactly one of train, validation, or test, verified programmatically before any training happened. No institution’s name variants leak across splits; no exact pair repeats across splits.We’re not able to release this dataset publicly yet; it sits under security and compliance constraints we need to clear first. Once we do, we intend to release it. We’re also building a manually verified subset right now, specifically to sanity-check the resolution API labels against human judgment, since “ground truth” from any single automated source deserves a second opinion before anyone treats it as gospel.Reframing the problemLaya evaluates typed questions over a piece of state in a single forward pass, using three primitives: choice (pick one of several options), score (place something on an ordinal scale), and noul (a direct yes/no question returning a calibrated probability).Laya’s own documentation is explicit that its choice . The primitive degrades badly past roughly 20 candidate options. Institution matching against a registry the size of ROR (~110,000 organisations) is therefore not a fit for that mode at all; you cannot enumerate every institution in the world as a multiple-choice list.The fix is to not treat it as classification against a huge candidate set in the first place. Reframed as pairwise verification, “Do these two strings name the same institution?”, it becomes a single noul question, and the full registry never enters the picture. This is the same reframing that made the whole approach tractable.state = { "name_a": "IIT Delhi", "name_b": "Indian Institute of Technology Delhi",}question = { "same_institution": { "type": "noul", "instructions": "Do name_a and name_b refer to the same real-world institution?", }}How to fine-tune Laya, step by stepLet’s decode the entire fine-tune strategy step by step.1. Set up the environmentLaya’s own reference fine-tune recipe targets Kaggle’s free GPU tier, and that’s what I used end-to-end, no paid compute anywhere in this project. In a new Kaggle notebook:Notebook options → Accelerator: GPU T4 ×2 (the training script auto-detects GPU count and falls back to a single GPU or CPU gracefully, but 2×T4 is what the official recipe is tuned for)Notebook options → Internet: On (needed to pull the base checkpoint from Hugging Face)pip install -q -U "laya>=0.3.3" "transformers>=4.48.0" safetensors huggingface_hub pandas2. Shape your data as pairsLaya doesn’t care what your task is; it cares that you give it a state (any dict of strings), a question (typed choice / score / noul), and, for training, a target. For a noul task like this one, every row is just two strings and a label:import pandas as pddf = pd.read_csv("train.csv") # columns: name_a, name_b, label (0 or 1)The one rule that matters more than any hyperparameter: split by entity, not by row. If any variant of “IIT Delhi” appears in your training set, no variant of “IIT Delhi” can appear in validation or test; your eval numbers are measuring memorisation, not generalisation. I built this as a stratified split by canonical entity (bucketed by how many string variants each entity has, so val/test aren’t starved of positive-pair material), then asserted zero overlap in entities, raw strings, and exact pairs across all three splits before touching the GPU.3. Turn pairs into tokenized training itemsimport json, osfrom transformers import AutoTokenizerfrom huggingface_hub import snapshot_downloadfrom laya.agent import _fix_tokenizer_configfrom laya.common import build_sequence, QTYPESMODEL_ID = "convaiinnovations/laya"model_dir = snapshot_download(MODEL_ID)_fix_tokenizer_config(model_dir)tok = AutoTokenizer.from_pretrained(os.path.join(model_dir, "tokenizer"))with open(os.path.join(model_dir, "rl_agent_config.json")) as f: cfg = json.load(f)INSTRUCTIONS = "Do name_a and name_b refer to the same real-world entity?"LABEL_SMOOTH = 0.05 # avoid exact 0/1 targetsdef build_item(name_a, name_b, label): state = {"name_a": name_a, "name_b": name_b} q = {"t": "noul", "ins": INSTRUCTIONS, "crit": {}} seq, markers = build_sequence(tok, state, q, cfg["max_len"], cfg["head_max_len"]) target = [1 - LABEL_SMOOTH, LABEL_SMOOTH] if label == 0 else [LABEL_SMOOTH, 1 - LABEL_SMOOTH] return {"ids": seq, "markers": markers, "qtype": QTYPES["noul"], "target": target, "label": int(label)}train_items = [build_item(a, b, y) for a, b, y in zip(df.name_a, df.name_b, df.label)]4. Write the training loopThis is a full fine-tune every parameter updates, nothing frozen, using Laya’s own published recipe: an RLCD/GRPO-style policy-gradient objective plus soft cross-entropy guidance, with discriminative learning rates (the pretrained encoder moves gently; the decision head moves faster).from laya.common import build_model, proper_rewardfrom safetensors.torch import load_fileimport torchmodel = build_model(cfg, encoder_dir=os.path.join(model_dir, "encoder"))model.load_state_dict(load_file(os.path.join(model_dir, "model.safetensors")), strict=True)model.to(device).train()enc_params = [p for n, p in model.named_parameters() if "encoder." in n]head_params = [p for n, p in model.named_parameters() if "encoder." not in n]optimizer = torch.optim.AdamW([ {"params": enc_params, "lr": 2.5e-5}, # pretrained language understanding: move gently {"params": head_params, "lr": 1.0e-4}, # task-specific decision layer: move fast], weight_decay=0.01)GROUP_SIZE, SIGMA = 4, 0.25for epoch in range(EPOCHS): for batch in dataloader(train_items, batch_size=8): logits, _ = model(batch["input_ids"], batch["attention_mask"], batch["marker_pos"], batch["marker_mask"], batch["qtype"]) mask, target = batch["marker_mask"], batch["target"] # sample a few perturbed guesses around the current logits eps = torch.randn((GROUP_SIZE,) + logits.shape, device=device) * SIGMA * mask z = logits.detach().unsqueeze(0) + eps q = torch.softmax(z.masked_fill(~mask, -1e4), -1) # reward each guess against the true label, advantage = how much better than average r = proper_reward(q, target.unsqueeze(0), batch["qtype"], mask, w_sph=0.75, w_rps=1.0) advantage = (r - r.mean(0, keepdim=True)) logp = -(((z - logits.unsqueeze(0)) ** 2) * mask).sum(-1) / (2 * SIGMA ** 2) loss_rl = -(advantage * logp).mean() loss_ce = -(target * torch.log_softmax(logits.masked_fill(~mask, -1e4), -1)).sum(-1).mean() loss = loss_rl + loss_ce loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) optimizer.step() optimizer.zero_grad()In plain terms: instead of just being told “the answer is 1, minimize distance to it,” the model samples several slightly-perturbed guesses each step, gets rewarded for the ones that score better against the true label, and is nudged toward those trial-and-error rather than being handed the answer key directly. It’s also why the output is a genuinely calibrated probability rather than an overconfident classifier score.5. Launch it across both GPUstorchrun --standalone --nproc_per_node=2 train_ddp.py torchrun handles the DDP wiring; the script above just needs to read RANK / WORLD_SIZE from the environment and shard train_items across ranks (train_items[rank::world_size]). If only one GPU is visible, drop --nproc_per_node to 1 . The training loop itself doesn't change.6. Calibrate, then saveAfter the epoch loop, fit a temperature scalar on your held-out validation set (never trained on) so the model’s output probabilities are actually trustworthy, not just directionally right:from laya.common import fit_one_temp # fits one scalar per question typefitted_temp = fit_one_temp(val_logits_and_targets)model_config["temperature"] = fitted_tempsave_model(model, output_dir)7. Load it back and use itimport layaagent = laya.load(output_dir, device="cuda") # or "mps" on Apple Silicon, "cpu" otherwisequestion = {"same_institution": {"type": "noul", "instructions": INSTRUCTIONS}}result = agent.predict({"name_a": "IIT Delhi", "name_b": "Indian Institute of Technology Delhi"}, question)print(result["answers"]["same_institution"]["noul"]) # -> 0.901Total training time: 3,095 seconds, 51.6 minutes for all 4 epochs, on free infrastructure.Validation accuracy was already at 99.07% after a single epoch and essentially flat from there; 4 epochs were already more than enough. If you’re working with a smaller dataset than the 17,500 pairs I used, don’t assume more epochs automatically helps: watch the validation curve and stop when it plateaus, not when you run out of patience.ResultsOn the held-out test set 3,750 pairs, 1,415 institutions never seen during training or validation:Precision stayed extremely high throughout the model very rarely claims two different institutions are the same. Almost all of the error comes from the 21 false negatives: missed matches, not false alarms.Accuracy holds at or above 97% for every country with a meaningful sample size. China, the largest single slice at 1,318 test pairs, comes in at 99.2%; no single region is propping up the global average.The errors that remain all share one signature: near-zero lexical overlap between two strings naming the same place, a colloquial short form, or a sub-lab name with no textual relationship to its parent institution’s name. That’s a real-world-knowledge gap, not a training failure, and it’s the same category of error you’d expect from any system that has to infer identity from text alone.Benchmarking against everything else I could get my hands onA result in isolation doesn’t mean much, so I benchmarked the fine-tuned model against four other approaches, all on the exact same 129-pair held-out test set, with zero overlap with anything used in training:A sentence-embedding cosine-similarity baseline (all-MiniLM-L6-v2) → a standard, widely-used DL approach to entity matching.RapidFuzz token-sort-ratio → a strong classical string-similarity baseline, threshold-tuned on a held-out validation split.ROR’s own affiliation-matching API → a real, production registry service used across the open-science ecosystem.GPT-4o-mini, zero-shot, no fine-tuning, prompted directly to answer the same yes/no question. Total cost to benchmark: $0.0018, well under two-tenths of a cent.A couple of things worth sitting with here.GPT-4o-mini has perfect precision and the worst recall of anything tested. It’s extremely conservative; it only says “same” when the match is almost verbatim, and misses more than half of genuine matches that use different phrasing. That’s exactly the failure mode you’d predict for a general-purpose model asked to make a confident judgment on a domain it was never specifically trained for.ROR and the fine-tuned model are the only two systems that hit anything close to perfect precision neither falsely merges two different institutions. But ROR misses far more real matches (72.1% recall) than the fine-tuned model (98.88–100% recall across the two evaluation sets). The classical and embedding baselines invert this entirely: they catch more matches, but with far more false alarms, because generic string or embedding similarity simply cannot distinguish “same institution, reworded” from “different institution, similarly named.”That gap between generic similarity and an actual learned decision boundary for this specific task is what fine-tuning closes. And it closes it on free compute, in under an hour, with a model that runs inference in single-digit-to-low-double-digit milliseconds per decision, not the hundreds of milliseconds to seconds you’d pay for a hosted LLM call at scale.How trustworthy is our training data, really?Nobody has an official answer key for institution name disambiguation, so before trusting the resolver’s labels enough to fine-tune on, I checked them with claude to verify, on a random sample of 900 institutions, independent of the model entirely.97.2% were correct. 21 were genuinely wrong, and 4 were too ambiguous for me to resolve confidently. Most of the real errors traced back to one specific, repeatable bug: when an institution’s name is generic or missing a distinguishing detail, the resolver occasionally grabs the wrong record from its catalog and the same wrong record gets reused across several unrelated real institutions.The last two rows were the ones that actually mattered: I went back and checked whether this known error pattern had leaked into what the model was trained on. It had but barely. 3 contaminated pairs out of 17,500 training examples isn’t enough to meaningfully move a fine-tune of this size, and re-running the test evaluation with every affected label excluded changed the headline accuracy by exactly nothing (99.20% either way).What this isn’t (yet)In the interest of not overselling this:The label source is ~97% accurate, not 100%. We measured this directly (above), rather than assuming it, but a 3% error rate in any label source is still a real ceiling on what “accuracy” against it can mean.This is a pairwise verifier, not an end-to-end resolver. It answers “are these the same institution,” not “which of N institutions does this string match.” In a production pipeline, it sits downstream of a candidate-retrieval step, fuzzy match, or embedding search as a high-precision reranker, not a replacement for one.Remaining errors cluster around real-world-knowledge gaps, colloquial names, sub-institutional naming with no lexical link to the parent, that no amount of more training data of the same kind will fully close. That likely needs either explicit knowledge injection or a retrieval component with access to institutional metadata beyond the raw string.What’s nextOnce the accompanying paper is ready and posted to arXiv, we will update it here. The training dataset itself will follow once we clear the compliance review currently blocking its release.Github(Model Weights & Notebook) → https://github.com/Jeet009/institution-name-disambiguation-layaIf you work in scientometrics, bibliometrics, or research-integrity tooling and this is a problem you’ve also been quietly fighting with your own ad hoc string-matching rules: this won’t be the last word on institution name disambiguation, but for a weekend’s worth of free Kaggle GPU time, it’s a considerably better word than anything else I tried.How I Fine-Tuned Laya to Solve an Important Problem in Scientometrics — With Claude Code was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.