AnyLearn
All lessons
AIadvanced

Contrastive Learning

The first family to make joint-embedding self-supervised learning work: pull together two views of the same image, push apart different images. This lesson covers the InfoNCE loss, SimCLR and its reliance on large batches, MoCo's momentum encoder and queue, why negatives block collapse, and the practical costs that motivated negative-free methods.

Updated · AI-authored, review-gated · how lessons are made

Not signed in: your progress and quiz score won't be saved.
Progress1 / 7

Pull together, push apart

The previous lesson ended on the collapse problem: making two views of an image agree, on its own, lets the model cheat by mapping everything to a constant. Contrastive learning blocks that cheat with a second force.

The idea has two parts working against each other. For a given image, its two augmented views form a positive pair, and their embeddings are pulled together. Every other image in the batch is a negative, and its embedding is pushed apart from the anchor. Attraction alone would collapse; repulsion alone would scatter meaninglessly. Together they carve out a representation where each image sits near its own augmentations and far from everything else. This push-and-pull is the entire mechanism, and it was the first approach to make joint-embedding SSL competitive with supervised pretraining.

Full lesson text

All 7 steps on one page, for reading, reference, and search.

Show

1. Pull together, push apart

The previous lesson ended on the collapse problem: making two views of an image agree, on its own, lets the model cheat by mapping everything to a constant. Contrastive learning blocks that cheat with a second force.

The idea has two parts working against each other. For a given image, its two augmented views form a positive pair, and their embeddings are pulled together. Every other image in the batch is a negative, and its embedding is pushed apart from the anchor. Attraction alone would collapse; repulsion alone would scatter meaninglessly. Together they carve out a representation where each image sits near its own augmentations and far from everything else. This push-and-pull is the entire mechanism, and it was the first approach to make joint-embedding SSL competitive with supervised pretraining.

2. The InfoNCE loss

The objective that implements pull-together-push-apart is InfoNCE (Noise-Contrastive Estimation applied to information). For an anchor embedding, InfoNCE is essentially a classification loss: among the anchor, its one positive, and many negatives, correctly identify the positive by similarity.

Concretely, you compute the similarity of the anchor to its positive and to every negative, scale by a temperature, and apply a softmax-style loss that is minimized when the positive is by far the most similar. A lower temperature sharpens the focus on the hardest negatives. Theoretically, minimizing InfoNCE maximizes a lower bound on the mutual information between the two views, so the shared content survives while view-specific noise is discarded. In practice you do not need the theory to use it: InfoNCE says "the matching view should be the nearest, and all the others should be far," and that is enough to drive strong representations.

3. SimCLR: simple and batch-hungry

SimCLR (Chen and colleagues, 2020) showed how far a clean contrastive recipe could go. Its pipeline is deliberately simple: take an image, apply two strong random augmentations to make the two views, encode each, pass the result through a small projection head (a couple of layers used only during pretraining), and apply the InfoNCE loss.

SimCLR made two findings the field absorbed. First, strong augmentation matters enormously: the combination of random cropping and color distortion is what forces the model to learn semantic content rather than trivial cues. Second, it needs many negatives, and SimCLR gets them from the current batch. That means it depends on very large batch sizes, thousands of images, to supply enough negatives for the loss to bite. That appetite for huge batches, and the compute they require, is SimCLR's main practical limitation, and it directly motivated the next method.

4. MoCo: a queue of negatives

MoCo (Momentum Contrast, He and colleagues, 2020) attacks SimCLR's batch-size problem directly. Instead of drawing negatives only from the current batch, MoCo maintains a queue: a running memory bank of embeddings from many recent batches, giving a large supply of negatives without needing a huge batch.

The catch is consistency. If the encoder changes quickly, embeddings sitting in the queue from earlier steps become stale and mismatched. MoCo's fix is a momentum encoder: a second copy of the encoder whose weights are updated as a slow moving average of the main encoder rather than by gradients. This slowly-changing encoder produces the queued embeddings, keeping them consistent over time. The result is many negatives at a modest batch size. SimCLR and MoCo thus reach the same goal by different routes, batch versus queue, and together they defined the contrastive era of SSL.

5. How negatives block collapse

It is worth stating precisely why negatives solve the problem from the previous lesson. Collapse is the state where every embedding is the same constant vector. But InfoNCE explicitly demands that each negative be dissimilar from the anchor. If all embeddings were identical, every negative would be maximally similar to the anchor, which is exactly what the loss punishes hardest.

So the repulsion term makes collapse the worst possible solution rather than the easiest one.

# InfoNCE, in essence (one anchor)
sim_pos = dot(anchor, positive) / tau
sim_neg = [dot(anchor, n) / tau for n in negatives]
loss = -log( exp(sim_pos) / (exp(sim_pos) + sum(exp(s) for s in sim_neg)) )

The loss shrinks only when the positive is close and the negatives are far. A collapsed encoder, where positive and negatives are equally close, gives the maximum loss. Negatives are, quite literally, the force that holds the representation open.

6. The contrastive setup

One anchor image yields two views; their embeddings are pulled together as a positive pair. Other images, supplied either by a large batch (SimCLR) or a momentum-encoder queue (MoCo), are negatives whose embeddings are pushed away. The InfoNCE loss balances both forces, and the repulsion is what forbids collapse.

flowchart TD
  IMG["Anchor image"] --> V1["View 1"]
  IMG --> V2["View 2"]
  V1 --> Z1["Embedding (anchor)"]
  V2 --> Z2["Embedding (positive)"]
  Z1 -->|"pull together"| Z2
  NEG["Other images: batch (SimCLR) or queue (MoCo)"] --> ZN["Negative embeddings"]
  Z1 -->|"push apart"| ZN
  Z1 --> L["InfoNCE loss"]
  Z2 --> L
  ZN --> L

7. The price of negatives

Contrastive learning works, but negatives carry real costs that shaped what came next:

IssueWhy it hurts
Many negatives neededLarge batches (SimCLR) or a queue and momentum encoder (MoCo) add compute and complexity
Augmentation sensitivityPerformance depends heavily on hand-tuned augmentations
False negativesTwo different images of the same class are pushed apart, even though they should be similar
Tuning burdenTemperature and negative count materially affect results

The false-negative problem is especially awkward: the method blindly treats every other image as a negative, so two different dogs get repelled even though a good representation would place them near each other. These frictions raised a natural question: could you prevent collapse without any negatives at all, keeping only the pull-together half? Answering yes, in more than one way, is the subject of the final lesson.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. In contrastive learning, what forms a positive pair and what are negatives?
    • Positives are two different images; negatives are two views of one image
    • Positives are two augmented views of the same image; negatives are other images
    • Positives are labeled data; negatives are unlabeled data
    • There are no positives, only negatives
  2. What does the InfoNCE loss do?
    • It reconstructs the original image pixels
    • It treats the task as identifying the positive among many negatives by similarity, maximizing a bound on mutual information between views
    • It counts the number of labels in the batch
    • It removes the encoder from the pipeline
  3. What is SimCLR's main practical limitation?
    • It cannot use augmentations
    • It requires very large batch sizes to supply enough in-batch negatives
    • It needs a fully labeled dataset
    • It only works on text
  4. How does MoCo supply many negatives without huge batches?
    • It labels every image by hand
    • It keeps a queue of embeddings from recent batches, produced by a slowly-updated momentum encoder for consistency
    • It uses only positive pairs
    • It reconstructs pixels instead of using negatives
  5. What is the 'false negative' problem in contrastive learning?
    • The loss function returns a negative number
    • Two different images that actually share a class are treated as negatives and wrongly pushed apart
    • Negatives are never used at all
    • The momentum encoder is too fast

Related lessons

AI
advanced

Beyond Negatives: Non-Contrastive and Masked Methods

How to prevent collapse without negative samples. This lesson covers distillation methods (BYOL, SimSiam) that rely on stop-gradients and asymmetry, regularization methods (Barlow Twins, VICReg) that constrain the embedding's statistics, and the masked-modeling family (MAE, BERT), then ties them to JEPA and the energy-based view.

8 steps·~12 min
AI
intermediate

Learning Without Labels: Pretext Tasks

Self-supervised learning turns unlabeled data into its own teacher. This lesson covers why labels are the bottleneck, how a pretext task manufactures free supervision, the shift from predicting pixels to learning embeddings invariant to augmentation, and the collapse problem that every method after it must solve.

8 steps·~12 min
AI
advanced

EBMs as a Unifying Lens

Why LeCun treats energy as the common language of machine learning. This lesson shows how classification, generative models, self-supervised learning, JEPA, and diffusion all read as energy-based models, ties the contrastive-versus-regularized split back to self-supervised learning, and gives an honest account of where explicit EBMs help and where they do not.

8 steps·~12 min
AI
advanced

Building Something That Holds Up

Given that the tradable-signal path is narrow and hard to evidence, the systems worth building are the ones the first lesson identified: extraction at scale. This lesson covers the engineering that makes them survive audit, the evaluation that does not depend on returns, and the governance obligations that apply once a model touches a regulated process.

8 steps·~12 min