AI4Bio Learning Hub · Field Guide

Contrastive Learning in Biomedical AI

Pull what belongs together, push what doesn't — a guide to contrastive objectives for single-cell, spatial, and multimodal biology, 2022–2025.

From NT-Xent on single cells (Concerto, 2022) to CLIP-style alignment of histology with transcriptomics (OmiCLIP, 2025) and chat-based exploration of cell atlases (CellWhisperer, 2025) — how contrastive objectives became a dominant paradigm for scalable representation learning across modalities.

Healshu LEGO master builder showing brick comparison, sorting, and difference-finding poses
LEGO lens · contrast & compare

像的归堆,不像的分开。

Contrastive learning teaches the model to sort by resemblance: pieces that click together belong in one pile, pieces that don't stay apart. 每一次「能拼上吗」的提问, 都是一次对比学习 —— every click test is a contrastive lesson.

Healshu LEGO master builder at a workbench with sorted bricks and a blank plan

Sort by Resemblance.

「能拼上的归一类,拼不上的分开。」

Contrastive learning is the tray-sorting game: hold two pieces side by side and ask whether they belong together. Do it a million times and the tray sorts itself — six scenes from the sorting bench, re-read as contrastive learning.

Scene 1 · 试拼一下

The click test

Hold two bricks and try to snap them. If they click, they belong to the same pile; if not, they don't. No labels needed — just the test.

Positive vs negative pairs. Every contrastive example is a click test: same-sample positives, different-sample negatives. See the basics ↓

Scene 2 · 分选盘同色归堆

The tray sorts itself

After enough click tests, the tray organizes: red bricks drift to red, long to long, studded to studded — without anyone naming the categories.

The embedding space. Contrastive objectives pull similar samples together and push dissimilar ones apart — unsupervised structure emerges. See the families ↓

Scene 3 · 找不同

Spot the difference

Two builds look identical at a glance. The game is finding the one brick that differs — and learning that everything else is "the same".

Augmentations & invariances. Two views of the same sample must land in the same spot: crops, noise, and modality shifts should not change identity. See the glossary ↓

Scene 4 · 混色砖的纠偏

The almost-right brick

A marbled brick sits between red and orange — the hardest call in the tray. Getting that one right teaches more than a hundred easy sorts.

Hard negatives. The most informative contrasts come from near-misses: samples that look alike but are genuinely different. See sampling ↓

Scene 5 · 同款不同色

Same mold, different color

A 2×4 brick is a 2×4 brick whether it is red, blue, or glow-in-the-dark. The color changes nothing about what it connects to.

Invariance to nuisance variation. Batch effects, sequencing depth, and imaging channels are color, not shape — good contrastive models ignore them. See the papers ↓

Scene 6 · 拿图纸对半成品

Check the half-build against the plan

Hold the half-finished castle next to the booklet: which parts already match, which are still loose ends?

Cross-modal pairing (CLIP-style). Match one modality against another — RNA against ATAC, image against text — the same way you check build against plan. See cross-modal models ↓

Four-panel LEGO comic of contrastive learning: two bricks are click-tested for fit, the sorting tray groups same-coloured bricks, a mismatched piece is spotted, and a mixed-colour brick is corrected
Four scenes, one sorting tray: the click test defines a positive pair, likes cluster, unlikes push apart — contrast enough, and the representation sorts itself.

对比一万次之后,分选盘自己会分类 —— contrast enough, and the representation sorts itself.

📖 What is Contrastive Learning?

Contrastive learning trains representations by pulling semantically related views together in an embedding space while pushing unrelated views apart. Unlike reconstruction objectives (VAEs, autoencoders) or token prediction (masked language modeling), contrastive losses operate directly on geometry of the embedding — defining what is similar by what the practitioner pairs together.

LEGO contrastive click test showing matching bricks, mismatched bricks, and embedding space separation
LEGO view. A click test defines positive and negative pairs before the model ever sees a label.
Core contrastive mechanism on the unit hypersphere. An anchor point and its positive pair (semantically related view) are pulled together; multiple negative points (unrelated views) are pushed apart by the InfoNCE / NT-Xent loss. The geometry of the final embedding space is determined entirely by what the practitioner defines as a positive pair — this is the upstream design decision that constrains everything downstream.
Figure 1Contrastive learning — the core mechanism. Pull the same thing together. Push everything else apart. A single objective on the unit hypersphere. The geometry of the embedding is defined entirely by what you call a positive pair — there is no "neutral" contrastive objective.

Why It Matters for Biology

The Four Contrastive Families You'll See

🔵 Instance Discrimination (SimCLR / NT-Xent)

anchor / + negatives

Two augmented views of the same cell are pulled together; all other cells in the batch are negatives. Concerto, scCello.

🟢 Cross-Modal (CLIP / InfoNCE)

Image Text / RNA pair shared space

Dual encoders project paired modalities into a shared space using InfoNCE. OmiCLIP, CellWhisperer, MedMPT, scCLIP.

🟡 Graph Contrastive (DGI / GCL)

real neighborhood corrupted max MI(node, neighborhood)

Maximize mutual information between a node and its local/global summary; corrupt the graph for negatives. GraphST, CellNEST, SpatialEx.

🟠 Supervised & Triplet Contrastive

anchor + (same class) − (other class)

Labels (cell ontology, cancer/WT, ligand class) define positives. Useful when class structure exists. ImmunoStruct (cancer–WT), supervised variants in foundation models.

The same paper often combines multiple families — e.g., MedMPT uses both intra-modal (CT slice ↔ CT slice) and inter-modal (CT ↔ report) contrastive losses alongside masked reconstruction.

Four contrastive families compared side by side. (1) Instance Discrimination (SimCLR/NT-Xent): two augmented views of the same input are the positive pair; everything else in the batch is negative. (2) Cross-Modal (CLIP/InfoNCE): dual encoders project paired modalities (image ↔ text, H&E ↔ omics, CT ↔ report) into a shared space. (3) Graph Contrastive (DGI/GCL): maximise mutual information between a node and its neighborhood; corrupted-feature graphs supply negatives. (4) Supervised Contrastive: class labels define positives — same class together, different class apart. The four pair-definitions produce four different latent-space geometries from the same data.
Figure 2The four contrastive families — same core loss, four ways to choose a positive pair. The architecture follows from the pair definition — not the other way around. Instance discrimination treats augmentations as positives; CLIP treats paired modalities; graph contrastive treats neighbors; supervised treats class siblings. Pick the family by asking: what invariance do I want my embedding to encode?

🔍 Visual Glossary: Hard Concepts at a Glance

A pictorial cheat sheet for the trickier ideas behind the methods below — InfoNCE geometry, EMA teacher–student, graph corruption, similarity matrices, the modality gap. Each diagram is the intuition, not the math.

LEGO embedding space with brick clusters and a hard negative between clusters
Embedding view. Similar pieces cluster naturally, while hard negatives sit near the boundary between groups.
The Loss

InfoNCE / NT-Xent: softmax over similarities

a anchor sim(a, ·) / τ → softmax + positive negatives in batch

The loss is just a categorical softmax: among the anchor's similarity scores to every candidate, the positive should win. Gradients drag its score up and everyone else's down. Temperature τ sharpens or softens the contest.

The Geometry

The unit hypersphere: only direction matters

‖z‖ = 1 · only angle counts cos similarity = aligned angles

All embeddings are L2-normalised onto a unit sphere. Similarity becomes a cosine — the angle between two vectors. Distance and magnitude are discarded; only direction in the latent space is meaningful.

Hyperparameter

Temperature τ: cold collapses, hot dissolves

τ = 0.01 τ = 0.1 τ = 1.0 collapsed healthy uniform

τ controls how concentrated representations get on the sphere. Too low and they collapse onto a single point; too high and the contrastive signal washes out into uniformity. Concerto uses 0.1; MedMPT uses 0.07 — both warm.

Architecture

Asymmetric EMA teacher–student

cell aug₁ aug₂ student ∇ trains teacher no gradient NT-Xent pull together EMA

Two encoders. Only the student gets a gradient; the teacher's weights are a slow exponential moving average of the student's. Asymmetry prevents the trivial "predict yourself" collapse.

Seen in: Concerto
Graph Contrastive

Deep Graph Infomax: real vs corrupted graph

real graph features shuffled discriminate: real summary ≠ corrupted summary

Keep the graph topology, shuffle the node features. Train the GNN so a node's embedding is informative about the real summary but uninformative about the corrupted one — forcing it to encode the genuine feature–location coupling.

Seen in: GraphST · CellNEST · SpatialEx
Cross-Modal

CLIP similarity matrix: diagonal positives

images i texts j positive (i=j) negative softmax row→col and col→row (symmetric)

Image-and-text pairs form an N×N similarity matrix. The only N positives lie on the diagonal; every off-diagonal cell is a "wrong" pair. Symmetric InfoNCE makes every row and every column pick its diagonal entry.

Seen in: OmiCLIP · CellWhisperer · MedMPT
Failure Mode

The modality gap

"shared" embedding space all images all texts gap clusters by modality, not semantics ✗

Even after CLIP training, images and texts often live in two parallel sub-spaces. Same-modality retrieval still works, but cross-modal retrieval — the whole point — quietly fails. Audit by checking off-modal nearest neighbors.

Graph Topology

Pairwise edges vs. hyperedges

pairwise graph hypergraph a single hyperedge connects a whole group at once

A pairwise edge says "A relates to B". A hyperedge says "A, B, C, D all participate in the same group" — niches, tissue domains, ligand–receptor cliques — without decomposing into 6 separate pairwise edges.

Seen in: SpatialEx
Spatial Communication

Multi-hop cell–cell relay

A B relay C ligand₁ ligand₂ A → B → C (two-hop signaling) attention weights reveal the cascade

Classical CCC methods only ask "does ligand on A bind receptor on B?". Multi-hop lets B then secrete a downstream ligand to C — a cascade. Graph attention surfaces it by treating the attention pattern itself as the signal.

Seen in: CellNEST
Geometry Shaping

Supervised contrastive on near-identical inputs

cross-entropy only + supervised contrastive cancer WT fragile boundary cancer WT

Cancer and wild-type peptides differ by one amino acid — their embeddings are almost on top of each other. Cross-entropy alone has to thread a hairline boundary. Supervised contrastive makes room first, then the classifier's job is easy.

Seen in: ImmunoStruct
Kernel Objective

HSIC: contrastive learning as dependence maximization

kernel dependence: tr(K H L H) K (reps) L (pairs) align HSIC = 0 ⇔ independent maximize dependence ⇒ reps encode pair ID

A kernel measure of statistical dependence between two variables: HSIC(X,Y) = 0 if and only if X and Y are independent (with a characteristic kernel). It is estimated as tr(K H L H)/(n−1)², where K and L are Gram (kernel) matrices over the two variables and H = I − (1/n)11ᵀ centers them. SSL-HSIC recasts contrastive learning as maximizing the dependence between a representation and its pair-identity, and shows InfoNCE is approximately a biased HSIC estimate — but the kernel supplies the spread, so it needs far fewer negatives.

HSIC = tr(K H L H) / (n−1)²
Seen in: SSL-HSIC (Li et al. 2021, kernel dependence maximization)

📅 Evolution Timeline: From One-Modality Cells to Multimodal Foundation Models

2022: Contrastive learning enters single-cell

Key Innovations:

  • Concerto (2022): First major application of NT-Xent contrastive learning to single-cell biology; scales to 10M+ cell reference atlases with rapid query mapping in seconds.

Era characteristic: Single-modality (RNA/CITE-seq), instance discrimination with model-level augmentation, atlas-scale ambition.

2023: Graph contrastive meets spatial

Key Innovations:

  • GraphST (2023): Deep Graph Infomax (DGI) variant for spatial transcriptomics — corrupts gene expression on a spatial graph to form negatives; unifies spatial clustering, multi-sample integration, and deconvolution.

Era characteristic: Spatial adjacency reframed as contrastive supervision; graph-level rather than instance-level objectives.

2025: Multimodal CLIP era — biology learns to retrieve

Key Innovations:

  • Nicheformer (2025-01): Foundation model trained on 110M dissociated + spatial cells; pretrained with masked language modeling (the non-contrastive counterpoint shown here) so spatial context transfers to scRNA-seq.
  • OmiCLIP (2025-05): CLIP-style dual encoder aligning H&E histology with transcriptomics over 2.2M paired image–text samples.
  • CellNEST (2025-06): Graph attention + DGI to detect single-cell-resolution cell–cell communication and multi-hop relay networks.
  • CellWhisperer (2025-11): InfoNCE on 1M transcriptomes paired with LLM-generated captions; enables chat-based exploration of single-cell data.
  • MedMPT (2025-11): Vision–language transformer for chest CT + reports, combining intra-modal and inter-modal contrastive losses with masked reconstruction.
  • ImmunoStruct (2025-12): Cancer–wild-type supervised contrastive loss separates immunogenic neoepitopes from near-identical wild-type peptides in latent space.
  • SpatialEx (2025-12): Hypergraph encoder + corrupted-hypergraph contrastive loss enables diagonal integration of serial spatial-omics sections via H&E as universal anchor.
  • Multimodal Foundation Transformers Perspective (2025-12): Proposes a unified "Super Transformer" framework where CLIP-style contrastive objectives bind heterogeneous biological modalities into one embedding space.

Era characteristic: Cross-modal contrastive alignment becomes the default mechanism for binding modalities (image–RNA, text–RNA, CT–report, structure–sequence) without a shared feature space.

🔬 Method Taxonomy: Four Contrastive Families

🧠 Instance Discrimination (SimCLR / NT-Xent / Self-Distillation)

Principle: Each cell is its own class. Generate two views (via dropout, gene masking, or asymmetric teacher–student passes) and pull them together while pushing all other cells in the batch apart on the unit hypersphere.

Advantages: No labels needed; scales to millions of cells; learns transcriptome-wide structure rather than HVG-only signal.

Watch out for: Performance is sensitive to batch size (more negatives → harder task → better embeddings); naïve gene-level augmentations can erase biology.

Representative work: Concerto (2022).

🔗 Cross-Modal Contrastive (CLIP / InfoNCE)

Principle: Two encoders project two different modalities into one shared space; paired samples are positives, all other pairs in the batch are negatives. Trained with symmetric InfoNCE.

Advantages: Enables zero-shot transfer, retrieval across modalities, and natural-language interfaces; doesn't require imputation between modalities.

Watch out for: Quality of paired data dominates everything; LLM-generated captions can leak label information; modality gap (representations cluster by modality rather than semantics) is a known failure mode.

Representative work: OmiCLIP (2025) · CellWhisperer (2025) · MedMPT (2025).

📊 Graph Contrastive (DGI / Deep Graph Infomax)

Principle: Build a graph from spatial/biological adjacency; corrupt it (e.g., shuffle node features) to create a negative graph; train a GNN to maximize mutual information between each node's representation and a real-graph summary while minimizing it against the corrupted summary.

Advantages: Encodes spatial neighborhood structure without requiring ground truth labels; well suited for ligand–receptor reasoning and multi-hop cell–cell communication.

Watch out for: Choice of graph (k-NN radius, hyperedge size) shapes results more than choice of loss; corruption strategy must not be trivially detectable.

Representative work: GraphST (2023) · CellNEST (2025) · SpatialEx (2025).

🎯 Supervised & Class-Conditional Contrastive

Principle: When labels exist (cell ontology, cancer vs. wild-type peptide, disease class), use them to define positive pairs across the dataset rather than just within-augmentation. Variants include SupCon and triplet/margin losses.

Advantages: Sharper decision boundaries than cross-entropy alone; particularly powerful for near-identical inputs that must be separated (1-aa peptide differences, fine-grained cell subtypes).

Watch out for: Label noise propagates aggressively into the geometry; requires careful sampling for class imbalance.

Representative work: ImmunoStruct (2025).

Choosing a Contrastive Recipe

Quick decision guide

  • One modality, lots of unlabeled cells: Instance discrimination (NT-Xent / self-distillation) — Concerto-style.
  • Two modalities, paired data: Symmetric InfoNCE with two encoders — OmiCLIP / CellWhisperer / MedMPT-style.
  • Spatial data or any graph-structured input: Graph contrastive (DGI variant) — GraphST / CellNEST / SpatialEx-style.
  • You have labels and near-identical inputs to separate: Supervised contrastive — ImmunoStruct-style.
  • Foundation model pretraining: Combine masked reconstruction + contrastive — MedMPT-style.

⚖️ Side-by-Side: Self-Augmentation vs. Cross-Modal Pairing

Concerto (2022) and OmiCLIP (2025) both minimise InfoNCE on the unit hypersphere, but they form positives — and avoid collapse — in completely opposite ways: one cell viewed twice through dropout vs. a matched H&E tile and transcriptome profile.

The same raw input — a single cell's gene-expression vector — becomes very different training signals depending on whether you augment within one modality or pair across two:

Concerto (2022)
Instance discrimination · NT-Xent · single modality
Form positive pair via dropout
Same cell passed through encoder twice with different dropout masks → two views of the same transcriptome
Collapse prevention: asymmetric teacher–student
A larger attention-based teacher aggregates gene embeddings; a smaller student encodes the dropout view. This architectural asymmetry, together with NT-Xent over in-batch negatives, prevents trivial collapse
RNA embedding unit sphere z
single modality · dropout augment · teacher–student asymmetry · in-batch negatives
OmiCLIP (2025)
Cross-modal CLIP · symmetric InfoNCE · H&E + transcriptome
Form positive pair via biological co-measurement
H&E image tile and its matching transcriptome profile are a paired sample; 2.2M such pairs collected from spatial omics experiments
Collapse prevention: dual-encoder modal separation
Image encoder and transcriptome encoder are architecturally disjoint; they cannot trivially agree. N×N similarity matrix — only diagonal cells are positive
image embedding RNA embedding
cross-modal pairing · dual encoder · symmetric loss · 2.2M pairs

The split traces back to one root decision — where does the positive pair come from? Concerto generates its own supervision through stochastic dropout on a single modality, so no paired data is ever needed, and collapse is prevented by the architectural asymmetry together with NT-Xent's in-batch negatives. OmiCLIP anchors supervision in biology: two genuinely different physical measurements of the same tissue spot define the positive, and the dual-encoder architecture provides the structural barrier against trivial collapse — but collecting 2.2M matched pairs is the prerequisite the whole approach rests on.

📄 Landmark Papers (2022–2025)

🔵 Instance Discrimination on Single Cells

Concerto: Contrastive learning enables rapid mapping to multimodal single-cell atlas of multimillion scale

2022 Nat Mach Intell scRNA + Protein NT-Xent / Self-Distillation
Asymmetric teacher–student architecture trained with NT-Xent loss on the unit hypersphere. Treats each cell as its own anchor, uses dropout as the only augmentation, and combines modalities by element-wise summation. Scales reference atlases to 10M+ cells with query mapping in seconds.
Why it matters:
  • First major contrastive recipe for single-cell biology
  • 10M cell reference trained in 1.5h on 8 GPUs; 10K query cells mapped in 8s
  • F1 = 0.926 on PBMC45k, beating SciBet, SingleR, Cell BLAST
Concerto asymmetric teacher–student architecture. The same cell is augmented two different ways (dropout-based, no biological augmentation): one view goes through the trainable Student encoder, the other through the Teacher encoder which receives no gradient. The Student's output is pulled toward the Teacher's via NT-Xent contrastive loss; the Teacher's weights are updated by exponential moving average of the Student's. Modalities (RNA + protein) are combined by element-wise summation before the loss. The asymmetry prevents collapse — both encoders sharing weights would degenerate.
Figure 3Concerto — asymmetric teacher–student. Two copies of the encoder, one trains, one drifts slowly. Augment the same cell two different ways, then pull the student toward the teacher — without ever giving the teacher a gradient. This is the same EMA-teacher pattern that later powered DINO in vision and STACK in single-cell biology; Concerto (2022) was the earliest published deployment in single-cell.

📊 Graph Contrastive Learning

GraphST: Spatially informed clustering, integration, and deconvolution of spatial transcriptomics

2023 Nat Commun Spatial RNA DGI / Graph Contrastive
Builds a k-NN spatial graph; the contrastive task pulls each spot's embedding toward a local summary of its neighbors and pushes it away from a corrupted-graph summary. Unifies spatial clustering, multi-sample batch integration, and reference-based cell-type deconvolution in one framework.
Why it matters:
  • ~10% higher clustering ARI than competing methods on DLPFC
  • Only method to recover Layer 6 / WM boundary in human cortex
  • Implicit batch correction (iLISI 1.85 vs 1.57 Harmony)
GraphST graph contrastive workflow. Step 1: build a k-nearest-neighbor spatial graph over spots, with each node carrying the spot's gene-expression vector. Step 2: generate a corrupted graph by shuffling node features across spots (preserves graph structure, destroys the feature–location coupling). Step 3: a GNN encoder processes both graphs. Step 4: DGI objective pulls each spot's embedding toward the real-graph local summary and pushes it away from the corrupted-graph summary. The result: tissue architecture (cortical layers, tumor boundaries) emerges in the embedding for free.
Figure 4GraphST — graph contrastive for spatial tissue. Real graph vs shuffled graph. Build a spatial graph, corrupt it by shuffling node features, train a GNN to tell them apart. Tissue architecture falls out for free. The trick: the only thing the corrupted graph destroys is the spatial-feature coupling, so the model is forced to encode that coupling — which is exactly the tissue-architecture signal.

CellNEST: Cell–cell relay networks via attention on spatial transcriptomics

2025 Nat Methods Spatial CCC GAT + DGI
Casts spatial transcriptomics as a multi-edge graph (cells = nodes, ligand–receptor pairs within distance = edges) and trains a graph attention network with DGI contrastive loss to detect single-cell-resolution communication and multi-hop ligand → receptor → ligand relay cascades.
Why it matters:
  • First method to detect multi-hop CCC relay networks at spot resolution
  • Unsupervised — no ground-truth CCC labels needed
  • Works across Visium, Visium HD, MERFISH, 2D and 3D data
CellNEST multi-hop cell–cell communication relay detection. Spatial transcriptomics is cast as a multi-edge graph: cells are nodes; different edge types correspond to different ligand–receptor pairs within distance. A graph attention network with DGI contrastive loss is trained on real-vs-corrupted graphs. The learned attention weights reveal multi-hop signaling cascades: Cell A → ligand1 → Cell B → ligand2 → Cell C, where Cell B is the relay. Unsupervised — no ground-truth communication labels needed. Works at single-cell resolution on Visium, Visium HD, MERFISH, both 2D and 3D.
Figure 5CellNEST — multi-hop cell–cell communication relays. A signal passes through more than two cells. Different edge types = different ligand–receptor pairs. A graph attention network + DGI detects relay cascades — unsupervised, no comms labels. The multi-hop ligand → receptor → ligand structure is what previous CCC methods missed; CellNEST surfaces it by treating attention weights themselves as the signal.

SpatialEx: High-parameter spatial multi-omics through histology-anchored integration

2025 Nat Methods Spatial Multi-Omics + H&E Hypergraph Contrastive
Uses H&E histology (embedded via the UNI pathology foundation model) as a universal anchor across serial sections. A hypergraph encoder captures group-level cellular interactions, and a contrastive loss between real and shuffled hypergraphs binds local cellular context to a global tissue summary — enabling diagonal multi-omics integration without paired coprofiling.
Why it matters:
  • Hypergraph instead of pairwise edges captures group-level interactions
  • Scales to >1M cells with non-overlapping serial sections
  • Technology-agnostic — both spot and single-cell resolution
SpatialEx hypergraph contrastive integration. Three serial tissue sections — each measured with a different modality (transcriptomics, proteomics, metabolomics) — share H&E histology imaging as their common substrate. SpatialEx builds a hypergraph where hyperedges connect groups of cells via histology features, then trains a hypergraph encoder with contrastive loss between real and shuffled hypergraphs. The result: a single embedding space integrates all three modalities without paired co-profiling — H&E is the Rosetta Stone every section already has.
Figure 6SpatialEx — hypergraph contrastive with histology as anchor. Three serial sections, three different measurements. H&E binds them all. Diagonal integration — no paired co-profiling required. This is the conceptual move that lets one section's RNA align with another section's proteome: anchor every section to its own H&E first, then use the histology embeddings as the bridge.

🔗 Cross-Modal CLIP-Style Models

OmiCLIP: A visual–omics foundation model bridging histopathology and spatial transcriptomics

2025 Nat Methods H&E + Spatial RNA CoCa / Dual-Encoder InfoNCE
ViT image encoder + transcriptome-as-text encoder trained on 2.2M paired image–transcriptome samples curated from 113 Visium studies spanning 32 organs. Top-50 expressed genes per spot are concatenated into "sentences" and aligned with H&E patches via contrastive loss. Powers the Loki platform (alignment, annotation, decomposition, retrieval, prediction).
Why it matters:
  • Largest paired histology–transcriptomics corpus to date (2.2M pairs)
  • Single embedding space unlocks five distinct downstream tasks
  • Bypasses PASTE/GPSA/CAST on tissue alignment benchmarks
OmiCLIP dual-encoder + Loki platform architecture. Left: ViT image encoder processes H&E patches; right: transcriptome-as-text encoder processes top-50-expressed-gene sentences per spot. Both project into a shared 768-d embedding space via symmetric InfoNCE on 2.2M paired samples (113 Visium studies, 32 organs). The resulting joint embedding powers five downstream Loki modules: Align (tissue-section registration), Annotate (cell type), Decompose (deconvolution), Retrieve (image↔omics search), PredEx (gene-expression prediction from H&E alone).
Figure 7OmiCLIP + Loki — dual-encoder alignment, 2.2M paired image–transcriptome pairs. Symmetric InfoNCE on H&E and spatial omics. Five downstream tasks fall out of the joint embedding. The platform model is what makes OmiCLIP useful in practice — once you have a good joint space, Align/Annotate/Decompose/Retrieve/PredEx are all the same retrieval problem with different queries.

CellWhisperer: Chat-based exploration of single-cell data via multimodal learning

2025 Nat Biotechnol Transcriptome + Text InfoNCE + LLM
Frozen Geneformer transcriptome encoder + BioBERT text encoder projected to a shared 2,048-d space via InfoNCE on 1M+ GEO/CELLxGENE profiles paired with Mixtral-curated captions. A fine-tuned Mistral-7B then reasons in natural language over the resulting embedding for zero-shot cell type queries and chat-based atlas exploration.
Why it matters:
  • First chat interface for single-cell data — no coding required
  • Zero-shot cell type annotation across diverse tissues
  • Integrated with CELLxGENE Explorer for visual + conversational workflow
CellWhisperer three-stage pipeline. Stage 1 (Pairing): 1M+ GEO/CELLxGENE transcriptome profiles are paired with Mixtral-generated natural-language captions describing cell type, tissue, condition. Stage 2 (Contrastive Alignment): frozen Geneformer encodes the transcriptome; BioBERT encodes the caption; an InfoNCE loss aligns them in a shared 2,048-d space. Stage 3 (Chat Interface): a fine-tuned Mistral-7B reasons over the resulting embedding for zero-shot cell type queries, natural-language atlas exploration, and free-form Q&A about single cells. The atlas becomes conversational without any coding.
Figure 8CellWhisperer — contrastive alignment then chat interface. Three stages from cells to natural-language atlas exploration: pair cells with captions → contrastive align → bolt a chat model on top. The contrastive alignment is what makes the chat coherent — without it, the LLM has no grounded representation of "this cell". The atlas is suddenly conversational, with no coding required from the biologist.

MedMPT: A vision–language pretrained transformer for clinical respiratory disease

2025 Nat Biomed Eng CT + Radiology Reports Intra + Inter-Modal Contrastive
Trained on 154,274 chest-CT + report pairs with four complementary objectives: intra-modal slice-level / scan-level contrastive (with momentum encoder), inter-modal CT ↔ report contrastive, masked image reconstruction, and cross-modal report generation. Multi-window slice fusion preserves volumetric structure.
Why it matters:
  • Demonstrates intra + inter-modal contrastive stacking on clinical CT
  • 31.75% reduction in radiologist reporting time in human–AI study
  • Covers diagnosis, report generation, and prescription recommendation

Multimodal foundation transformer models for multiscale genomics

2025 Nat Methods Perspective scCLIP / Super Transformer
Perspective organizing transformer-based genomics models into three tiers (unimodal, augmented unimodal, multimodal) and proposing a modular "Super Transformer" architecture. Highlights CLIP-style contrastive objectives as the binding mechanism that lets heterogeneous modalities (DNA, RNA, ATAC, spatial, imaging, text) share one embedding space.
Why it matters:
  • Frames CLIP-style contrastive as the lingua franca of multimodal genomics
  • Practical code-based primers using public datasets
  • Roadmap rather than method — useful for orienting newcomers

🎯 Foundation Models: Contrastive vs. Masked-LM Pretraining

Nicheformer: A foundation model for single-cell and spatial omics

2025 Nat Methods Dissociated + Spatial Masked LM
Transformer pretrained on SpatialCorpus-110M (57M dissociated + 53M spatial cells) using rank-based gene tokenization plus assay/modality/species context tokens. Pretrained with masked language modeling (masked-token prediction) — not a contrastive loss — so spatial context (niche labels, neighborhood composition) can be transferred to scRNA-seq atlases. Included here as the masked-LM counterpoint to the contrastive methods above.
Why it matters:
  • First foundation model jointly trained on dissociated + spatial data
  • 110M cells across 5 spatial technologies + dissociated protocols
  • Demonstrates necessity of multimodal training for spatial tasks

ImmunoStruct: Multimodal deep learning for immunogenicity prediction

2025 Nat Mach Intell Peptide–MHC Structure Supervised Contrastive
Three-tower architecture (sequence VAE + EGNN graph transformer on AlphaFold2 structures + biochemical MLP) for peptide–MHC immunogenicity. A cancer ↔ wild-type contrastive loss explicitly forces immunogenic mutant peptides farther from their wild-type counterparts in latent space — a discrimination cross-entropy alone struggles with.
Why it matters:
  • 26,049-sample multi-allelic structural dataset (27 most common HLAs)
  • Demonstrates value of supervised contrastive for near-identical inputs
  • E(n)-equivariant GNN layers handle 3D coordinates correctly
Why supervised contrastive beats cross-entropy alone for near-identical inputs. Two peptides differ by a single amino acid: a cancer mutant (immunogenic) and its wild-type counterpart (non-immunogenic). Left panel: cross-entropy loss alone — the model is asked to find a thin hyperplane between near-identical input embeddings; the decision boundary is fragile, easily flipped by noise. Right panel: supervised contrastive loss adds an explicit force pushing the cancer-vs-WT pair apart in latent space first; cross-entropy then operates on a much more separated geometry. Contrastive loss makes the room first; the classifier can then easily find the boundary.
Figure 9ImmunoStruct — why supervised contrastive beats cross-entropy alone. When two inputs differ by one amino acid, geometry matters. A thin hyperplane can't separate near-identical inputs; contrastive loss makes the room first. The lesson generalises: any task where the inputs are within an arm's reach of each other (single mutations, allelic variants, time-adjacent timepoints) benefits from a contrastive geometry-shaping step before the classifier.

🧭 Putting Contrastive Learning into Practice

Designing Positive & Negative Pairs

The most important decision is what you call a positive pair — it defines the geometry of the resulting space. Get this wrong and the embedding will collapse onto the wrong invariance.

Pair definition What the embedding learns Typical use
Two views of same cell (dropout / masking) Invariance to noise & technical perturbation Reference mapping, batch correction (Concerto)
Cell + spatial neighborhood Tissue architecture, local context Spatial clustering, niche identification (GraphST, SpatialEx)
Cell + caption / image + transcriptome Cross-modal semantics, zero-shot transfer Retrieval, chat interfaces (OmiCLIP, CellWhisperer)
Same ontology class (supervised) Class-aware geometry, fine-grained discrimination Cell type annotation, immunogenicity (ImmunoStruct)
Graph vs corrupted graph (DGI) Mutual information with local/global summary Spatial / interaction graphs (CellNEST)
Five panels showing the same dataset embedded under five different positive-pair definitions. Panel 1 (augmentation pairs): embedding encodes robustness to noise — same-cell views cluster, no semantic structure. Panel 2 (spatial-neighbor pairs): embedding encodes tissue architecture — niches and cortical layers separate. Panel 3 (cross-modal pairs): embedding encodes shared semantics across image/text/omics — modalities mix, semantics dominate. Panel 4 (class-label pairs): embedding encodes ontology structure — cell types separate cleanly with no within-class structure. Panel 5 (graph DGI pairs): embedding encodes mutual information with neighborhood — local context determines geometry. Same data, five very different latent spaces.
Figure 10Positive-pair choice defines the embedding geometry. Five plots. Same data. Five very different latent spaces. Pick the wrong positive pair and the model encodes the wrong invariance. There is no neutral contrastive objective — the choice of pair definition is the modelling decision, and everything downstream (clustering, retrieval, zero-shot classification) is determined by it.

Common Pitfalls

The InfoNCE temperature parameter τ across three regimes on the unit hypersphere. Cold (τ small, e.g. 0.01): representations concentrate to a few sharp clusters, indistinguishable representations collapse onto each other, useful structure is lost. Warm (τ moderate, e.g. 0.07–0.1): healthy spread on the hypersphere, semantically related points cluster while preserving fine-grained distinctions — this is what Concerto (τ=0.1) and MedMPT (τ=0.07) use. Hot (τ large, e.g. 0.5+): representations dissolve toward uniform on the sphere, contrastive signal washes out, the model can't discriminate. The regime is task-dependent — tune τ on a held-out downstream task.
Figure 11The temperature parameter τ — too cold collapses, too hot dissolves. τ controls the concentration of representations on the unit hypersphere. Three regimes: cold ❄ · warm 🟢 · hot 🔥. Tune it on a downstream task — there is no universal optimum. The published recipes that worked (Concerto τ=0.1, MedMPT τ=0.07) all sit in the warm regime, but the right value depends on batch size, negative-pair difficulty, and the geometry of the desired output space.

When NOT to use contrastive learning

Contrastive learning isn't always the right tool

Skip it when:

  • You need calibrated probabilities or generative samples: VAEs and diffusion models give you these; contrastive embeddings don't.
  • Your dataset is small (<10k samples): Contrastive losses need large batches of negatives to work well; small datasets often do better with supervised cross-entropy or matrix factorization (MOFA+, scVI).
  • You want explicit, interpretable latent factors: NMF, MOFA+, and ICA give factor loadings; contrastive embeddings give a metric space with no axis interpretation.
  • Pair definition is ambiguous: If you can't clearly say what two samples being "similar" means in your problem, a contrastive objective will encode the wrong invariance.
Top-down decision tree for picking contrastive learning vs alternatives. Root: what do you need? Branch A (calibrated probabilities or generative samples): use VAE or diffusion model — not contrastive. Branch B (small dataset, less than 10k samples): use supervised cross-entropy or scVI/MOFA+. Branch C (interpretable factors): use NMF, MOFA+, or ICA. Branch D (clear positive pair available + metric space output desired): use contrastive — and within contrastive, choose by what defines a positive: augmentations (Concerto), spatial neighbors (GraphST), paired modalities (OmiCLIP), class labels (ImmunoStruct), graph corruption (CellNEST). Don't reach for contrastive when something else fits better.
Figure 12Contrastive learning vs alternatives — top-down decision tree. Don't reach for contrastive when something else fits better. Top-down by what you actually need. Contrastive is a good default for one thing — a metric space with a clear notion of similarity — not for everything. If you need calibrated probabilities, generative samples, interpretable factors, or you can't define a positive pair clearly, pick a different tool.

Software & Reproducibility

🛠️ Hands-On Practice

The sections below give you a concrete path from a blank environment to a working contrastive training loop for single-cell data — with the packages, data structures, a runnable snippet, and the pitfalls you'll actually hit.

Environment & packages

Install into a fresh conda or venv environment. lightly wraps common SSL objectives (NT-Xent, MoCo, BYOL) and works with any PyTorch encoder. info-nce-pytorch is a minimal InfoNCE reference implementation. pytorch-lightning handles the training loop boilerplate.

# Python 3.10+
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu118
pip install pytorch-lightning lightly info-nce-pytorch
pip install scikit-learn anndata scanpy
# optional: sentence-transformers for text-side of CLIP-style objectives
pip install sentence-transformers

Hardware. NT-Xent/InfoNCE requires large effective batch sizes (256–2048) to supply enough in-batch negatives; a single A100 (80 GB) handles batch 512 with a 128-D encoder. For CPU-only prototyping, reduce batch to 64 and use a small synthetic dataset — expect slow convergence but correct gradients.

Data structures & formats

Minimal code walkthrough

Define an MLP encoder, build two augmented views of each cell in a batch, compute NT-Xent loss via info_nce, and run one gradient step — a self-contained 25-line training loop.

import torch
import torch.nn as nn
import torch.nn.functional as F
from info_nce import InfoNCE

# --- Encoder: gene counts (G,) -> unit-sphere embedding (D,) ---
class CellEncoder(nn.Module):
    def __init__(self, n_genes: int = 2000, d_emb: int = 128):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(n_genes, 512), nn.BatchNorm1d(512), nn.ReLU(),
            nn.Linear(512, 256),    nn.BatchNorm1d(256), nn.ReLU(),
            nn.Linear(256, d_emb),
        )
    def forward(self, x):
        return F.normalize(self.net(x), dim=-1)  # L2-normalise onto unit sphere

# --- Augmentation: random gene dropout (simulates technical dropout) ---
def augment(x: torch.Tensor, drop_prob: float = 0.2) -> torch.Tensor:
    mask = torch.bernoulli(torch.full_like(x, 1.0 - drop_prob))
    return x * mask

# --- Training step ---
encoder = CellEncoder(n_genes=2000, d_emb=128)
loss_fn  = InfoNCE(temperature=0.1, reduction="mean", negative_mode="unpaired")
optimizer = torch.optim.Adam(encoder.parameters(), lr=1e-3)

# x: (N, G) float32 log-normalised expression for one batch
x = torch.randn(256, 2000).clamp(min=0)   # synthetic placeholder
view1 = augment(x)
view2 = augment(x)
z1 = encoder(view1)   # (N, D)
z2 = encoder(view2)   # (N, D)

loss = loss_fn(z1, z2)  # NT-Xent: pull (z1_i, z2_i) together, push apart from all j != i
optimizer.zero_grad()
loss.backward()
optimizer.step()
print(f"InfoNCE loss: {loss.item():.4f}")   # ~log(N) at init, decreases as pairs align

Common pitfalls & tips