{"id":33058421,"url":"https://github.com/cambridgeltl/sapbert","last_synced_at":"2025-11-23T16:01:23.886Z","repository":{"id":38682872,"uuid":"356237604","full_name":"cambridgeltl/sapbert","owner":"cambridgeltl","description":"[NAACL'21 \u0026 ACL'21] SapBERT: Self-alignment pretraining for BERT \u0026 XL-BEL: Cross-Lingual Biomedical Entity Linking.","archived":false,"fork":false,"pushed_at":"2023-04-28T20:04:27.000Z","size":107103,"stargazers_count":162,"open_issues_count":2,"forks_count":32,"subscribers_count":11,"default_branch":"main","last_synced_at":"2024-06-12T12:25:21.899Z","etag":null,"topics":["acl2021","bert","bionlp","contrastive-learning","language-model","lexical-semantics","machine-learning","metric-learning","naacl2021","nlp","representation-learning"],"latest_commit_sha":null,"homepage":"https://www.aclweb.org/anthology/2021.naacl-main.334","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/cambridgeltl.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2021-04-09T10:55:09.000Z","updated_at":"2024-05-23T16:04:30.000Z","dependencies_parsed_at":"2024-01-14T07:04:07.139Z","dependency_job_id":null,"html_url":"https://github.com/cambridgeltl/sapbert","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/cambridgeltl/sapbert","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cambridgeltl%2Fsapbert","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cambridgeltl%2Fsapbert/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cambridgeltl%2Fsapbert/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cambridgeltl%2Fsapbert/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/cambridgeltl","download_url":"https://codeload.github.com/cambridgeltl/sapbert/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cambridgeltl%2Fsapbert/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":285977076,"owners_count":27264304,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-11-23T02:00:06.149Z","response_time":135,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["acl2021","bert","bionlp","contrastive-learning","language-model","lexical-semantics","machine-learning","metric-learning","naacl2021","nlp","representation-learning"],"created_at":"2025-11-14T05:00:28.834Z","updated_at":"2025-11-23T16:01:23.880Z","avatar_url":"https://github.com/cambridgeltl.png","language":"Python","funding_links":[],"categories":["Taxonomies and Ontologies of Research Concepts"],"sub_categories":[],"readme":"# SapBERT: Self-alignment pretraining for BERT\n\n**\\[news | 22 Aug 2021\\]** SapBERT is integrated into NVIDIA's deep learning toolkit NeMo as its [entity linking module](https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/main/nlp/entity_linking.html) (thank you NVIDIA!). You can play with it in this [google colab](https://colab.research.google.com/github/NVIDIA/NeMo/blob/v1.0.2/tutorials/nlp/Entity_Linking_Medical.ipynb).\n\n--------\n\nThis repo holds code, data, and pretrained weights for **(1)** the **SapBERT** model presented in our NAACL 2021 paper: [*Self-Alignment Pretraining for Biomedical Entity Representations*](https://www.aclweb.org/anthology/2021.naacl-main.334.pdf); **(2)** the **cross-lingual SapBERT** and a cross-lingual biomedical entity linking benchmark (**XL-BEL**) proposed in our ACL 2021 paper: [*Learning Domain-Specialised Representations for Cross-Lingual Biomedical Entity Linking*](https://arxiv.org/pdf/2105.14398.pdf).\n\n![front-page-graph](/misc/sapbert_front_graphs_v6.png?raw=true)\n\n\n\n\n## Huggingface Models\n\n### English Models: [\\[SapBERT\\]](https://huggingface.co/cambridgeltl/SapBERT-from-PubMedBERT-fulltext) and [\\[SapBERT-mean-token\\]](https://huggingface.co/cambridgeltl/SapBERT-from-PubMedBERT-fulltext-mean-token)\nStandard SapBERT as described in [\\[Liu et al., NAACL 2021\\]](https://www.aclweb.org/anthology/2021.naacl-main.334.pdf). Trained with UMLS 2020AA (English only), using `microsoft/BiomedNLP-PubMedBERT-base-uncased-abstract-fulltext` as the base model. For [\\[SapBERT\\]](https://huggingface.co/cambridgeltl/SapBERT-from-PubMedBERT-fulltext), use `[CLS]` (before pooler) as the representation of the input; for [\\[SapBERT-mean-token\\]](https://huggingface.co/cambridgeltl/SapBERT-from-PubMedBERT-fulltext-mean-token), use mean-pooling across all tokens.\n\n### Cross-Lingual Models: [\\[SapBERT-XLMR\\]](https://huggingface.co/cambridgeltl/SapBERT-UMLS-2020AB-all-lang-from-XLMR) and [\\[SapBERT-XLMR-large\\]](https://huggingface.co/cambridgeltl/SapBERT-UMLS-2020AB-all-lang-from-XLMR-large)\nCross-lingual SapBERT as described in [\\[Liu et al., ACL 2021\\]](https://arxiv.org/pdf/2105.14398.pdf). Trained with UMLS 2020AB (all languages), using `xlm-roberta-base`/`xlm-roberta-large` as the base model. Use `[CLS]` (before pooler) as the representation of the input.\n\n## Environment\nThe code is tested with python 3.8, torch 1.7.0 and huggingface transformers 4.4.2. Please view `requirements.txt` for more details.\n\n## Embedding Extraction with SapBERT\n\nThe following script converts a list of strings (entity names) into embeddings.\n```python\nimport numpy as np\nimport torch\nfrom tqdm.auto import tqdm\nfrom transformers import AutoTokenizer, AutoModel  \n\ntokenizer = AutoTokenizer.from_pretrained(\"cambridgeltl/SapBERT-from-PubMedBERT-fulltext\")  \nmodel = AutoModel.from_pretrained(\"cambridgeltl/SapBERT-from-PubMedBERT-fulltext\").cuda()\n\n# replace with your own list of entity names\nall_names = [\"covid-19\", \"Coronavirus infection\", \"high fever\", \"Tumor of posterior wall of oropharynx\"] \n\nbs = 128 # batch size during inference\nall_embs = []\nfor i in tqdm(np.arange(0, len(all_names), bs)):\n    toks = tokenizer.batch_encode_plus(all_names[i:i+bs], \n                                       padding=\"max_length\", \n                                       max_length=25, \n                                       truncation=True,\n                                       return_tensors=\"pt\")\n    toks_cuda = {}\n    for k,v in toks.items():\n        toks_cuda[k] = v.cuda()\n    cls_rep = model(**toks_cuda)[0][:,0,:] # use CLS representation as the embedding\n    all_embs.append(cls_rep.cpu().detach().numpy())\n\nall_embs = np.concatenate(all_embs, axis=0)\n```\n\nPlease see [inference/inference_on_snomed.ipynb](https://github.com/cambridgeltl/sapbert/blob/main/inference/inference_on_snomed.ipynb) for a more extensive inference example.\n\n## Train SapBERT\nExtract training data from UMLS as insrtructed in `training_data/generate_pretraining_data.ipynb` (we cannot directly release the training file due to licensing issues).\n\nRun:\n```bash\n\u003e\u003e cd train/\n\u003e\u003e ./pretrain.sh 0,1 \n```\nwhere `0,1` specifies the GPU devices. \n\nFor finetuning on your customised dataset, generate data in the format of \n```\nconcept_id || entity_name_1 || entity_name_2\n...\n```\nwhere `entity_name_1` and `entity_name_2` are synonym pairs (belonging to the same concept `concept_id`) sampled from a given labelled dataset. If one concept is associated with multiple entity names in the dataset, you could traverse all the pairwise combinations.\n\nFor cross-lingual SAP-tuning with general domain parallel data (muse, wiki titles, or both), the data can be found in `training_data/general_domain_parallel_data/`. An example script: `train/xling_train.sh`. \n\n## Evaluate SapBERT\nFor evaluation (both monlingual and cross-lingual), please view `evaluation/README.md` for details. `evaluation/xl_bel/` contains the XL-BEL benchmark proposed in [\\[Liu et al., ACL 2021\\]](https://arxiv.org/pdf/2105.14398.pdf).\n\n## Citations\nSapBERT: \n```bibtex\n@inproceedings{liu2021self,\n\ttitle={Self-Alignment Pretraining for Biomedical Entity Representations},\n\tauthor={Liu, Fangyu and Shareghi, Ehsan and Meng, Zaiqiao and Basaldella, Marco and Collier, Nigel},\n\tbooktitle={Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies},\n\tpages={4228--4238},\n\tmonth = jun,\n\tyear={2021}\n}\n```\nCross-lingual SapBERT and XL-BEL:\n```bibtex\n@inproceedings{liu2021learning,\n\ttitle={Learning Domain-Specialised Representations for Cross-Lingual Biomedical Entity Linking},\n\tauthor={Liu, Fangyu and Vuli{\\'c}, Ivan and Korhonen, Anna and Collier, Nigel},\n\tbooktitle={Proceedings of ACL-IJCNLP 2021},\n\tpages = {565--574},\n\tmonth = aug,\n\tyear={2021}\n}\n```\n\n## Acknowledgement\nParts of the code are modified from [BioSyn](https://github.com/dmis-lab/BioSyn). We appreciate the authors for making BioSyn open-sourced.\n\n## License\nSapBERT is MIT licensed. See the [LICENSE](LICENSE) file for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcambridgeltl%2Fsapbert","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcambridgeltl%2Fsapbert","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcambridgeltl%2Fsapbert/lists"}