Foundations to Frontier
Tests
E. Deep Learning › E2 Loss Functions (one page each)

InfoNCE and NT-Xent

InfoNCE turns representation learning into classification: given a query, pick its one positive out of a set that also contains many negatives, with a softmax over similarities divided by a temperature τ. NT-Xent is the SimCLR version, where the positive is another augmented view of the same image and the rest of the batch supplies the negatives. These losses drive self-supervised learning (SimCLR, MoCo, CLIP) and give a lower bound on mutual information. This page covers the loss, its temperature, the role of negatives and batch size, its information-theoretic meaning, and common pitfalls. In the exercises you implement InfoNCE and NT-Xent, then learn an embedding without labels from two noisy views and find that it lifts nearest-neighbour accuracy from 0.28 to about 0.9, that more negatives helped at every temperature, and that the temperature mattered little for a linear encoder.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Find your partner in a crowd

Take an image and make two altered versions of it, cropped differently or recoloured: the pair is a “positive”. Every other image in the batch is a “negative”. The network embeds all of them, and the loss asks: from this view’s point of view, which of all the others is my partner? Getting this right for every image forces the network to capture what stays the same under the alterations, the content, while ignoring what changes. No labels are needed.

Metric learning: pull same-class points together, push others apart
input spacelearned embedding
1-nearest-neighbour test accuracy: in the embedding 0.880 · in the raw input space 0.940
The two rings and the two blobs are classes; rings are not linearly separable in the input. Contrastive loss pulls same-class pairs to distance 0 and pushes different-class pairs beyond the margin m. Triplet loss only asks each anchor to be closer to a positive than to a negative by m. InfoNCE normalises embeddings onto a circle and asks each anchor to pick its positive out of the batch; lower τ sharpens that choice. With 0 training steps you see the random initial embedding.
Why engineers care

Labelled data are scarce in robotics and aerospace, while unlabelled logs, images and telemetry are plentiful. Self-supervised pre-training with InfoNCE-style losses learns useful features from those unlabelled data. CLIP-style models trained with the same loss on image–text pairs power open-vocabulary detection and language-guided robots.

📝 Quick check (Level 0)
0/3 answered
  1. 1. In SimCLR, a positive pair is…
  2. 2. InfoNCE is essentially…
  3. 3. Does SimCLR need labels?

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • InfoNCE for one query q with positive k⁺ and negatives k⁻ (all normalised): L = −log [exp(q·k⁺/τ) / (exp(q·k⁺/τ) + Σ exp(q·k⁻/τ))].
  • Examples:
    • If all similarities are equal (or τ is huge), L = log(number of candidates): log 4 ≈ 1.386 for one positive and three negatives.
    • If the positive’s similarity is 1 and the negative’s is −1 with τ = 0.05, L = log(1 + e⁻⁴⁰) ≈ 0.
  • NT-Xent (SimCLR): a batch of N images gives 2N views. Each view’s positive is its partner, and its 2N − 2 negatives are the other views: 14 negatives for N = 8 and 8190 for N = 4096.
  • Temperature: a smaller τ sharpens the softmax, concentrating the gradient on the hardest negatives. Common values are 0.07–0.5.
  • Mutual-information bound: I(view₁; view₂) ≥ log(n) − L, with n candidates, so the bound can never exceed log n.
📝 Quick check (Level 1)
0/3 answered
  1. 1. With 1 positive and 15 negatives and equal similarities, InfoNCE is…
  2. 2. Negatives per anchor in NT-Xent with N = 64 images?
  3. 3. A smaller temperature focuses the gradient on…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

InfoNCE in code

Exercise 1.

  • InfoNCE equals the cross-entropy of picking the positive, and tends to log(number of candidates) as τ → ∞.
  • NT-Xent is low (0.126) when the two views coincide and high (6.32) for random embeddings at τ = 0.1.
  • The mutual-information bound log n − L behaves as stated.

Implementation notes.

  1. L2-normalise embeddings before the dot products; the temperature then sets the sharpness.
  2. Mask self-similarities with −∞.
  3. Compute the loss as cross-entropy over the rows of the similarity matrix, with the partner’s index as the label.
  4. SimCLR computes the loss on a projection head’s output and uses the representation before the head for downstream tasks.

More negatives.

  • SimCLR needs large batches (up to 4096) for many negatives.
  • MoCo keeps a queue of past embeddings from a slowly updated (momentum) encoder, to get many negatives cheaply.
  • CLIP uses the image–text pairs of a batch as each other’s negatives.
z = F.normalize(proj(enc(x)), dim=1); S = z @ z.T / tau; S.fill_diagonal_(-1e9)
loss = F.cross_entropy(S, torch.cat([torch.arange(N, 2 * N), torch.arange(N)]))
🐍 Exercise 1: InfoNCE and NT-Xent
Implement InfoNCE for one query, NT-Xent for a batch of paired views, the mutual-information lower bound and normalisation.
📝 Quick check (Level 2)
0/3 answered
  1. 1. MoCo gets many negatives by…
  2. 2. SimCLR uses for downstream tasks…
  3. 3. Self-similarities in NT-Xent are…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Noise-contrastive estimation. InfoNCE (van den Oord, Li and Vinyals, 2018) generalises NCE: the model learns a score f(x, y) such that the true pair can be told apart from n − 1 noise samples. The optimal score is proportional to the density ratio p(y | x)/p(y), and log n − L lower-bounds the mutual information I(x; y). The bound is loose when the true mutual information exceeds log n, which is one argument for many negatives.

Alignment and uniformity. Wang and Isola (2020) decomposed the loss on the sphere into two parts:

  • alignment: positives should map close together;
  • uniformity: embeddings should spread uniformly over the sphere.

The negatives provide the uniformity pressure, preventing collapse.

Temperature. τ controls how strongly the hardest negatives dominate. A small τ approaches a hardest-negative hinge loss; a large τ treats all negatives equally. Too small can make training unstable and penalise semantically similar negatives (false negatives from the same class); too large gives weak uniformity.

What augmentations decide. The representation keeps what is shared between views and discards what the augmentations randomise. Exercise 2’s views kept the informative coordinates and resampled the nuisance, so the embedding learned to ignore the nuisance without labels. Bad augmentations produce useless invariances.

📝 Quick check (Level 3)
0/3 answered
  1. 1. log n − InfoNCE bounds…
  2. 2. Uniformity on the sphere is provided by…
  3. 3. Contrastive representations keep what is…

Level 4: Expert

★★★★★ Expert⏱ 25 minResearchers: original papers and open problems.

Temperature and negatives

History.

  • M. Gutmann and A. Hyvärinen (2010) introduced noise-contrastive estimation.
  • A. van den Oord, Y. Li and O. Vinyals (2018) introduced InfoNCE (CPC).
  • T. Chen et al. (2020) introduced SimCLR and NT-Xent.
  • K. He et al. (2020) introduced MoCo.
  • A. Radford et al. (2021) trained CLIP on 400 million image–text pairs with a symmetric InfoNCE loss.
  • T. Wang and P. Isola (2020) analysed alignment and uniformity.

Exercise 2. The data of E2-10 and E2-11 again: 10 hidden classes in 5 informative dimensions plus 15 nuisance dimensions with standard deviation 3. No labels are used for training. Each view keeps the informative coordinates with small noise and resamples the nuisance completely. A linear 8-D encoder is normalised and trained with NT-Xent for 400 steps. Evaluation is cosine nearest-neighbour accuracy against the hidden labels.

τ batch 8 (14 negatives) batch 64 (126 negatives)
0.05 0.898, 0.896 0.918, 0.938
0.1 0.898, 0.912 0.922, 0.924
0.5 0.898, 0.906 0.926, 0.928
1.0 0.900, 0.902 0.910, 0.928

Raw inputs: 0.276.

  • Label-free learning worked. Accuracy rose from 0.28 to about 0.9, comparable to the label-supervised embeddings of E2-10 and E2-11. The views told the encoder what to ignore.
  • More negatives helped at every temperature and seed, by 1–4 points from batch 8 to 64. A separate native probe with batch 256 (four seeds) added a further 0–2.4 points over batch 64, at about 12 times the cost: diminishing returns.
  • Temperature mattered little here, within about 0.02 at batch 64. With a linear encoder there are few hard negatives to emphasise. The strong temperature sensitivity reported for deep encoders comes from their ability to fit hard negatives, including false ones.
🐍 Exercise 2 (research): temperature and negatives
Learn an embedding without labels with NT-Xent from two views, at temperatures 0.05 to 1 and batch sizes 8 and 64, and measure nearest-neighbour accuracy against the hidden labels.

InfoNCE in AI, robotics and aerospace

  • Self-supervised pre-training on unlabelled flight imagery, robot camera streams or telemetry gives features that need few labels downstream.
  • Vision–language models trained with InfoNCE on image–text pairs (CLIP) enable open-vocabulary detection and language-specified robot goals.
  • Multimodal alignment: contrastive losses align camera, lidar and radar embeddings of the same scene, a basis for sensor fusion and cross-modal retrieval.

References

  1. M. Gutmann, A. Hyvärinen (2010). “Noise-contrastive estimation: a new estimation principle for unnormalized statistical models.” Proc. AISTATS.
  2. A. van den Oord, Y. Li, O. Vinyals (2018). “Representation learning with contrastive predictive coding.” arXiv:1807.03748.
  3. T. Chen, S. Kornblith, M. Norouzi, G. Hinton (2020). “A simple framework for contrastive learning of visual representations.” Proc. ICML.
  4. K. He, H. Fan, Y. Wu, S. Xie, R. Girshick (2020). “Momentum contrast for unsupervised visual representation learning.” Proc. CVPR.
  5. T. Wang, P. Isola (2020). “Understanding contrastive representation learning through alignment and uniformity on the hypersphere.” Proc. ICML.
  6. A. Radford et al. (2021). “Learning transferable visual models from natural language supervision.” Proc. ICML.