Update card
Browse files12 unmodified lines13141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716812 unmodified lines# CLEST-TCRdist**C**ontrastive **LE**arning with **S**oft **T**argets from **TCRdist**.Checkpoint `SCEPTR6L_AC_soft_800k_20ep_bs1024`.A paired-chain αβ **T-cell receptor (TCR) language model** that maps a TCR to a128-dimensional vector such that TCRs binding the same epitope land closetogether. It is built on[SCEPTR](https://github.com/yutanagano/sceptr) (Nagano et al. 2025, *CellSystems*) and changes exactly one term of its training objective: theautocontrastive target, which treats every other receptor in the batch as anegative, is replaced with a graded target `exp(-d_TCRdist/τ)` computed inbatch (τ = 50). Architecture, corpus, augmentation and compute are held fixedagainst the autocontrastive control, so the difference between them isattributable to that term.### Two things to read before quoting a number- **This is one training run, not a mean.** The checkpoint predates seeding inour pipeline. Three seeded replicates of the identical configuration score0.809 ± 0.006 prototype AUROC@50 and 0.774 ± 0.009 at nearest-neighbour, wherethis run scores 0.842 and 0.794 — it sits above all three in every cell. Treatthe replicate means as the recipe's expected performance.- **What the objective is actually worth.** Seeding both arms (3 soft-labelreplicates, 2 autocontrastive controls, scored in one run on shared referencedraws) puts the gap over the matched control at **+0.038 AUROC@50** atnearest-neighbour — six times the pooled seed spread, positive on five of sixepitopes — down from the +0.058 the two published runs suggested. The controlarm reproduces its published run almost exactly (0.7356/0.7366 vs 0.7361), sothis is a real shrinkage and not environment drift.- **It does not beat TCRdist on accuracy, and we do not claim it does.** Overseeds the 1-NN margin changes sign. What the objective buys is measuredagainst its own autocontrastive control, and a scoring-rule inversion that isitself conditional on the evaluation repertoire (see the paper).- **Architecture:** 6-layer Pre-LN / NormFormer transformer encoder,d_model = 128, 8 heads, `CdrSimpleEmbedder` (embedding_dim = 29), CLS-tokenreadout. ~1.2 M parameters.- **Output:** L2-comparable 128-d embedding per TCR(`calc_vector_representations`); pairwise distances via`calc_cdist_matrix` / `calc_pdist_vector`.- **Inference is epitope-free:** the model sees only the TCR, never the epitope.## How to use```pythonfrom scaled_sceptr.hf_hub import load_championmodel = load_champion() # downloads ~5 MB on first call# df: columns TRAV, CDR3A, TRAJ, TRBV, CDR3B, TRBJvecs = model.calc_vector_representations(df) # (N, 128) float32cdist = model.calc_cdist_matrix(df_a, df_b) # (Na, Nb) distances```Requires the study package installed (local editable `libtcrlm` + `sceptr`,see the repo README "Installation"). The encoder class is registered into`libtcrlm` automatically by `load_champion`.## Application: few-shot epitope-specificity retrievalThis is the model's headline use case. Give it **k known binders** for anepitope (the reference set) and it scores **any query TCR** for how stronglyit is specific to that epitope — no epitope sequence and no classifierretraining required. It is the epitope-free, learned analogue of TCRMatch andtcrdist3 meta-clonotypes. On the paper's fourteen-method slate thischeckpoint ranks first (NN AUROC@50 = 0.801, prototype AUROC@50 = 0.860), butthat ranking should be read with two controls attached: the checkpoint wasselected on the same epitope panel it is scored on (moving selection to sixheld-out epitopes costs 0.013), and it is a single unseeded run that sits aboveall three of its seeded replicates. The margin over TCRdist does not surviveeither control, and does not survive giving TCRdist its own published read-outeither (Dash et al. score the nearest 10% of the reference set, not the nearestone; under each method's own best rule the comparison is a draw, +0.010,p = 0.42). The durable comparison is against the matched autocontrastivecontrol. Note that the prototype-over-nearest-neighbour gain is **not** specificto this objective: once the control is reseeded it gains +0.041 from prototypescoring against this model's +0.034, so that inversion is a property of theevaluation repertoire rather than of the training target.```pythonimport numpy as npfrom scaled_sceptr.hf_hub import load_championmodel = load_champion()# reference = k known binders for the epitope of interest# query = TCRs you want to score (a repertoire, a screen, etc.)# both are DataFrames with columns TRAV, CDR3A, TRAJ, TRBV, CDR3B, TRBJcdist = model.calc_cdist_matrix(query, reference) # (n_query, k)# Prototype scoring (recommended — averages the whole reference cloud into a# centroid; this is where the soft-label geometry pays off). Higher = more# specific to the epitope.proto_score = -cdist.mean(axis=1) # (n_query,)# Nearest-neighbour scoring (single closest binder) — also strong, use when# the reference set is heterogeneous / multi-clonal.nn_score = -cdist.min(axis=1) # (n_query,)ranked = np.argsort(-proto_score) # most-specific queries first```The score is a relative ranking, not a calibrated probability. To get abinary call, pick a threshold on a held-out labeled set, or rank a repertoireand take the top hits. Prototype scoring is the mode to prefer whenever the kreference binders are known to share the epitope; it is what produces themodel's largest, statistically significant advantage over TCRdist.## Training| | ||---|---|| **Objective** | Autocontrastive (AC) + MLM. Positives = two augmented views of the *same* TCR (token dropout 0.2, chain dropout 0.5); the InfoNCE matrix is additionally weighted by **in-batch TCRdist soft labels** (`exp(−d_TCRdist/τ)`, τ = 50, distance threshold 200). || **Contrastive loss** | dot-product InfoNCE, temperature 0.05 || **MLM loss** | adjusted cross-entropy, label smoothing 0.1 || **Data** | ~828k **unlabeled** paired αβ TCRs (Tanno et al. 2022, Zenodo 14288119). No epitope labels are used in pretraining. || **Schedule** | batch size 1024, 20 epochs, Noam warmup 2000 steps || **Checkpoint** | epoch 20 (lowest `valid_cont_loss` = 1.978); selected automatically |This is the **autocontrastive** regime — the protocol that matches the SCEPTRpaper. It does **not** use epitope labels, so its benchmark AUROC is a genuinezero-shot number (unlike the supervised-contrastive "clean" variants elsewherein the study, which see the benchmark epitopes during training and reportinflated ~0.97 AUROC).## EvaluationFew-shot epitope retrieval on the SCEPTR paper protocol (raw VDJdb, 6 epitopes,1-NN scoring, `--max-neg 5000`, 100 repeats). AUROC, equal-weighted acrossepitopes:| Model | AUROC@50 | AUROC@200 ||---|---|---|| **CLEST-TCRdist (this model)** | **0.7945** | **0.8138** || TCRdist (reference) | 0.7787 | 0.8020 || SCEPTR (base AC, published) | 0.7360 | 0.7459 || CDR3 Levenshtein | 0.6989 | — |The headline number reproduces exactly (`0.79448`) from the publishedcheckpoint with the command in the repo README.**Scope / caveats.**- This is a **TCR-to-TCR similarity** model, not an epitope classifier. Itpredicts binding only by retrieval against a labeled reference set.- The scaling study found this recipe is **plateaued**: deeper (12L), wider(d=256), modern-norm (RMSNorm/SwiGLU/QK-Norm), and larger-corpus variants alltie or lose to this 6L Tanno-only recipe.- ~8.6% of Tanno CDR3β sequences also appear in VDJdb — the field-standardbackground contamination shared by TCRdist and the published SCEPTR baselinealike; a CDR3β-clean leak-free benchmark preserves the same small advantage.## CitationBuilt on SCEPTR (Nagano et al. 2025, *Cell Systems*) and TCRdist(Dash et al. 2017, *Nature*). Pretraining data: Tanno et al. 2022.12 unmodified lines13141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116212 unmodified lines# CLEST-TCRdistContrastive LEarning with Soft Targets from TCRdist. Checkpoint`SCEPTR6L_AC_soft_800k_20ep_bs1024`.A paired-chain αβ T-cell receptor encoder. It maps a TCR to a 128-dimensional vector inwhich receptors that recognise the same peptide sit close together, so retrieval andclustering of specificity groups reduce to nearest-neighbour search. The model reads onlythe receptor, never the epitope.It is built on [SCEPTR](https://github.com/yutanagano/sceptr) (Nagano et al. 2025, *CellSystems*) and changes one term of its objective. Autocontrastive pretraining treats everyother receptor in a batch as a negative. Here each in-batch pair gets a graded target`exp(-d_TCRdist / 50)`, zero beyond a TCRdist of 200, computed on the fly with tcrdist3.No epitope labels are involved, and nothing is precomputed. Architecture, corpus,augmentation and batch size are held fixed against an autocontrastive control trained thesame way, which is what makes the comparison between them a single-variable one.## Install```bashpip install git+https://github.com/20eddibae/CLEST-TCRDist.gitpip install --no-deps sceptr==1.2.0```sceptr goes in with `--no-deps` because its metadata asks for numpy 2 while tcrdist3 needs1.26. Everything it actually imports is already installed by the line above.## Use it```pythonimport pandas as pdfrom clest_tcrdist import load_pretrainedmodel = load_pretrained() # pulls ~5 MB here, then cachestcrs = pd.DataFrame({"TRAV": ["TRAV35*01"], "CDR3A": ["CAGQLGGGSQGNLIF"], "TRAJ": ["TRAJ42*01"],"TRBV": ["TRBV19*01"], "CDR3B": ["CASSIRSSYEQYF"], "TRBJ": ["TRBJ2-7*01"],})vectors = model.calc_vector_representations(tcrs) # (N, 128)distances = model.calc_cdist_matrix(tcrs, tcrs) # (N, N)```The returned object is a `sceptr.model.Sceptr`, so anything written against the SCEPTR APIworks unchanged. Columns are IMGT symbols and amino-acid junctions. A missing chain or genecan be left empty, and single-chain input is accepted.### Few-shot retrievalGiven a few known binders for one epitope, rank a repertoire:```pythonfrom clest_tcrdist import read_tcrs, retrieverepertoire = read_tcrs("repertoire.csv") # any common column namingseeds = read_tcrs("known_binders.csv")ranked = retrieve(repertoire, seeds, model=model) # sorted best first```or from the shell:```bashpython -m clest_tcrdist.retrieve repertoire.csv --seeds known_binders.csv -o ranked.csv```Scoring is distance to the mean seed embedding by default, or to the nearest single seedwith `--scoring nearest`. Averaging over the seeds is worth about 0.05 AUROC to this modeland is what the headline number below uses.### Clustering```bashpython -m clest_tcrdist.cluster repertoire.csv -o clustered.csv```Pairs within a radius are linked and connected components become clusters, the sameconstruction GIANA and TCRdist use, with the radius measured in this embedding. The radiusis calibrated from the data unless you set `--threshold`, and it controls a purity againstretention tradeoff: on 120 TCRs across four epitopes, purity is 1.00 out to 20% retention,then 0.88 at 30% and 0.74 at 40%. `--sweep` prints that curve for a labelled file. Compareclustering methods at matched retention, never at matched radius.## How it scoresFew-shot retrieval on the six-epitope VDJdb backtest of the SCEPTR paper, 100 resamplingsof the reference set, mean AUROC over epitopes, nearest-neighbour scoring:| Reference TCRs | CLEST-TCRdist | TCRdist | SCEPTR (released) | CDR3 Levenshtein ||---|---|---|---|---|| 1 | 0.701 | 0.684 | 0.643 | 0.621 || 10 | 0.765 | 0.756 | 0.710 | 0.687 || 50 | 0.794 | 0.779 | 0.737 | 0.699 || 200 | 0.814 | 0.802 | 0.754 | 0.708 |## Read this before quoting a number**These weights are one training run, not an average.** The checkpoint predates seeding inour pipeline. Five seeded replicates of the identical configuration average 0.7750 ± 0.0076at nearest-neighbour and 0.8104 ± 0.0053 under average-distance scoring, where this rungives 0.7945 and 0.8423. It sits above all five in every cell, 2.5 seed standard deviationsout at nearest-neighbour and 6.0 under averaging. Treat the replicate means as what therecipe gives you, and this checkpoint as a lucky draw from it. All five replicates are inthe paper's supplement.**What the objective is worth is measured against its own control, not against TCRdist.**With the full set of replicates the soft-label target buys +0.039 AUROC@50 atnearest-neighbour over the matched autocontrastive control (paired over six epitopes,p = 0.043, positive on five) and +0.048 under averaging (p = 0.119). Across estimators therange is +0.038 to +0.056. That single-variable comparison is the contribution.**It does not reliably beat TCRdist, and we do not claim it does.** The margin in the tableabove does not survive two controls: reselecting hyperparameters on held-out epitopes costsabout 0.013, and giving TCRdist the read-out from its own publication rather than the 1-NNrule inherited here closes the rest. Over seeds the sign of the 1-NN margin changes. Whatholds up is the gap over the control.**It is not an epitope-binding classifier.** There is no peptide or MHC input. It tells youwhich receptors resemble each other in a space shaped by specificity; it cannot tell youthat a receptor binds a peptide you have not given it examples of.## Training- 6-layer Pre-LN transformer with NormFormer norms, d_model 128, 8 heads, dropout 0.1,`CdrSimpleEmbedder` (29-dim token embedding), CLS readout, 1,203,860 parameters.- 827,802 unlabeled paired αβ TCRs from Tanno et al. 2022([Zenodo 14288119](https://doi.org/10.5281/zenodo.14288119)). No epitope labels anywherein pretraining.- 20 epochs, batch 1024, Noam schedule with 2000 warmup steps, contrastive temperature0.05, masked-token auxiliary loss with 0.1 label smoothing.- Shipped epoch is the one with the lowest validation contrastive loss, epoch 20. Therepository contains `config.json` and `log.csv` for the whole run.## Also here- [Fine-tuned variant](https://huggingface.co/20eddibae/sceptr-ac-finetuned), for when youhave epitope labels to train on.- [Benchmark data](https://huggingface.co/datasets/20eddibae/sceptr-tcr-benchmark), theVDJdb snapshot these numbers come from.- [Code](https://github.com/20eddibae/CLEST-TCRDist), including the training configs andthe benchmark that produced the table.## CitationThe manuscript is in preparation; cite the repository until it appears. Please also citeSCEPTR (Nagano et al., *Cell Systems* 2025), TCRdist (Dash et al., *Nature* 2017), theTanno et al. 2022 paired repertoire, and VDJdb (Bagaev et al. 2020).MIT licensed.
README.md+127-133