To learn good sentence embeddings, we want two things: sentences with the same meaning should get nearby vectors, and sentences with different meanings should get vectors that are far apart. Contrastive learning turns exactly this wish into a training objective: pull positive pairs together, push negatives apart.
This reading introduces the contrastive loss through SimCSE (Gao, Yao & Chen, 2021), a simple method that produces excellent sentence embeddings. We look at its supervised version, which learns from natural language inference data, and its surprising unsupervised version, which needs nothing but raw sentences and dropout.
1The contrastive loss
Like Sentence-BERT, SimCSE uses a pretrained encoder (e.g., BERT) to map each sentence to a vector, and compares vectors with cosine similarity. What differs is how the encoder is trained.
Suppose a training batch contains $N$ positive pairs $(x_i, x_i^+)$: two sentences that should be close (we will see where they come from below). Let $\mathbf{h}_i$ and $\mathbf{h}_i^+$ be their embeddings. For sentence $i$, the loss is
$$\ell_i = -\log\frac{e^{\text{sim}(\mathbf{h}_i,\mathbf{h}_i^+)/\tau}}{\sum_{j=1}^{N} e^{\text{sim}(\mathbf{h}_i,\mathbf{h}_j^+)/\tau}},$$- $\text{sim}(\cdot,\cdot)$ is cosine similarity;
- $N$ is the batch size;
- $\tau$ is a temperature (SimCSE uses $\tau=0.05$).
This loss is often called the InfoNCE loss. Read it as a classification problem: among the $N$ candidates $\mathbf{h}_1^+,\dots,\mathbf{h}_N^+$, which one is the partner of $\mathbf{h}_i$? It is exactly a softmax over the $N$ similarities followed by cross-entropy with the correct answer $j=i$. Minimizing it raises the similarity of the positive pair (numerator) and lowers the similarity to all others (denominator).
In-batch negatives
Where do the negatives come from? We do not need to collect any: for sentence $i$, the partners of the other sentences in the same batch, $\mathbf{h}_j^+$ with $j\neq i$, serve as negatives. A batch of $N$ pairs gives every sentence $N-1$ negatives for free. In matrix form, the $N\times N$ matrix of similarities between $\mathbf{h}_i$ and $\mathbf{h}_j^+$ has the positives on its diagonal, and the loss asks each row's diagonal entry to win its softmax.
bert-base-uncased with mean pooling, and all-MiniLM-L6-v2, a Sentence-Transformers model trained with an in-batch contrastive loss. Green outlines mark positives; every other cell in a row is an in-batch negative. The last column is the loss $\ell_i$ for that row. Click a row to see its softmax.Temperature and batch size
- Temperature $\tau$: cosine similarities lie in $[-1,1]$; dividing by a small $\tau$ stretches them so the softmax can become confident. A smaller $\tau$ makes the softmax sharper and puts more weight on the hardest negatives (those most similar to the anchor).
- Batch size: each sentence has $N-1$ negatives, so larger batches give more (and harder) negatives, which usually helps.
2Supervised SimCSE
Where do good positive pairs come from? Supervised SimCSE uses natural language inference (NLI) datasets such as SNLI (Bowman et al., 2015) and MNLI. Each premise comes with hypotheses labeled entailment, neutral, or contradiction:
| Premise | Hypothesis | Label | Role in SimCSE |
|---|---|---|---|
| A boy is jumping on skateboard in the middle of a red bridge. | The boy does a skateboarding trick. | entailment | positive |
| The boy is wearing safety equipment. | neutral | not used | |
| The boy skates down the sidewalk. | contradiction | hard negative |
- Positive pair: a premise and its entailment hypothesis.
- In-batch negatives: the entailment hypotheses of the other premises in the batch.
- Hard negative: the premise's own contradiction hypothesis. It is about the same scene but means something incompatible, so it is hard to tell apart, and very informative. With hard negatives $\mathbf{h}_j^-$, the denominator gains one more sum: $$\ell_i = -\log\frac{e^{\text{sim}(\mathbf{h}_i,\mathbf{h}_i^+)/\tau}}{\sum_{j=1}^{N}\Big(e^{\text{sim}(\mathbf{h}_i,\mathbf{h}_j^+)/\tau}+e^{\text{sim}(\mathbf{h}_i,\mathbf{h}_j^-)/\tau}\Big)}.$$
Compared with Sentence-BERT, which classifies one pair at a time (or uses one negative per triplet), the contrastive loss compares each sentence against the whole batch at once.
3Unsupervised SimCSE: dropout as augmentation
What if we have no labeled pairs at all, only a large collection of sentences? We need some way to create a positive partner for each sentence. A natural idea is data augmentation: make a slightly altered copy of the sentence, such as masking or deleting a few words (“If [mask] is sunny tomorrow, we [mask] go hiking.”). Surprisingly, SimCSE found that such word-level changes work worse than something much simpler.
Dropout
Dropout (Srivastava et al., 2014) is a standard regularization technique: during training, each neuron is randomly switched off (set to zero) with some probability (0.1 in BERT), using a fresh random pattern on every forward pass. Unsupervised SimCSE uses this randomness as its augmentation:
- Pass the same sentence through the encoder twice, with dropout on.
- Because the dropout masks differ, the two embeddings $\mathbf{h}_i$ and $\mathbf{h}_i^+$ are slightly different. They form the positive pair.
- The other sentences in the batch (their second passes) are the negatives, exactly as before.
The model must learn to map two noisy versions of a sentence close together while keeping different sentences apart. Since the meaning of the sentence is unchanged by dropout, this is a “perfect” augmentation: it adds noise without altering any words.
bert-base-uncased (mean pooling) with dropout switched on, before any contrastive training. Rows: first pass; columns: second pass. The diagonal (same sentence, different dropout masks) is high but not exactly 1; these are the positives. Off-diagonal entries are the in-batch negatives that the training pushes down.4Why does it work? Alignment and uniformity
Recall that raw BERT embeddings are crowded into a narrow cone: almost every pair of sentences has high cosine similarity. The contrastive loss fixes this. Its two parts have two effects (Wang & Isola, 2020):
- Alignment (numerator): positive pairs move close together.
- Uniformity (denominator): all embeddings push away from each other and spread out over the space, so unrelated sentences no longer look similar.
5Results
Average Spearman correlation (×100) over seven STS tasks (numbers from Gao et al., 2021):
| Model | Training data | Avg. STS |
|---|---|---|
| Average GloVe embeddings | none | 61.32 |
| BERT-base (first-last layer average) | none | 56.70 |
| Unsupervised SimCSE-BERT-base | raw sentences only | 76.25 |
| SBERT-base | NLI | 74.89 |
| Supervised SimCSE-BERT-base | NLI | 81.57 |
| Supervised SimCSE-RoBERTa-large | NLI | 83.76 |
- Unsupervised SimCSE, trained without any labels, already beats SBERT, which was trained on labeled NLI data.
- With the same NLI data, the contrastive objective (supervised SimCSE) improves over SBERT's classification objective by almost 7 points.
| Sentence-BERT | SimCSE | |
|---|---|---|
| Objective | classification over NLI labels (or triplet) | contrastive (InfoNCE) with in-batch negatives |
| Negatives per example | none (classification) or one (triplet) | $N-1$ from the batch (+ hard negatives) |
| Labels needed | NLI | NLI (supervised) or none (unsupervised) |
6Contrastive learning beyond sentences
The same loss appears throughout modern AI whenever we want to learn embeddings in which matching things are close:
- Dense retrieval: Dense Passage Retrieval (Karpukhin et al., 2020) trains a question encoder and a passage encoder so that each question is close to the passage containing its answer, with the other passages in the batch as negatives. This is the retrieval step of retrieval-augmented generation.
- Text embedding models: today's general-purpose embedding models are trained contrastively on very large collections of related text pairs (questions and answers, titles and articles, and so on).
- Images and text: CLIP (Radford et al., 2021) trains an image encoder and a text encoder so that each image is close to its caption, using in-batch negatives over hundreds of millions of image–caption pairs.
7Summary
- Contrastive learning pulls positive pairs together and pushes negatives apart.
- The InfoNCE loss is a softmax cross-entropy over the batch: each sentence must pick out its own partner among $N$ candidates.
- In-batch negatives give $N-1$ negatives per sentence for free; temperature $\tau$ controls how sharply hard negatives are emphasized.
- Supervised SimCSE: NLI entailment pairs as positives and contradictions as hard negatives.
- Unsupervised SimCSE: the same sentence passed twice with different dropout masks forms a positive pair, with no labels needed.
- The loss makes embeddings aligned and uniformly spread, fixing the crowded geometry of raw BERT embeddings; the same idea powers dense retrieval and CLIP.
8Practice
Exercise 1: compute the loss
A batch has $N=3$ pairs. For sentence 1, the similarities to $\mathbf{h}_1^+,\mathbf{h}_2^+,\mathbf{h}_3^+$ are $0.8$, $0.3$, $0.1$, and $\tau=0.1$. Compute $\ell_1$. (Use $e^{8}\approx 2981$, $e^{3}\approx 20.1$, $e^{1}\approx 2.72$.)
Exercise 2: negatives
With a batch of 64 pairs and one hard negative per sentence (supervised SimCSE), how many negatives does each sentence have?
Exercise 3: dropout at test time
Unsupervised SimCSE relies on dropout during training. Should dropout be on when we use the trained model to embed sentences?
Quick quiz
9Further reading
- Gao, Yao & Chen (2021). SimCSE: Simple Contrastive Learning of Sentence Embeddings. EMNLP.
- Weng (2021). Contrastive Representation Learning. (From triplet loss to InfoNCE, with many illustrations.)
- Wang & Isola (2020). Understanding Contrastive Representation Learning through Alignment and Uniformity on the Hypersphere. ICML.
- Karpukhin et al. (2020). Dense Passage Retrieval for Open-Domain Question Answering. EMNLP.