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 · 9 min read ·Core ·Intermediate

Visual quick review

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.

Allowed views define agreement; comparison with declared negatives shapes the representation

Allowed views define agreement; comparison with declared negatives shapes the representationTwo allowed views of one item pass through the same encoder. Training raises their match relative to declared negatives. The unit-length embeddings show an illustrative step, not a fitted result. View choices define which changes should be ignored. The positive remains in the whole candidate set; an undeclared relevant item remains a negative. Negatives oppose collapse, but false negatives can damage the representation.Two allowed views; one shared encoderView AOView POShared encoderAll views and negatives use the sameweights.Before the illustrative updateAPN1N2Positive share: 27.9%After one illustrative updateAPN1N2Positive share: 48.1%Same unit-length scale. The positivegains relative to both negatives.The declared positive belongs tonumerator and denominatorNumerator: declared positive onlyPDenominator: the wholedeclared candidate setPN1N2Same positive identity; negativesremain declared negatives.
Read it this way: Two allowed views of one item pass through the same encoder. Training raises their match relative to declared negatives. The unit-length embeddings show an illustrative step, not a fitted result. View choices define which changes should be ignored. The positive remains in the whole candidate set; an undeclared relevant item remains a negative. Negatives oppose collapse, but false negatives can damage the representation. Is the declared positive excluded from the denominator candidate set?
Full explanation 9 min read

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.

The positive belongs to both numerator and denominator; a false negative stays in the denominator

The positive belongs to both numerator and denominator; a false negative stays in the denominatorA toy InfoNCE example uses unnormalized exponentiated similarity weights four, three, two, and one. One denominator enclosure contains all four candidates. Its positive row has a smaller numerator enclosure and four equal units. The same-class different-source item is still a sampler-negative with three units. The denominator totals ten and the positive probability is four tenths, drawn with ten equal units. Weights are illustrative, not observed similarities.Toy exp(similarity / temperature) weightsijsame item Aanchor croppositive cropDENOMINATOR: ALL FOUR CANDIDATESpositive jsame source A4 in numeratorsampler-negativesource B; same class3negative k1different source2negative k2different source1Denominator = 4 + 3 + 2 + 1 = 10Positive probability = 4 / 10 = 0.4Four of ten equal units belong to the positive.Same-class B stays in the denominator: theloss still repels it.
The nested positive row belongs to both enclosures. Its four units are part of the denominator total of ten. Source B is semantically similar but remains a sampler-negative, so the loss still pushes it away. The weights are illustrative.
Check: Is the positive also in the denominator? Why is a same-class item still repelled?
Reference drawing

Allowed views define agreement; comparison with declared negatives shapes the representation

Allowed views define agreement; comparison with declared negatives shapes the representationTwo allowed views of one item pass through the same encoder. Training raises their match relative to declared negatives. The unit-length embeddings show an illustrative step, not a fitted result. View choices define which changes should be ignored. The positive remains in the whole candidate set; an undeclared relevant item remains a negative. Negatives oppose collapse, but false negatives can damage the representation.Two allowed views; one shared encoderView AOView POShared encoderAll views and negatives use the sameweights.Before the illustrative updateAPN1N2Positive share: 27.9%After one illustrative updateAPN1N2Positive share: 48.1%Same unit-length scale. The positivegains relative to both negatives.The declared positive belongs tonumerator and denominatorNumerator: declared positive onlyPDenominator: the wholedeclared candidate setPN1N2Same positive identity; negativesremain declared negatives.
Derivation
The positive belongs to both numerator and denominator; a false negative stays in the denominatorA toy InfoNCE example uses unnormalized exponentiated similarity weights four, three, two, and one. One denominator enclosure contains all four candidates. Its positive row has a smaller numerator enclosure and four equal units. The same-class different-source item is still a sampler-negative with three units. The denominator totals ten and the positive probability is four tenths, drawn with ten equal units. Weights are illustrative, not observed similarities.Toy exp(similarity / temperature) weightsijsame item Aanchor croppositive cropDENOMINATOR: ALL FOUR CANDIDATESpositive jsame source A4 in numeratorsampler-negativesource B; same class3negative k1different source2negative k2different source1Denominator = 4 + 3 + 2 + 1 = 10Positive probability = 4 / 10 = 0.4Four of ten equal units belong to the positive.Same-class B stays in the denominator: theloss still repels it.
The nested positive row belongs to both enclosures. Its four units are part of the denominator total of ten. Source B is semantically similar but remains a sampler-negative, so the loss still pushes it away. The weights are illustrative.
Check: Is the positive also in the denominator? Why is a same-class item still repelled?
Read it this way: Two allowed views of one item pass through the same encoder. Training raises their match relative to declared negatives. The unit-length embeddings show an illustrative step, not a fitted result. View choices define which changes should be ignored. The positive remains in the whole candidate set; an undeclared relevant item remains a negative. Negatives oppose collapse, but false negatives can damage the representation. Is the declared positive excluded from the denominator candidate set?

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.