Sentence Similarity
sentence-transformers
Safetensors
Transformers
English
bert
feature-extraction
text-embeddings-inference
Instructions to use Tao-AI-Informatics/NA-SapBERT with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- sentence-transformers
How to use Tao-AI-Informatics/NA-SapBERT with sentence-transformers:
from sentence_transformers import SentenceTransformer model = SentenceTransformer("Tao-AI-Informatics/NA-SapBERT") sentences = [ "That is a happy person", "That is a happy dog", "That is a very happy person", "Today is a sunny day" ] embeddings = model.encode(sentences) similarities = model.similarity(embeddings, embeddings) print(similarities.shape) # [4, 4] - Transformers
How to use Tao-AI-Informatics/NA-SapBERT with Transformers:
# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModel tokenizer = AutoTokenizer.from_pretrained("Tao-AI-Informatics/NA-SapBERT") model = AutoModel.from_pretrained("Tao-AI-Informatics/NA-SapBERT", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Update README.md
Browse files5 unmodified lines67891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291305 unmodified lines- feature-extraction- sentence-similarity- transformers---# {MODEL_NAME}This is a [sentence-transformers](https://www.SBERT.net) model: It maps sentences & paragraphs to a 768 dimensional dense vector space and can be used for tasks like clustering or semantic search.<!--- Describe your model here -->## Usage (Sentence-Transformers)Using this model becomes easy when you have [sentence-transformers](https://www.SBERT.net) installed:```pip install -U sentence-transformers```Then you can use the model like this:```pythonfrom sentence_transformers import SentenceTransformersentences = ["This is an example sentence", "Each sentence is converted"]model = SentenceTransformer('{MODEL_NAME}')embeddings = model.encode(sentences)print(embeddings)```## Usage (HuggingFace Transformers)Without [sentence-transformers](https://www.SBERT.net), you can use the model like this: First, you pass your input through the transformer model, then you have to apply the right pooling-operation on-top of the contextualized word embeddings.```pythonfrom transformers import AutoTokenizer, AutoModelimport torch#Mean Pooling - Take attention mask into account for correct averagingdef mean_pooling(model_output, attention_mask):token_embeddings = model_output[0] #First element of model_output contains all token embeddingsinput_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)# Sentences we want sentence embeddings forsentences = ['This is an example sentence', 'Each sentence is converted']# Load model from HuggingFace Hubtokenizer = AutoTokenizer.from_pretrained('{MODEL_NAME}')model = AutoModel.from_pretrained('{MODEL_NAME}')# Tokenize sentencesencoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')# Compute token embeddingswith torch.no_grad():model_output = model(**encoded_input)# Perform pooling. In this case, mean pooling.sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])print("Sentence embeddings:")print(sentence_embeddings)```## Evaluation Results<!--- Describe how your model was evaluated -->For an automated evaluation of this model, see the *Sentence Embeddings Benchmark*: [https://seb.sbert.net](https://seb.sbert.net?model_name={MODEL_NAME})## TrainingThe model was trained with the parameters:**DataLoader**:`torch.utils.data.dataloader.DataLoader` of length 853 with parameters:```{'batch_size': 256, 'sampler': 'torch.utils.data.sampler.RandomSampler', 'batch_sampler': 'torch.utils.data.sampler.BatchSampler'}```**Loss**:`sentence_transformers.losses.MultipleNegativesRankingLoss.MultipleNegativesRankingLoss` with parameters:```{'scale': 20.0, 'similarity_fct': 'cos_sim'}```Parameters of the fit()-Method:```{"epochs": 1,"evaluation_steps": 0,"evaluator": "NoneType","max_grad_norm": 1,"optimizer_class": "<class 'torch.optim.adamw.AdamW'>","optimizer_params": {"lr": 1e-05},"scheduler": "WarmupLinear","steps_per_epoch": null,"warmup_steps": 85,"weight_decay": 0.01}```## Full Model Architecture```SentenceTransformer((0): Transformer({'max_seq_length': 64, 'do_lower_case': False}) with Transformer model: BertModel(1): Pooling({'word_embedding_dimension': 768, 'pooling_mode_cls_token': False, 'pooling_mode_mean_tokens': True, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False, 'pooling_mode_weightedmean_tokens': False, 'pooling_mode_lasttoken': False, 'include_prompt': True}))```## Citing & Authors<!--- Describe where people can find more information -->5 unmodified lines67891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601615 unmodified lines- feature-extraction- sentence-similarity- transformerslanguage:- enbase_model:- cambridgeltl/SapBERT-from-PubMedBERT-fulltext-mean-token---# NA-SapBERT: Noise-Augmented SapBERT for Clinical Concept NormalizationNA-SapBERT is a dense retrieval model designed for clinical concept normalization over large ontologies such as SNOMED CT. It extends SapBERT by incorporating noise-aware training, enabling robust retrieval for real-world clinical mentions.Unlike standard SapBERT, this model is trained to handle:- abbreviations (e.g., "NAD", "DM")- misspellings- shorthand and telegraphic clinical text- surface form variation across notes---## OverviewClinical concept normalization maps noisy text mentions to standardized ontology concepts. While modern NER systems perform well, entity linking remains challenging due to:- large ontology size- noisy clinical text- ambiguous abbreviations- mismatch between ontology terms and real-world mentionsNA-SapBERT addresses this by learning invariant embeddings across noisy and canonical forms.---## Key IdeaDuring training, the model learns to align:- noisy mentions (LLM-generated variants, abbreviations)- clean ontology terms (concept names and synonyms)This is achieved using contrastive learning:- clean–clean pairs preserve structure- noisy–clean pairs improve robustness---## Model ArchitectureSentenceTransformer:- Transformer (PubMedBERT backbone)- Mean PoolingEmbedding dimension: 768Max sequence length: 64---## Training Details### Data- SNOMED CT concepts (subset of key semantic types)- Synthetic variants:- LLM-generated (MedGemma) noise- abbreviation mappings### ObjectiveMultipleNegativesRankingLoss (InfoNCE-style)### Training Configuration- epochs: 1- batch_size: 256- learning_rate: 1e-5- warmup_steps: 85---## Usage### Installpip install -U sentence-transformers### Encode Mentions```pythonfrom sentence_transformers import SentenceTransformermodel = SentenceTransformer("YOUR_MODEL_NAME")mentions = ["NAD", "hx of diabetes", "left axillary lymph node"]embeddings = model.encode(mentions, normalize_embeddings=True)```---## Retrieval Example (FAISS)```pythonimport faissimport numpy as npfrom sentence_transformers import SentenceTransformermodel = SentenceTransformer("YOUR_MODEL_NAME")concept_embeddings = np.load("concept_embeddings.npy").astype("float32")index = faiss.IndexFlatIP(768)index.add(concept_embeddings)query = "NAD"q_emb = model.encode([query], normalize_embeddings=True)scores, indices = index.search(q_emb, k=10)```---## Pipeline IntegrationTypical pipeline:1. Exact match2. Dense retrieval (NA-SapBERT)3. Optional rewrite / multi-query4. Optional reranking---## Performance Summary- SapBERT: XX recall@1- NA-SapBERT: XX recall@1Improvements:- Better handling of noisy mentions- Strong generalization to full SNOMED CT---## Limitations- No explicit modeling of negation or temporality- Abbreviations remain ambiguous without context- Depends on ontology synonym quality---## Use CasesUse for:- clinical NLP- concept normalization- ontology retrievalNot intended for:- general semantic similarity- non-biomedical tasks
README.md+111-80