Topic 57 of 62 · Wider ML toolkit
Contrastive loss (InfoNCE)
MediumHow does the InfoNCE / NT-Xent contrastive loss work, and what roles do positives, negatives, and temperature play?
1 · Start with the intuition
Contrastive learning trains an encoder to map related items (a positive pair, such as a search query and a relevant document, or two augmented views of the same image) close together on the unit hypersphere while pushing unrelated items (negatives) apart. InfoNCE frames this as a multi-class classification problem over the batch: given an anchor embedding zᵢ, treat its positive partner zⱼ as the correct class and all other candidates in the pool as competing wrong classes, then apply cross-entropy to their temperature-scaled cosine similarities.
2 · How the mechanism works
Mechanism step 1 of 3 · no question to answer
Encode (and usually L2-normalize)
Map queries/anchors and candidates to vectors. Retrieval and SimCLR-style setups usually L2-normalize them so the dot product is cosine similarity; InfoNCE itself allows any score function.
Next, we will look at: Scale by temperature τ. Move on when this operation makes sense.
Visualizing the behavior
Cosine similarities for 2 images × 2 views (positives outlined)
Illustrative| anchor ↓ · candidate → | 1a | 1b | 2a | 2b |
|---|---|---|---|---|
| 1a | self | 0.8 | 0.2 | 0 |
| 1b | 0.8 | self | 0.1 | 0.3 |
| 2a | 0.2 | 0.1 | self | 0.7 |
| 2b | 0 | 0.3 | 0.7 | self |
Anchor 1a, scores [0.8 positive, 0.2, 0.0]: effect of temperature
Derivedp(positive) = softmax(s / τ)
3 · The governing equation
sᵢₖ = cᵢₖ / τ, cᵢₖ = zᵢᵀ zₖ, τ > 0 (‖z‖₂ = 1 in the common cosine form)
L_InfoNCE = −log [ exp(sᵢ,pos) / ( exp(sᵢ,pos) + Σ_{k ∈ Neg(i)} exp(sᵢₖ) ) ]
∂L/∂sᵢₖ = pₖ − 1[k = pos], ∂L/∂cᵢₖ = (pₖ − 1[k = pos]) / τ (p = softmax over positive + negatives)
SimCLR (2N views from N images): 1 positive and (2N − 2) negatives per anchorNotation: zᵢ is the anchor representation (L2-normalized in the cosine form used here, a modeling choice rather than part of InfoNCE), cᵢₖ is the raw similarity, pos is its positive partner, Neg(i) is its set of negative candidates, and τ is the temperature hyperparameter.
Look at the gradient with respect to the scaled logits: ∂L/∂sₖ = pₖ − 1[k = pos], where p is the softmax over the positive and all negatives together. The positive gets p_pos − 1 (pulled up) and each negative gets its own pₖ (pushed down), so the push is shared among negatives in proportion to how likely the model currently finds them. With respect to the raw similarities, every term is also divided by τ. A small temperature (e.g., τ = 0.05) sharpens p and so concentrates the push on the hardest negatives (those with the highest cosine similarity to the anchor). That is why mined hard negatives are often valuable for learning fine-grained retrieval boundaries (how much they help depends on the data and how well false negatives are filtered)—but it also creates contrastive learning’s main failure mode: if an unlabeled item in the batch or hard-negative pool is actually relevant to the anchor (a false negative), small τ strongly penalizes the model for ranking a relevant item highly.
4 · Put concrete numbers on it
Worked numbers (from stated assumptions)5 · Common misconception to avoid
Saying “contrastive loss only pulls positives together” (without negatives in the denominator, every input would collapse to the exact same constant vector!), or forgetting to exclude the anchor’s self-similarity from the denominator in symmetric views like SimCLR.
In practice · implementation & engineering rule of thumb
In the cosine-similarity form usual for retrieval, L2-normalize both query and document embeddings before the dot product (a modeling choice, not something InfoNCE requires), and mask out duplicate/same-item rows in the batch so relevant items are never penalized as false negatives.
q = F.normalize(q_emb, p=2, dim=-1)
d = F.normalize(d_emb, p=2, dim=-1)
logits = (q @ d.T) / temperature
# Mask out off-diagonal entries that share the same item/cluster ID:
same_item = (item_ids.unsqueeze(0) == item_ids.unsqueeze(1)) & ~torch.eye(len(q), dtype=torch.bool, device=q.device)
logits = logits.masked_fill(same_item, float("-inf"))
loss = F.cross_entropy(logits, torch.arange(len(q), device=q.device))Go one level deeper
Follow-ups that often come after a correct first answer.
- CLIP uses the same idea across modalities
- For N image–text pairs, compute an N × N similarity matrix and apply cross-entropy along both the rows and the columns, with a learned temperature. The matching caption is the positive; every other caption in the batch is a negative.
- Why more negatives help
- The InfoNCE loss gives a lower bound on mutual information that cannot exceed log N, so more candidates make the task harder and the bound tighter. MoCo keeps a queue of encoded negatives from past batches to get many negatives without a huge batch.
Scenario practice · Choose the loss for the scenario
10 scenarios, ordered Easy → Medium → Hard. Choose the best option, then rate your confidence. A first miss gives a nudge and one retry; a second miss or reveal gives an explanation and zero credit.
Session-only practice. Changing level, leaving, or reloading resets this set.
6 · Self-check & interview synthesis
Explain it in your own words first
Before revealing the reference answer, try answering the opening question aloud in four beats: what it is → how the math works → what trade-off it makes → a concrete number or failure mode.
Follow-up question interviewers often ask next
MediumIn SimCLR, you take a batch of N = 32 images and generate 2 augmented views of each (64 views total). For a single anchor view, how many positives and how many negatives sit in the softmax denominator?
Show follow-up reasoning
Out of the 64 views, 1 is the anchor itself (excluded), 1 is the other augmented view of the same image (the positive), and the remaining 2N − 2 = 62 views from the other 31 images serve as negatives—so the softmax denominator sums over 1 + 62 = 63 terms.