Representation learning and contrastive losses
Derive a contrastive objective and examine the assumptions hidden in positive and negative examples.
On this page
The question for today
What you’ll understand
- Compute an InfoNCE-style loss from similarity scores.
- Explain how augmentations define the invariances a representation learns.
- Evaluate embeddings without confusing contrastive training loss with downstream utility.
A representation is useful when it preserves distinctions needed by later decisions. Contrastive learning specifies which observations should be close and which should be distinguishable, then learns features that support that comparison. Its labels may come from paired views rather than human categories, but the pairing process still supplies supervision. Examine that process carefully: an objective can be optimized perfectly while teaching invariances that erase the information a downstream task requires.
Positive pairs make a scientific claim
Two augmented views of one image are often treated as a positive pair. Cropping, color changes, and blur then declare which transformations should leave the representation similar. This is appropriate only when those transformations preserve the relevant semantics. A crop can remove the only diseased region in a medical image; changing color can erase a color-based label. The augmentation policy is therefore part of the task specification, not merely a way to generate more training rows.
An encoder maps an input to a representation, and a projection head maps that representation into the space used by the contrastive loss. Unit normalization makes dot products into cosine similarities. A projection head can absorb loss-specific constraints while leaving an earlier representation useful for transfer. Decide which layer will be evaluated downstream. Measuring only the projection output can answer a different question from measuring the encoder representation used by a deployed classifier.
The denominator defines the competition
A positive score competes with all included candidates through the softmax denominator. Lower temperature sharpens this competition and increases sensitivity to score differences, but it also changes gradient scale and can amplify difficult or mislabeled comparisons. Larger batches provide more in-batch candidates, with greater memory and communication costs. Stored representations from a memory bank can add candidates but may have been encoded by older parameters.
A negative example is not guaranteed to be semantically unrelated. Two different images of the same category can become false negatives if the objective pushes them apart. Duplicate records and correlated observations can also make candidate counts overstate diversity. Distributed training must define whether embeddings are gathered across devices and how gradients through that gather behave. These details change the effective loss; matching only local batch size does not reproduce a global candidate set.
Evaluate what the embedding preserves
A frozen linear probe measures how accessible labels are to a linear classifier with an unchanged encoder. Fine-tuning measures a different capability: how well the representation adapts when all or some parameters may move. Retrieval evaluation depends on the candidate collection, duplicate handling, and relevant-item definition. Report these protocols separately. A lower pretraining loss need not imply better results under every probe or domain shift.
Keep validation and test identities separated when records contain repeated people, products, or documents. Inspect nearest neighbors for shortcuts such as watermarks or acquisition devices. Pairwise similarity matrices require quadratic storage in the number of candidate embeddings if materialized naively; chunking can reduce peak memory while retaining the stated objective. Any approximation, including sampled negatives, should be reported with its sampling distribution. The representation's geometry is a product of both data construction and computation.
Work it through
Calculate one contrastive loss
An anchor has positive similarity 1 and two negative similarities 0 and 0. Use temperature one and natural logarithms.
Exponentiated scores are e for the positive and 1 for each negative, so the denominator is e+2≈4.7183.
The positive probability is e/(e+2)≈0.5761, giving loss −log(0.5761)≈0.5514.
The positive score derivative is 0.5761−1=−0.4239. Each negative derivative is 1/(e+2)≈0.2119; their sum balances the positive derivative.
Gradient descent raises the positive relative to its competitors. A zero loss would require overwhelming relative separation, not merely a positive similarity larger than zero.
The living notebook
Explore the model
Interactive lab · vectors
Inspect angle and projection
The lab shows one two-dimensional vector with angle and magnitude controls and its coordinate projections. Use its angle to reason about alignment with the fixed positive x-axis. It does not learn embeddings, draw candidate sets, or calculate a contrastive objective; cosine similarity between unit vectors is the conceptual connection.
- x component
- 1.393
- y component
- 0.975
- Magnitude
- 1.7
Playback traces a fixed vector and its projections. Angle and magnitude set the geometry; the moving marker does not change them. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.
Look forAngular agreement and vector magnitude are distinct quantities; unit normalization deliberately removes magnitude from a cosine comparison.
Pause & reason
Check your understanding
Your turn
Try it yourself
If one positive and three negatives all have equal similarity, what is the single-anchor contrastive loss? Would decreasing temperature change it while all scores remain equal?
Take a moment to make a prediction or work it out on paper. Open a hint when you need one.
Give me a hint
Every candidate has the same exponential weight regardless of their common score.
Compare with the solution
The positive probability is one-quarter, so the loss is log(4)≈1.3863. Any positive temperature leaves equal logits equally likely, so changing temperature alone does not change this loss. It does change score derivatives by the factor one over temperature, which can alter subsequent learning.
Keep the idea
Take it with you
- Pair construction defines the invariances and distinctions of contrastive learning.
- Temperature and candidate membership are part of the objective.
- Transfer, retrieval, and linear probes test different aspects of representation quality.
Read further
Original sources and deeper explanations to follow at your own pace.
Optional progress, saved in this browser when available. Revisit any lesson at any time.
Lesson not marked complete.