CSCE 471 Natural Language Processing · Spring 2027

Contrastive Learning

Kuan-Hao Huang · Course Website

Note: This page was created with the help of AI as a supplementary reading. It may contain errors or simplifications. The lecture slides are the primary reference for this course; please refer to them first.

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.

After reading this, you should be able to state the idea of contrastive learning · write down the contrastive (InfoNCE) loss and explain each symbol · explain in-batch negatives · describe how supervised SimCSE builds positive and hard negative pairs from NLI data · explain how unsupervised SimCSE uses dropout to create positive pairs · explain the effect of the temperature and batch size · connect contrastive learning to retrieval

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}},$$

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.

Encoder:Temperature $\tau$:
Figure 1 (interactive). A batch of five NLI (premise, entailment) pairs. Cells are cosine similarities $\text{sim}(\mathbf{h}_i,\mathbf{h}_j^+)$ computed with real models: 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

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:

PremiseHypothesisLabelRole in SimCSE
A boy is jumping on skateboard in the middle of a red bridge.The boy does a skateboarding trick.entailmentpositive
The boy is wearing safety equipment.neutralnot used
The boy skates down the sidewalk.contradictionhard negative

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:

  1. Pass the same sentence through the encoder twice, with dropout on.
  2. Because the dropout masks differ, the two embeddings $\mathbf{h}_i$ and $\mathbf{h}_i^+$ are slightly different. They form the positive pair.
  3. 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.

Figure 2. Real cosine similarities between two forward passes of 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):

Temperature $\tau$:
Figure 3 (interactive). A toy contrastive training run with eight sentences in a 2-D embedding space (unit vectors). Each sentence has two views (same color, filled and hollow), as with dropout. They start crowded in a narrow cone, like pretrained BERT embeddings. Gradient descent on the InfoNCE loss pulls each pair together (alignment) and spreads the pairs around the circle (uniformity).

5Results

Average Spearman correlation (×100) over seven STS tasks (numbers from Gao et al., 2021):

ModelTraining dataAvg. STS
Average GloVe embeddingsnone61.32
BERT-base (first-last layer average)none56.70
Unsupervised SimCSE-BERT-baseraw sentences only76.25
SBERT-baseNLI74.89
Supervised SimCSE-BERT-baseNLI81.57
Supervised SimCSE-RoBERTa-largeNLI83.76
Sentence-BERTSimCSE
Objectiveclassification over NLI labels (or triplet)contrastive (InfoNCE) with in-batch negatives
Negatives per examplenone (classification) or one (triplet)$N-1$ from the batch (+ hard negatives)
Labels neededNLINLI (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:

7Summary

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$.)

Divide by $\tau$: $8, 3, 1$. Softmax probability of the positive: $2981/(2981+20.1+2.72)\approx 0.992$. Loss $\ell_1=-\log 0.992\approx 0.008$. With $\tau=1$ instead, the probability would be only $e^{0.8}/(e^{0.8}+e^{0.3}+e^{0.1})\approx 0.48$, and the loss $\approx 0.74$.

Exercise 2: negatives

With a batch of 64 pairs and one hard negative per sentence (supervised SimCSE), how many negatives does each sentence have?

$63$ in-batch positives of other sentences, plus the $64$ hard negatives in the batch (its own and the other sentences'), for $127$ negatives in total. The denominator has $128$ terms, one of which is the positive.

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?

No. As usual, dropout is turned off at inference so that each sentence gets one deterministic embedding. Dropout is only used during training to create the two noisy views.

Quick quiz

9Further reading