Search

Search papers and lessons

Contrastive Learning

Level 3 · 10 min read

Contrastive learning trains an encoder so that two views of the same item land close together in embedding space while views of different items are pushed apart.

On this page

  • Colour = topic mix
  • Calculus
  • Linear algebra
  • Losses & regularization
  • Neural network basics
  • Discrete math
  • Probability
  • Sign in to see your progress

TL;DR

Contrastive learning trains a model to produce embeddings, which are lists of numbers that describe an input. The training signal is a comparison: two views of the same item should get embeddings that point in nearly the same direction, and views of different items should point in different directions. No human labels are needed. The pairs come from the data itself, usually by applying augmentations to one item twice.

The result is an encoder whose features group similar things together. Those features can then be used for classification, search, or matching with only a small amount of labelled data.

Where you'll see it: in image models that learn from unlabelled photos, in CLIP style models that match pictures to captions, and in retrieval systems that compare a query against millions of candidates.

Intuition

Pulling friends together and pushing strangers apart

Imagine a room of people at a party, and you want to seat them so that people who know each other sit together. You do not know anyone's job or hobby, but you can see that two photos of the same person, taken at different angles and in different lights, are the same person. So you tell the seating planner: put these two photos close, and put every other photo away from them.

That is the whole idea. The "friends" are two augmented views of one image. The "strangers" are the views of all the other images in the batch. The model is never told what a dog is. It learns that a dog photo and its cropped, recoloured twin belong together, and that they belong apart from a photo of a car.

−1−0.500.5101234similarity of the positive pairloss
  • loss for one anchor
One anchor with six negatives at similarity 0, temperature 0.5. As the positive pair becomes more similar, the loss falls toward zero.

Why not just use labels

Labels are expensive. Someone has to look at each image and name it. Contrastive learning gets its supervision from a different question: "which of these items is the same as this one?" The answer is known for free, because we created the pair ourselves. This is the core of Self-Supervised Learning, and it lets a model train on far more data than any labelling budget could cover.

The catch is that the model has to be told what "the same" means. Two crops of one photo are the same item. A photo and its caption are the same item, if the dataset says so. The choice of positive pairs decides what the model learns to ignore and what it learns to keep.

flowchart LR
  A["One image"] --> B["Augmentation 1"]
  A --> C["Augmentation 2"]
  B --> D["Encoder"]
  C --> E["Encoder"]
  D --> F["Embedding z1"]
  E --> G["Embedding z2"]
  F --> H["Pull z1 and z2 together"]
  G --> H
  I["Other images in the batch"] --> J["Push away from z1"]
  F --> J

The math

Setting up the embeddings

Let fθf_\theta be an encoder, such as a Convolutional Neural Network, that maps an input xx to a vector z=fθ(x)\mathbf{z} = f_\theta(x). A small projection head (a couple of extra layers that map the features to the space where the loss is computed) is often applied on top, but the idea is the same.

Similarity is measured by the cosine of the angle between two embeddings. For vectors u\mathbf{u} and v\mathbf{v} it is

sim(u,v)=u⊤v∥u∥ ∥v∥.\mathrm{sim}(\mathbf{u}, \mathbf{v}) = \frac{\mathbf{u}^\top \mathbf{v}}{\lVert \mathbf{u} \rVert \, \lVert \mathbf{v} \rVert}.

Here ∥u∥\lVert \mathbf{u} \rVert is the length of u\mathbf{u}. Dividing by the lengths means only the direction matters, so the score lies between −1-1 (opposite) and 11 (same direction). Normalising the embeddings this way keeps the scores on a fixed scale, whatever the network's raw output size.

The InfoNCE loss

Take a batch of NN images. Each image is augmented twice, which gives 2N2N embeddings. For an anchor embedding zi\mathbf{z}_i, the positive is the other view of the same image, written zj\mathbf{z}_j. All remaining 2N−22N - 2 embeddings in the batch are negatives.

A temperature τ>0\tau \gt 0 controls how sharp the comparison is. The loss for the anchor is

ℓi=−log⁡exp⁡(sim(zi,zj)/τ)∑k≠iexp⁡(sim(zi,zk)/τ).\ell_i = -\log \frac{\exp\big(\mathrm{sim}(\mathbf{z}_i, \mathbf{z}_j) / \tau\big)}{\sum_{k \neq i} \exp\big(\mathrm{sim}(\mathbf{z}_i, \mathbf{z}_k) / \tau\big)}.

The sum in the denominator runs over every other embedding in the batch, including the positive. The fraction is therefore the probability that the softmax over the batch would pick the true positive. The loss is the negative log of that probability, which is exactly the Cross-Entropy Loss of a Softmax classifier whose classes are the other items in the batch. The name InfoNCE comes from that connection, since the loss is a noise-contrastive estimate of mutual information between the two views.

Why temperature matters

Dividing by τ\tau before the softmax changes how peaked the distribution is. A small τ\tau makes the largest similarity dominate. A large τ\tau spreads the probability out. Most practical systems tune τ\tau and find that it matters a great deal.

Random chance as a baseline

If the embeddings carry no information, every candidate has the same probability, 1/(2N−1)1/(2N-1), of being chosen. The loss is then

ℓ=log⁡(2N−1).\ell = \log(2N - 1).

This gives a quick sanity check for a training run. If the loss stays near this value after many steps, the model has not learned to tell pairs apart.

Worked examples

Example
One anchor with two negatives, by hand

Let the anchor be z=(1,0)\mathbf{z} = (1, 0). Its positive is z+=(0.8,0.6)\mathbf{z}^+ = (0.8, 0.6), and it has two negatives, z1−=(0,1)\mathbf{z}^- _1 = (0, 1) and z2−=(−1,0)\mathbf{z}^- _2 = (-1, 0).

  1. Lengths: the anchor and the positive have length 1, because 0.82+0.62=0.64+0.36=1\sqrt{0.8^2 + 0.6^2} = \sqrt{0.64 + 0.36} = 1. The negatives also have length 1.
  2. Cosine similarities: sim(z,z+)=0.8\mathrm{sim}(\mathbf{z}, \mathbf{z}^+) = 0.8, sim(z,z1−)=0\mathrm{sim}(\mathbf{z}, \mathbf{z}^-_1) = 0, and sim(z,z2−)=−1\mathrm{sim}(\mathbf{z}, \mathbf{z}^-_2) = -1.
  3. Take τ=1\tau = 1. The exponentials are e0.8=2.2255e^{0.8} = 2.2255, e0=1e^0 = 1, and e−1=0.3679e^{-1} = 0.3679.
  4. The denominator is 2.2255+1+0.3679=3.59342.2255 + 1 + 0.3679 = 3.5934.
  5. The probability on the positive is 2.2255/3.5934=0.61932.2255 / 3.5934 = 0.6193.
  6. The loss is −ln⁡(0.6193)=0.479-\ln(0.6193) = 0.479.
  7. Now take τ=0.1\tau = 0.1. The scores become 88, 00, and −10-10. The exponentials are e8=2980.96e^8 = 2980.96, 11, and 0.00004540.0000454.
  8. The probability on the positive is 2980.96/2981.96=0.999662980.96 / 2981.96 = 0.99966, and the loss is 0.000340.00034.

Interpretation: the same embeddings give a loss of 0.479 at temperature 1 and almost zero at temperature 0.1. A small temperature makes the model focus on the hardest negatives, which is useful, but it also makes gradients sharp.

Example
A realistic batch: four images, two views each

A training run uses N=4N = 4 images per batch, with two augmented views of each. That gives 8 embeddings.

  1. Each anchor has one positive and 2N−2=62N - 2 = 6 negatives.
  2. The candidate set for each anchor therefore has 1+6=71 + 6 = 7 items.
  3. With no information, every candidate has probability 1/71/7, so the starting loss is ln⁡7=1.946\ln 7 = 1.946.
  4. Suppose after training the positive similarity is 0.9 and the six negatives sit near similarity 0, at temperature τ=0.5\tau = 0.5. The positive has score 0.9/0.5=1.80.9 / 0.5 = 1.8, and each negative has score 0.
  5. The numerator is e1.8=6.050e^{1.8} = 6.050. The denominator is 6.050+6×1=12.0506.050 + 6 \times 1 = 12.050.
  6. The probability on the positive is 6.050/12.050=0.5026.050 / 12.050 = 0.502, so the loss is −ln⁡(0.502)=0.689-\ln(0.502) = 0.689.
  7. That is a drop from 1.946 to 0.689, so the model has begun to separate the pair from the rest of the batch.

Interpretation: with small batches the task is easy, because there are few negatives. Larger batches make the task harder and usually give better features, which is why many methods use large batches or a memory queue of past embeddings.

Tradeoffs and failure modes

Contrastive learning is powerful, but it depends on details that are easy to get wrong.

  • Weak augmentations. If the two views are nearly identical, the model can match them using a shortcut such as colour histograms, and it learns nothing about shape. Strong, varied augmentations force it to find robust features.
  • Too few negatives. With small batches the task becomes trivially easy and the features stay weak. The fix is a larger batch, or a queue that stores embeddings from earlier steps.
  • False negatives. Two different images may depict the same thing, such as two dogs. Treating them as negatives pushes apart things that should be close.
  • Temperature sensitivity. A poor temperature can slow learning or give weaker features. It is worth a sweep.
  • Compute. Each step needs many forward passes through the encoder, and large batches need a lot of memory.
SituationProblemBetter choice
Views differ only by a small cropModel matches shortcutsStronger crops, colour changes, blur
Small batch sizeNegatives too easyLarger batch, or a memory queue
Dataset has many near-duplicatesFalse negativesFilter duplicates, or use a softer loss
Paired image and text availableNo augmentation neededImage-text contrastive loss, as in CLIP
Labels available for a taskContrastive pretraining may be overkillSupervised training, or fine-tuning a pretrained encoder

History

The core idea is older than the deep learning boom. In the early 1990s, Siamese networks compared two inputs through a shared network, for example to check whether two signatures came from the same person. In 2006, Hadsell, Chopra, and LeCun gave a contrastive loss that pulled similar pairs together and pushed dissimilar pairs apart by a margin, which made the approach general.

The modern version came with contrastive predictive coding in 2018, which introduced the InfoNCE loss and used the softmax over a set of candidates as the training objective. It showed that predicting the right future from many distractors gives useful representations of sequences and images.

In 2020, SimCLR showed that a simple recipe, with strong random crops, colour changes, a large batch, and a projection head, could match supervised pretraining on image classification. Its experiments made the role of augmentation clear: the choice of transformations mattered more than many architectural details.

CLIP, in 2021, applied the same loss to pairs of images and captions scraped from the web. Matching each picture to its caption across a large batch produced embeddings that could classify images from text prompts alone, which is the basis of much of the current work on zero-shot vision.

Check yourself

QuestionIn SimCLR style training, what is a positive pair and what is a negative?Show answer

A positive pair is two augmented views of the same image. A negative is an embedding of a different image in the same batch. The model is trained to make positives similar and negatives dissimilar, so the choice of positives defines what counts as the same item.

QuestionA batch has N=16N = 16 images, each with two views. What is the loss of a model that outputs no useful information?Show answer

There are 2N=322N = 32 embeddings, so each anchor has 2N−1=312N - 1 = 31 candidates including its positive. With no information every candidate is equally likely, so the loss is ln⁡31=3.434\ln 31 = 3.434.

QuestionWhy does lowering the temperature make the loss sharper, and what can go wrong if it is too small?Show answer

Dividing the similarities by a small τ\tau amplifies differences between them, so the largest similarity dominates the softmax. The loss then focuses on the hardest negatives and produces large gradients on them. If τ\tau is too small, training can become unstable or focus on a few difficult pairs, so the model learns less from the rest of the batch.

QuestionYou want an encoder for medical scans, but you have only a few hundred labelled scans and many unlabelled ones. Would you use contrastive pretraining, and what would you check first?Show answer

Contrastive pretraining on the unlabelled scans is a reasonable choice, because it needs no labels. The first thing to check is the augmentations. Standard crops and colour changes may destroy diagnostic detail or be implausible for scans, so the transformations must keep the clinically relevant structure. It is also worth checking for near-duplicate scans that would act as false negatives.

Sources