How does contrastive learning work?
- User
How does contrastive learning work?
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
How does contrastive learning work?
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Contrastive learning, in one sentence:
“Teach the model to pull together representations of similar things (positives) and push apart representations of dissimilar things (negatives).”
Imagine giving every image (or sentence, audio clip, etc.) a “magnetic” embedding vector.
• Positive pair → should attract each other (small distance, high cosine similarity).
• Negative pair → should repel each other (large distance, low cosine similarity).
If you repeat this game across a big dataset, you carve the embedding space so that semantic neighbors cluster and everything else scatters. A downstream classifier or search system can then work with far fewer labeled examples—or none at all.
| Ingredient | Typical Choice/Example |
|---|---|
| Encoder f(·) | CNN (ResNet), Transformer, Audio conv-net, etc. |
| Data augmentation | Crops, color jitter, token masking, view permutations… |
| Positive pair | Same item under two augmentations (SimCLR) OR text–image caption pair (CLIP) |
| Negatives | Other samples in the batch, a queue (MoCo), or synthetic hard negatives |
| Similarity metric | Cosine similarity or dot product |
| Loss | InfoNCE, NT-Xent, Triplet loss, ArcFace, etc. |
| Temperature τ | A scalar to control softness of the similarity distribution |
Let
• 𝑧ᵢ, 𝑧ⱼ = normalized embeddings of a positive pair
• 𝑁 = batch size (2 augmentations per sample → 2N vectors)
• 𝜏 = temperature
The probability that 𝑧ᵢ matches 𝑧ⱼ among all candidates:
p(i,j) = exp( sim(𝑧ᵢ,𝑧ⱼ)/τ ) / Σ_{k≠i} exp( sim(𝑧ᵢ,𝑧_k)/τ )
Loss for one pair (take the log-likelihood):
ℓᵢⱼ = − log p(i,j)
Total contrastive loss: L = (1/2N) Σ ℓᵢⱼ
Minimizing L maximizes agreement for positives and minimizes it for negatives.
• MoCo (Momentum Contrast): Maintains a moving-average encoder + a queue of past negatives → huge negative set without giant batches.
• BYOL, SimSiam: No explicit negatives! Learn by predicting one view from another + stop-gradient trick.
• CLIP: Cross-modal—aligns text and image embeddings via contrastive loss.
• SupCon: Same loss, but uses labels to define all positives of the same class.
• Debiased Contrastive, Hard-Negative Mining: Address trivial positives/false negatives.
Information theory angle: Maximizing mutual information between two views.
Geometry angle: Encoded points lie on a hypersphere; contrastive loss shapes their angular distances to reflect semantics.
Regularization angle: Heavy augmentations force invariance, acting like data-driven priors.
✅ Big, diverse augmentations (but not so aggressive they change semantics).
✅ Large effective negative set (big batch or memory bank).
✅ Tune temperature τ (typ. 0.05–0.2).
✅ L2-normalize embeddings—prevents collapse.
❌ False negatives (two images of same dog treated as negative) can hurt; label-aware or clustering methods help.
❌ Representation collapse (all z equal) if you drop negatives incorrectly; BYOL avoids via momentum + stop-grad.
def contrastive_step(batch, encoder, tau=0.07):
x1, x2 = augment(batch), augment(batch) # 2 views
z1, z2 = F.normalize(encoder(x1), dim=1), F.normalize(encoder(x2), dim=1)
sim = torch.mm(z1, z2.T) / tau # NxN similarities
labels = torch.arange(len(batch)).to(sim.device)
loss = F.cross_entropy(torch.cat([sim, sim.T], dim=0), # logits
torch.cat([labels, labels], dim=0))
return loss
• Pre-train vision encoders (SimCLR, MoCo v3)
• Zero-shot text-image retrieval (CLIP, ALIGN)
• Audio self-supervision (Wav2Vec 2.0)
• Graph representations (GraphCL)
• Recommendation systems, drug discovery, code search…
🎯 Key takeaway: By converting raw unlabeled data into a supervised signal of “which views belong together,” contrastive learning unlocks powerful representations that generalize across tasks—often rivaling or surpassing fully-supervised pre-training.