Skip to content
mlmentorship

Contrastive and self-supervised learning

Learn useful representations from unlabeled data by defining which views should agree and which examples should stay apart.

Published · 6 min read ·Core ·Intermediate

Visual quick review

Visual first · depth when needed

See that InfoNCE asks an anchor to identify one declared positive among all candidates, so positive and negative sampling choices determine both the learned invariance and false-negative pressure.

Preparing the visual…

Summary

Self-supervised learning creates training targets from the data itself. Contrastive learning is one form: it brings related examples closer in an embedding space and pushes unrelated examples apart.

Why AI labs care

Most available data has no human label. Self-supervised objectives let models learn from text, images, audio, video, code, and interaction logs at large scale.

Examples include:

  • next-token prediction for language models;
  • masked-token prediction for BERT;
  • masked audio prediction for speech models;
  • image reconstruction for masked autoencoders;
  • image-text matching for CLIP;
  • two augmented views of one image for SimCLR.

The hard part is choosing a task that teaches information useful for later work.

Contrastive learning

Let be the embedding of an example. For an anchor , choose a positive example that should have a similar representation. Other examples in the batch act as negatives.

A common loss is InfoNCE:

  • is often cosine similarity.
  • is the temperature. A lower value makes the model focus more on the hardest comparisons.
  • The denominator contains the positive and candidate negatives.

The loss teaches the model to identify the positive among the candidates.

Candidate-set intuition

InfoNCE rewards one declared positive while every other candidate competes with it.

One anchor, one declared positive, and three candidate negatives in InfoNCE An anchor embedding from crop A of one image sits at the left. A solid line connects it to crop B of the same image, the sole declared positive and numerator term. Dashed lines connect the anchor to three other candidates, all included with the positive in the denominator. Two diamond candidates are true negatives. A third diamond is close to the anchor and depicts the same semantic class, but because it came from another source item the sampler labels it negative. A warning states that InfoNCE pushes this false negative away. A summary panel says the positive-pair rule chooses invariance and the candidate sampler chooses repulsion. ONE ANCHOR'S INFONCE CLASSIFICATION TASK ANCHOR i source A · crop 1 PULL TOGETHER POSITIVE j source A · crop 2 the numerator FALSE NEGATIVE source B · same class NEG k₁ NEG k₂ SAMPLER SAYS “different item” LOSS SAYS push away all three sampled items enter the denominator positive rule chooses invariance · sampler chooses repulsion
Read it this way: for anchor i, only the second view of source A is positive j and enters the numerator; that view plus every sampled candidate enters the denominator. If source B is semantically a valid match, the batch still calls it negative and pushes it away; this is the false-negative risk hidden inside the sampling rule. Original schematic informed by SimCLR, CPC, and Debiased Contrastive Learning.

The positive pair defines the representation

A positive pair tells the model which changes should not alter meaning.

Examples:

TaskPositive pairInvariance learned
Image learningTwo crops of one imageCrop, color, and small viewpoint changes
Image-textImage and its captionCross-modal meaning
SearchQuery and relevant documentRelevance
RecommendationUser context and engaged itemPreference under the logging policy
SpeechTwo views of one utteranceNoise or channel changes

A bad positive definition teaches the wrong invariance. If two crops remove the object, the model is asked to match unrelated content. If clicks define positives, position bias becomes part of the representation.

Choosing negatives

Useful negatives are plausible alternatives. Very easy negatives add little signal.

Risks:

  • False negatives: two examples are treated as unrelated even though both are valid matches.
  • Sampling bias: in-batch negatives come from a distribution that may differ from serving traffic.
  • Popularity bias: common items appear as negatives more often and receive different training pressure.
  • Shortcut features: the model separates examples using source, formatting, or language instead of meaning.

Hard-negative mining can help. It can also select mislabeled false negatives. Review mined examples and track performance by slice.

Representation collapse

A collapsed model maps every input to the same vector. It satisfies some similarity goals without learning useful information.

Contrastive negatives prevent the simplest collapse. Other self-supervised methods use stop-gradient paths, predictors, variance constraints, or decorrelation terms instead of explicit negatives.

The goal is not only to avoid identical vectors. A representation can keep enough variance while encoding the wrong features. Evaluate it on the target use.

How to evaluate representations

Use several checks:

  1. Linear probe: freeze embeddings and train a simple linear model.
  2. Retrieval: test whether relevant examples appear near each other.
  3. Transfer: fine-tune with limited labels on a new task.
  4. Robustness: test noise, domain, language, or viewpoint shifts.
  5. Slice analysis: measure rare groups and long-tail items.
  6. Efficiency: measure embedding size, index cost, and serving latency.

A two-dimensional plot is useful for inspection. It is not enough to prove representation quality.

Contrastive versus generative objectives

Contrastive objectives focus on relationships among examples. Generative objectives model the input or missing parts of it.

Use contrastive learning when matching and retrieval are central. Use generative or masked objectives when detailed content and generation matter. Many systems combine both.

In an interview

Use this order:

  1. Define the downstream task.
  2. Define the positive pair and intended invariance.
  3. Explain negative sampling and false-negative risk.
  4. State the loss and role of temperature.
  5. Discuss collapse and shortcut learning.
  6. Evaluate transfer, retrieval, slices, and serving cost.

Common mistakes

  • Saying “use contrastive loss” without defining positives.
  • Treating every other batch item as a true negative.
  • Choosing augmentations that remove task-relevant information.
  • Evaluating only on the pretraining dataset.
  • Assuming larger batches always help.
  • Reading a t-SNE plot as proof of useful clusters.

Related: embedding spaces and similarity, two-tower retrieval, and multimodal foundation models.