# Contrastive learning explained: InfoNCE, SimCLR and CLIP with worked numbers and PyTorch code

Contrastive learning is how image encoders, CLIP and most text embedding models learn. It pulls matching pairs together and pushes everything else apart. This guide derives the InfoNCE loss, works through the numbers and trains a small encoder in PyTorch.

How does a model learn that a photo of a dog and the words "a dog on a beach" mean the same thing, without anyone labelling what a dog is? Contrastive learning answers that question. It shows the model pairs that belong together and many that do not, and trains it so that matching pairs land close together in an embedding space while non-matching ones land far apart.

This simple idea powers CLIP and the vision encoders inside many multimodal models, the text embedding models behind retrieval-augmented generation, and self-supervised image encoders. This article derives the loss that almost all of them use, InfoNCE, explains the role of temperature and negatives with numbers you can check, and trains a small encoder in PyTorch that learns to ignore noise it was never told about.

## What happened

### open_clip 4.2.2 is released (10 November 2026)

The open_clip library, the most widely used open implementation of CLIP training, published version 4.2.2 on PyPI on 10 November 2026. Its loss module ships `ClipLoss` (softmax InfoNCE), `SigLipLoss` (the sigmoid variant), `CoCaLoss` and `DistillClipLoss`, so one package covers the main contrastive objectives for image and text.

### sentence-transformers 6.3.0 is released (11 November 2026)

sentence-transformers 6.3.0 followed on 11 November 2026. Its `MultipleNegativesRankingLoss`, the standard in-batch contrastive loss for text embeddings, now exposes options for the direction of comparison and a `hardness_mode` that up-weights difficult negatives inside the softmax, citing the weighting used for EmbeddingGemma. Its default `scale` of 20.0 corresponds to a temperature of 0.05.

## The idea: learn by comparison

Contrastive learning needs only a way to say "these two belong together". The pairs can come from anywhere:

- **Two augmented views of the same image**, as in SimCLR: crop, colour-jitter and blur one photo twice. Both views show the same object, so their embeddings should match.
- **An image and its caption**, as in CLIP: 400 million image and text pairs scraped from the web.
- **A question and a passage that answers it**, as in text retrieval models.

Everything else in the batch acts as a negative. A batch of N pairs gives each item one positive and N − 1 negatives for free. Think of a party game where each person must find their partner in a crowded room. You learn what makes your partner distinctive by comparing them to everyone else, not by studying them alone.

The comparison is usually cosine similarity between L2-normalised embeddings, so every embedding lies on a unit sphere and similarity ranges from −1 to 1.

## The InfoNCE loss, step by step

For an anchor embedding a_i and its positive b_i, with all other b_j in the batch as negatives, the InfoNCE loss is

L_i = −log [ exp(sim(a_i, b_i) / τ) / Σ_j exp(sim(a_i, b_j) / τ) ]

This is exactly a softmax cross-entropy where the "classes" are the N candidates in the batch and the correct class is the positive. The temperature τ divides the similarities before the softmax. CLIP uses a symmetric version: it computes the loss for each image against all texts and for each text against all images, then averages the two.

InfoNCE comes from Contrastive Predictive Coding, published by van den Oord and colleagues in 2018, who showed that minimising it maximises a lower bound on the mutual information between the two views: I ≥ log N − L. A larger batch makes the bound higher, which is one reason contrastive methods like big batches.

**Worked example.** Take a batch of three image and text pairs with this cosine similarity matrix, where rows are images, columns are texts and the diagonal holds the true pairs:

| | Text 1 | Text 2 | Text 3 |
|---|---|---|---|
| Image 1 | 0.8 | 0.1 | 0.0 |
| Image 2 | 0.2 | 0.7 | 0.3 |
| Image 3 | 0.0 | 0.4 | 0.9 |

With τ = 1, row 1 gives softmax probabilities proportional to e^0.8, e^0.1 and e^0, which are 2.226, 1.105 and 1.000. The positive gets 2.226 / 4.331 = 0.514, so the loss is −log 0.514 = 0.666. Rows 2 and 3 give 0.823 and 0.700, and the mean is 0.729.

With τ = 0.1 the same similarities become logits of 8, 1 and 0. The positive now gets almost all the probability, and the per-row losses drop to 0.001, 0.025 and 0.007, a mean of 0.011. Temperature controls how sharply the loss separates the positive from the negatives.

## Temperature and negatives: the two knobs that matter

**Temperature.** A low τ makes the softmax sharp, so the gradient focuses on the hardest negatives, the ones with similarity close to the positive. A high τ spreads the gradient over all negatives. Too low and training becomes unstable and over-sensitive to near-duplicates or false negatives. Too high and the model barely separates anything. SimCLR tuned τ as a hyperparameter. CLIP made it learnable, initialised at 0.07 and clipped so the logit scale 1/τ never exceeds 100. Text embedding models commonly use about 0.05, which is the sentence-transformers default scale of 20.

**Negatives.** The loss only learns what the negatives force it to learn. Random in-batch negatives are often easy, so the model stops improving. Three remedies are common. Use larger batches, as SimCLR did with up to 8,192 examples. Keep a queue of recent embeddings as extra negatives, as MoCo did with a momentum-updated encoder. Or mine hard negatives, such as passages that look relevant but do not answer the question, which is standard in retrieval training.

**False negatives** are the flip side. If two captions in a batch both describe dogs on beaches, the loss pushes them apart even though they match. Large batches over diverse data make this rare, but in narrow domains it can hurt.

| Method | Year | Positives | Negatives | Loss | Main idea |
|---|---|---|---|---|---|
| CPC | 2018 | Future vs context | Other samples | InfoNCE | Mutual information bound |
| MoCo | 2019 | Two views | Queue of 65,536 keys | InfoNCE | Momentum encoder and queue |
| SimCLR | 2020 | Two augmented views | In-batch | NT-Xent (InfoNCE) | Strong augmentations, projection head |
| CLIP | 2021 | Image and caption | In-batch, symmetric | InfoNCE | Language as supervision |
| SigLIP | 2023 | Image and caption | All pairs, independently | Sigmoid | No softmax over the batch |

SigLIP replaced the softmax with an independent binary decision for every image and text pair: positive pairs should score high, all others low. Because each pair is scored on its own, the loss does not need a global normalisation across the batch, which makes very large batches cheaper to distribute.

## Runnable code: InfoNCE and a small SimCLR-style encoder

The script first reproduces the worked example. It then builds synthetic data where class information sits in 4 dimensions and loud nuisance noise sits in 16 others. The "augmentation" redraws the nuisance dimensions and slightly jitters the signal, just as cropping and colour jitter change what does not matter in a photo. The encoder is never told the classes. A linear probe with only 40 labels measures how useful the features are.

```python
import torch, torch.nn as nn, torch.nn.functional as F
from sklearn.linear_model import LogisticRegression
torch.manual_seed(0)

def info_nce(a, b, tau=0.1):
    """CLIP-style symmetric InfoNCE: row i of a should match row i of b."""
    a, b = F.normalize(a, dim=-1), F.normalize(b, dim=-1)
    logits = a @ b.T / tau
    target = torch.arange(len(a))
    return (F.cross_entropy(logits, target) + F.cross_entropy(logits.T, target)) / 2

S = torch.tensor([[0.8, 0.1, 0.0], [0.2, 0.7, 0.3], [0.0, 0.4, 0.9]])
for tau in [1.0, 0.1]:
    row_loss = F.cross_entropy(S / tau, torch.arange(3), reduction="none")
    print(f"tau={tau}: per-row loss {[round(v, 3) for v in row_loss.tolist()]}, mean {row_loss.mean():.3f}")

centers = torch.randn(4, 4)
def sample(n):
    y = torch.randint(4, (n,))
    return torch.cat([centers[y] + 0.3 * torch.randn(n, 4), 3 * torch.randn(n, 16)], dim=1), y
def augment(x):
    return torch.cat([x[:, :4] + 0.1 * torch.randn(len(x), 4), 3 * torch.randn(len(x), 16)], dim=1)

enc = nn.Sequential(nn.Linear(20, 64), nn.ReLU(), nn.Linear(64, 16))
opt = torch.optim.Adam(enc.parameters(), lr=1e-3)
Xtr, ytr = sample(2000); Xte, yte = sample(1000)

def probe():
    with torch.no_grad(): ftr, fte = enc(Xtr[:40]).numpy(), enc(Xte).numpy()
    return LogisticRegression(max_iter=2000).fit(ftr, ytr[:40].numpy()).score(fte, yte.numpy())

print(f"probe accuracy before training: {probe():.3f}")
for step in range(500):
    x, _ = sample(256)
    loss = info_nce(enc(augment(x)), enc(augment(x)), tau=0.2)
    opt.zero_grad(); loss.backward(); opt.step()
    if step in (0, 499): print(f"step {step}: InfoNCE loss {loss.item():.3f} (ln 256 = {torch.log(torch.tensor(256.)):.3f})")
print(f"probe accuracy after training:  {probe():.3f}")
```

Output on PyTorch 2.15.0 (CPU):

```text
tau=1.0: per-row loss [0.666, 0.823, 0.7], mean 0.729
tau=0.1: per-row loss [0.001, 0.025, 0.007], mean 0.011
probe accuracy before training: 0.299
step 0: InfoNCE loss 6.160 (ln 256 = 5.545)
step 499: InfoNCE loss 3.754 (ln 256 = 5.545)
probe accuracy after training:  0.997
```

Before training, a random encoder mixes the class signal with the loud nuisance dimensions, and a linear probe on 40 labels manages only 29.9 percent, close to the 25 percent of guessing among four classes. After 500 contrastive steps, the probe reaches 99.7 percent. The encoder learned to keep what stays the same across views and to discard what changes, without ever seeing a class label. The starting loss of 6.160 is above ln 256 = 5.545, the value for uniform guessing, because a low temperature amplifies the random similarities of an untrained network. The [CLIP contrastive learning simulation](/ai-simulations/clip-contrastive-learning) shows the same pull and push on image and text pairs.

## What goes wrong in practice

**Augmentations define what is learned.** The model becomes invariant to whatever the augmentations change. Colour jitter teaches colour invariance, which is wrong if colour is the label you care about.

**Collapse and shortcuts.** If positives can be matched by a trivial cue, such as a shared watermark or the same image border, the model learns the cue. SimCLR found that colour distortion was needed to stop views being matched by colour histograms alone.

**Batch size and memory.** More negatives help, but similarity matrices grow with the square of the batch. Gradient caching, memory queues or the sigmoid loss work around this.

**False negatives in narrow domains.** In a dataset of near-identical product photos or legal clauses, many in-batch "negatives" are really positives. Deduplicate and consider filtering negatives by similarity.

**Projection heads.** SimCLR found that features before the final projection head transfer better than those after it, because the head discards information the loss does not need. Probe both.

## How it is used in today's models

Contrastive objectives sit inside much of today's AI stack. CLIP-style and SigLIP-style encoders give multimodal language models their vision, and the same encoders power zero-shot image classification and image search. Text embedding models for retrieval are trained with in-batch and hard-negative InfoNCE on question and passage pairs, often after self-supervised pretraining, and their quality is what makes retrieval-augmented generation work. Matryoshka training adds the same contrastive loss at several embedding sizes so vectors can be truncated cheaply. Rerankers and recommendation systems use contrastive losses to compare users with items. On this site, see how [embedding models are chosen and measured](/articles/embedding-models-for-rag-choose-measure) and how [Matryoshka embeddings and binary quantisation shrink vector search](/articles/matryoshka-embeddings-binary-quantisation-rescoring).

## What it means in practice

Contrastive learning converts "these belong together" into a training signal. Its quality depends less on the network than on three choices: what counts as a positive, where negatives come from and what temperature sharpens the comparison. If you fine-tune an embedding model for your domain, mining good hard negatives and checking for false negatives usually matters more than any architectural change.

It also explains behaviour you may already have seen. An embedding model that ranks a passage on the right topic above the passage that answers the question was probably trained mostly on easy negatives. A CLIP-based classifier that confuses two similar products was never forced to separate them during training. In both cases the fix is the same: show the model those exact confusions as negatives and train again with a modest learning rate.

## What to do now

1. **Start from a pretrained encoder.** Fine-tune an existing CLIP, SigLIP or text embedding model rather than training from scratch.
2. **Define positives carefully.** Make sure each pair truly matches and that nothing trivial, such as a shared template, gives it away.
3. **Use in-batch negatives first.** `MultipleNegativesRankingLoss` or `ClipLoss` with the largest batch your memory allows is a strong baseline.
4. **Add hard negatives.** Mine near-misses with your current model or BM25 and add them as explicit negatives.
5. **Tune temperature.** Try values around 0.05 to 0.1 for text and let it be learned for image and text pairs.
6. **Check for false negatives.** Inspect the most similar in-batch negatives and drop or relabel true matches.
7. **Evaluate on your task.** Measure retrieval recall, nDCG or a linear probe on your own data, not only on public leaderboards.
8. **Consider the sigmoid loss for scale.** For very large distributed batches, SigLIP-style losses avoid a global softmax.

## Risks and open questions

**Web pairs carry web biases.** CLIP-style models trained on scraped captions inherit stereotypes and gaps in that data, which then flow into downstream classifiers and multimodal models.

**Benchmarks overlap with training pairs.** Large scraped datasets may contain test images or near-copies, which can inflate zero-shot scores.

**Hardness weighting is still empirical.** How strongly to up-weight hard negatives, and when it starts to amplify label noise, is settled per dataset rather than by theory.

**Watch next:** how hardness-weighted contrastive losses in sentence-transformers 6.3 change open embedding model quality, and whether sigmoid-style losses replace softmax InfoNCE for text as they have for many vision encoders.

## Frequently asked questions

### What is the difference between contrastive and self-supervised learning?

Contrastive learning is one way to do self-supervised learning, by comparing pairs. Other self-supervised methods predict masked tokens or pixels instead. Contrastive losses are also used with supervised pairs, such as labelled question and answer pairs for retrieval.

### Why does the batch size matter so much?

Each example's negatives come from the rest of the batch, so a larger batch means more and harder comparisons per step. InfoNCE's mutual information bound also grows with log N. Methods such as MoCo's queue and SigLIP's sigmoid loss reduce the dependence on huge batches.

### What temperature should I use?

Common values are about 0.05 for text embedding models and 0.07 as a starting value for learnable CLIP temperature. Lower values focus on hard negatives but can be unstable. Treat it as a hyperparameter and check validation retrieval quality.

### What is a hard negative?

A hard negative is a non-matching example that the model currently finds very similar to the anchor, such as a passage on the right topic that does not answer the question. Training on hard negatives teaches finer distinctions than random negatives. Check them carefully, because some will be unlabelled true positives.

### How is CLIP's loss different from SimCLR's?

Both use InfoNCE. SimCLR compares two augmented views of the same image within one encoder. CLIP compares images with captions using two encoders and averages the loss in both directions. CLIP also learns its temperature.

## Summary

Contrastive learning trains embeddings by making matching pairs more similar than every other pair in the batch. The InfoNCE loss is softmax cross-entropy over similarities divided by a temperature. In the worked example, three pairs gave a mean loss of 0.729 at τ = 1 and 0.011 at τ = 0.1. A small encoder trained with InfoNCE learned to ignore nuisance noise and lifted a 40-label linear probe from 29.9 to 99.7 percent. SimCLR, MoCo, CLIP and SigLIP differ mainly in where positives and negatives come from. Read more on [contrastive learning](/tools/contrastive-learning), [InfoNCE](/tools/infonce), [CLIP](/tools/clip) and [SimCLR](/tools/simclr), or explore the [embedding space simulation](/ai-simulations/embedding-space).

## Sources

- [arXiv: A Simple Framework for Contrastive Learning of Visual Representations, SimCLR (Chen et al., 2020)](https://arxiv.org/abs/2002.05709)
- [arXiv: Learning Transferable Visual Models From Natural Language Supervision, CLIP (Radford et al., 2021)](https://arxiv.org/abs/2103.00020)
- [arXiv: Representation Learning with Contrastive Predictive Coding (van den Oord et al., 2018)](https://arxiv.org/abs/1807.03748)
- [arXiv: Momentum Contrast for Unsupervised Visual Representation Learning, MoCo (He et al., 2019)](https://arxiv.org/abs/1911.05722)
- [arXiv: Sigmoid Loss for Language Image Pre-Training, SigLIP (Zhai et al., 2023)](https://arxiv.org/abs/2303.15343)
- [Sentence Transformers: Loss functions reference](https://sbert.net/docs/package_reference/sentence_transformer/losses.html)
- [PyPI: sentence-transformers 6.3.0](https://pypi.org/project/sentence-transformers/6.3.0/)
- [PyPI: open-clip-torch 4.2.2](https://pypi.org/project/open-clip-torch/4.2.2/)
