Contrastive learning is a discriminative training approach where a model learns an embedding space by comparing sample pairs. The objective function explicitly minimizes the distance between positive pairs—such as a clinical mention and its correct UMLS concept—while maximizing the distance between negative pairs, like a mention and an incorrect entity. This is typically implemented using the InfoNCE loss or triplet loss, which computes similarity scores between anchor, positive, and negative samples to shape the representation manifold.
Glossary
Contrastive Learning

What is Contrastive Learning?
Contrastive learning is a self-supervised training paradigm that learns robust data representations by pulling semantically similar pairs together and pushing dissimilar pairs apart in a dense vector space.
In clinical entity linking, contrastive learning is critical for disambiguation. Models like SapBERT are pre-trained by pulling synonymous biomedical concepts from the UMLS Metathesaurus together, creating a unified vector space where "MI" and "myocardial infarction" are proximal. The paradigm relies heavily on hard negative mining, where the most confusable incorrect candidates are selected during training to sharpen the decision boundary and prevent false grounding of ambiguous medical abbreviations.
Key Characteristics of Contrastive Learning
Contrastive learning is a self-supervised paradigm that learns effective representations by pulling semantically similar pairs (positive) together and pushing dissimilar pairs (negative) apart in embedding space.
Positive Pair Construction
The engine of contrastive learning relies on defining positive pairs—two views of the same underlying concept. In clinical entity linking, a positive pair consists of a mention (e.g., 'heart attack') and its canonical entity (e.g., UMLS C0027051: Myocardial Infarction). These pairs can be generated through:
- Synonym substitution from ontologies like SNOMED CT
- Dropout augmentation where the same input passes through a model twice
- Contextual paraphrasing of the surrounding clinical text The model learns to map these distinct surface forms to identical vector coordinates.
Negative Sampling Strategies
The discriminative power of contrastive learning comes from negative pairs—entities that the mention should not link to. Effective negative sampling is critical:
- In-batch negatives: Other entities within the same training mini-batch serve as negatives, enabling efficient computation
- Hard negative mining: Selecting highly confusable entities (e.g., 'myocardial infarction' vs. 'myocardial ischemia') that share semantic overlap with the mention
- Random negatives: Uniformly sampled entities from the knowledge base to provide broad repulsive force Without hard negatives, the model fails to learn fine-grained disambiguation.
InfoNCE Loss Function
The standard training objective is InfoNCE (Noise Contrastive Estimation), a categorical cross-entropy loss over similarity scores. For a given mention anchor m and a positive entity e+:
- Compute cosine similarity between
mand all candidates in the batch - Apply a temperature parameter (τ) to control the concentration of the distribution
- Lower τ creates a sharper distribution, penalizing hard negatives more aggressively
- The loss minimizes
-log(exp(sim(m, e+)/τ) / Σ exp(sim(m, ei)/τ))This formulation is a lower bound on mutual information between the mention and entity representations.
Bi-Encoder Architecture
Contrastive learning in entity linking typically uses a dual-tower (bi-encoder) architecture:
- Mention Encoder: A transformer (e.g., SapBERT, PubMedBERT) encodes the clinical mention and its surrounding context into a dense vector
- Entity Encoder: A separate or shared transformer encodes the entity's canonical name, synonyms, and description from the knowledge base
- Both towers project into a shared L2-normalized embedding space where inner product equals cosine similarity
- At inference, entity embeddings are pre-computed and indexed using FAISS for fast approximate nearest neighbor search
Supervised Contrastive Variant
Beyond self-supervised instance discrimination, supervised contrastive learning leverages label information to structure the embedding space more effectively:
- Multiple mentions that link to the same UMLS concept are treated as positives for each other, not just their entity description
- This pulls together diverse surface forms like 'MI', 'heart attack', and 'myocardial infarct' into a tight cluster
- The loss function generalizes InfoNCE to handle multiple positives per anchor
- This approach is particularly effective for high-variance clinical language where the same condition has dozens of synonymous expressions
Momentum Contrast (MoCo)
Momentum Contrast addresses the challenge of maintaining a large and consistent dictionary of negative samples without massive batch sizes:
- A momentum encoder (slowly updating copy of the main encoder) maintains a dynamic queue of recent entity embeddings
- The queue acts as a large negative sample bank, decoupling batch size from negative set size
- The momentum update rule
θ_k ← m·θ_k + (1-m)·θ_qwith a high momentum coefficient (e.g., 0.999) ensures consistency - This is critical for biomedical entity linking where the knowledge base may contain millions of concepts
Frequently Asked Questions
Explore the core mechanisms, training strategies, and architectural decisions behind contrastive learning for clinical entity linking. These answers target the precise technical queries of NLP scientists and bioinformatics engineers building high-precision medical grounding systems.
Contrastive learning is a self-supervised representation learning paradigm that trains models to pull positive mention-entity pairs together and push negative pairs apart in a shared dense vector space. For clinical entity linking, a bi-encoder architecture independently encodes a text mention (e.g., 'MI') and a candidate concept (e.g., UMLS C0027051: Myocardial Infarction) into embeddings. The training objective—typically InfoNCE loss—maximizes the cosine similarity between the mention and its true concept while minimizing similarity with all other in-batch negatives. This forces the model to learn semantic representations that cluster synonymous clinical terms (like 'heart attack' and 'myocardial infarction') near each other, while separating them from confusable entities such as 'mitral insufficiency'. The result is a model that can perform efficient approximate nearest neighbor search over millions of UMLS concepts without needing exhaustive pairwise scoring at inference time.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
Core architectural components and training strategies that operationalize contrastive learning for high-precision clinical entity linking.
Bi-Encoder Architecture
A dual-tower neural network that independently encodes a text mention and a knowledge base entity into dense vectors for efficient, scalable semantic similarity search. In contrastive learning, the bi-encoder forms the backbone that generates the representations to be pulled together or pushed apart.
- Mention Encoder: A transformer (e.g., PubMedBERT) that contextualizes the ambiguous clinical span.
- Entity Encoder: A separate tower that encodes the canonical entity's title and description.
- Efficiency: Enables pre-computation of all entity embeddings for fast Approximate Nearest Neighbor Search at inference time.
Hard Negative Mining
A contrastive learning strategy that selects highly confusable but incorrect candidate entities during training to improve a model's disambiguation capability. Standard random negatives are too easy; hard negatives force the model to learn fine-grained distinctions.
- In-Batch Negatives: Treating other entities in the same mini-batch as negative examples.
- BM25 Hard Negatives: Using lexical retrieval to find top-scoring but incorrect candidates.
- Cross-Encoder Filtering: Employing a reranker to identify the most plausible false positives for the training batch.
InfoNCE Loss
The canonical contrastive loss function (Noise Contrastive Estimation) that maximizes the mutual information between positive mention-entity pairs while minimizing it for negatives. It is the mathematical engine driving representation learning in models like SapBERT.
- Temperature Parameter: A hyperparameter that controls the concentration of the distribution; lower values create sharper distinctions between positives and hard negatives.
- Symmetric Formulation: The loss is often computed bidirectionally, pulling the mention to the entity and the entity to the mention.
SapBERT
A pre-trained biomedical language model optimized for entity linking by aligning synonymous concepts from the UMLS Metathesaurus into a shared dense vector space. It is trained using a self-supervised contrastive objective where synonymous concepts are positives and random concepts are negatives.
- Synonym Marginalization: Aggregates multiple synonymous terms for a single CUI to form a robust centroid representation.
- Cross-Lingual Alignment: Extends contrastive learning to map concepts across languages, enabling zero-shot multilingual entity linking.
In-Batch Negative Sampling
A memory-efficient contrastive training technique that repurposes other positive examples within the same mini-batch as negative samples. This avoids the computational cost of explicitly mining negatives from the full knowledge base.
- Scalability: The effective number of negatives scales linearly with batch size, making large batch sizes critical for performance.
- Gradient Accumulation: Used to simulate large batches on hardware with limited GPU memory.
- Bias Correction: Techniques to correct for the sampling bias introduced when true positives accidentally appear as in-batch negatives.
Cross-Encoder Reranker
A neural architecture that processes a mention-candidate pair jointly through a transformer to produce a high-fidelity relevance score. While too slow for full retrieval, it serves as the precise scoring function during candidate ranking, often trained with a contrastive or cross-entropy objective.
- Joint Encoding: Allows full cross-attention between the mention tokens and entity description tokens.
- Two-Stage Pipeline: A bi-encoder retrieves top-k candidates, and the cross-encoder reranks them.
- Distillation: The cross-encoder's knowledge can be distilled back into a bi-encoder for faster inference.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us