Overview
Suppose you have pairs that belong together, such as an image and its caption, or two augmented views of one photo. InfoNCE trains the embeddings so that each item is closer to its own partner than to anyone else's. It does this by setting up a classification problem inside the batch. For item on one side, the classes are all items on the other side, and the correct class is partner . The other serve as negatives for free. The scores are similarities divided by a temperature, and the loss is ordinary cross-entropy with the correct answers on the diagonal.
A short history
Aaron van den Oord, Yazhe Li and Oriol Vinyals introduced InfoNCE in the 2018 paper on contrastive predictive coding, building on the noise-contrastive estimation of Michael Gutmann and Aapo Hyvärinen from 2010. They showed that minimising it maximises a lower bound on mutual information. SimCLR used a variant called NT-Xent for image representations in 2020, and CLIP used a symmetric form in 2021 to align images with text.
How it works
- Take two batches of embeddings and of shape (N, D), where row of each forms a matching pair.
- When
normalizeis on, scale every embedding to unit length so that dot products are cosine similarities. - Build the N by N matrix of similarities and divide by the temperature. This is what
logitsreturns. - Treat each row as a classification over the columns with the diagonal as the correct class, and take the mean cross-entropy.
- When
symmetricis on, do the same down the columns and average the two losses. - In
backward, the gradient on the logits is softmax minus identity, divided by . It is then carried back through the dot product and the normalisation.
Watch out for
- Other rows are assumed to be negatives. If two rows in a batch are in fact the same thing, the loss pushes true matches apart. These are called false negatives.
- Small batches give few negatives and a weak signal. The mutual-information bound the loss provides is capped at , so quality often depends on batch size.
- The temperature has a large effect. Too high and all negatives look alike, too low and a handful of hard negatives dominate with unstable gradients.
- The template compares rows only with rows. SimCLR's NT-Xent also uses the other items of the same view as negatives, so its numbers will differ slightly.
Use cases
When to use it
Self-supervised representation learning and dual-encoder retrieval, such as SimCLR-style pretraining, image and text alignment, and dense passage retrieval.
In industry
- Search and retrieval
- Dense retrieval models train a query encoder and a passage encoder with in-batch negatives, so a question lands near the passages that answer it.
- Image and text matching
- CLIP was trained with a symmetric form of this loss on image and caption pairs, which lets it match photos to text descriptions it has not seen.
- Self-supervised vision
- SimCLR and MoCo learn image features without labels by treating two augmented views of one image as a positive pair.
Choosing it: what must hold
- Positive pairs: two views or two modalities of the same thing, with other batch items serving as negatives.
- Large batches or a memory bank, since the number of negatives strongly affects quality.
- A temperature setting that you tune, and few false negatives among the items in a batch.
When to choose something else
| If | Use instead |
|---|---|
| Batches must be small and you can mine hard examples | Triplet loss |
| Negatives come from a known sampling distribution over a huge catalogue | Sampled softmax with its correction term |
| You only have pairs labelled similar or dissimilar | Contrastive loss |
Math foundations
The similarity logits
The cosine similarity of every with every , divided by the temperature. Matching pairs sit on the diagonal.
The loss in one direction
Cross-entropy over each row with the diagonal as the target. It is small when each is much more similar to its own than to any other.
The symmetric loss
The same loss with the roles swapped, which normalises over columns instead of rows. Averaging trains both retrieval directions.
Gradient with respect to the logits
Softmax minus one-hot. Each negative is pushed away in proportion to the probability it currently steals, so hard negatives get the most attention.
The link to mutual information
The loss gives a lower bound on the mutual information between the two sides. The bound cannot exceed , one reason larger batches can help.
Symbols
- the i-th matching pair of embeddings
- the embeddings scaled to unit length
- the logit comparing a_i with b_j
- the temperature,
temperaturein the config, default 0.07 - the batch size, which is also the number of candidates
- softmax probability that a_i picks b_j
- the loss when a retrieves b
- the mutual information between the two sides
- 1 on the diagonal, otherwise 0
Worked by hand
A batch of two pairs. Matching cosine similarities are 0.9 and mismatched ones are 0.2, with temperature . Use .
Each row gives 0.2204, and by symmetry so does each column, so the loss is 0.2204. Each item picks its partner with probability 0.8022.
Visual example
Loading the example.
Try this
- Move across the curve: the height is what the model is charged.
- Move each control and watch which part of the curve it changes.
Code sample
import numpy as np
from impl import InfoNCE
from config import InfoNCEConfig
loss = InfoNCE(InfoNCEConfig(temperature=0.07))
rng = np.random.default_rng(0)
queries = rng.normal(size=(8, 16)) # (N, D)
documents = queries + 0.1 * rng.normal(size=(8, 16)) # row i matches query i
print(loss.forward(queries, documents)) # near 0: every pair is easy to pick out
print(loss.forward(queries, rng.normal(size=(8, 16)))) # near log(8) or above: no pair structure
g_queries, g_documents = loss.backward(queries, documents)Read the implementation (74 lines)
"""InfoNCE / NT-Xent: in-batch contrastive loss, cross-entropy over the similarity matrix with the matching pairs on
the diagonal.
NumPy only. `forward` returns the loss (a mean over the batch), `backward` its gradients with respect to both
batches of embeddings.
"""
from __future__ import annotations
import numpy as np
try:
from .config import InfoNCEConfig
except ImportError: # run from the template's own folder
from config import InfoNCEConfig
def _log_softmax(z: np.ndarray, axis: int = -1) -> np.ndarray:
"""log(softmax(z)) along `axis`, with the maximum subtracted first so exp cannot overflow."""
shifted = z - z.max(axis=axis, keepdims=True)
return shifted - np.log(np.exp(shifted).sum(axis=axis, keepdims=True))
def _unit(x: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""Rows of x scaled to unit length, and the lengths (N, 1) they were divided by."""
norm = np.maximum(np.sqrt((x**2).sum(axis=1, keepdims=True)), 1e-12)
return x / norm, norm
class InfoNCE:
"""Row i of `a` must pick out row i of `b` among all rows of `b` (and the reverse when symmetric)."""
def __init__(self, config: InfoNCEConfig | None = None) -> None:
self.config = config or InfoNCEConfig()
def _prepare(self, a, b) -> tuple[np.ndarray, ...]:
"""Embeddings as used for the similarity (unit length when normalising), their norms, and the logits."""
a, b = np.asarray(a, dtype=float), np.asarray(b, dtype=float)
if a.ndim != 2 or a.shape != b.shape:
raise ValueError(f"a and b must both have shape (N, D), got {a.shape} and {b.shape}")
(ua, na), (ub, nb) = (_unit(a), _unit(b)) if self.config.normalize else ((a, None), (b, None))
return ua, na, ub, nb, ua @ ub.T / self.config.temperature
def logits(self, a: np.ndarray, b: np.ndarray) -> np.ndarray:
"""Similarity matrix divided by the temperature. a, b: (N, D). Returns (N, N); entry [i, j] compares
a[i] with b[j]."""
return self._prepare(a, b)[4]
def forward(self, a: np.ndarray, b: np.ndarray) -> float:
"""a, b: (N, D) embeddings, a[i] and b[i] being a matching pair. Returns the mean loss as a float."""
logits = self._prepare(a, b)[4]
loss = -np.diag(_log_softmax(logits, axis=1)).mean()
if self.config.symmetric:
loss = 0.5 * (loss - np.diag(_log_softmax(logits, axis=0)).mean())
return float(loss)
def backward(self, a: np.ndarray, b: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""Gradients of the loss with respect to a and b, each (N, D)."""
ua, na, ub, nb, logits = self._prepare(a, b)
n = logits.shape[0]
g_logits = (np.exp(_log_softmax(logits, axis=1)) - np.eye(n)) / n # softmax minus one-hot, per row
if self.config.symmetric:
g_logits = 0.5 * (g_logits + (np.exp(_log_softmax(logits, axis=0)) - np.eye(n)) / n)
g_a, g_b = g_logits @ ub / self.config.temperature, g_logits.T @ ua / self.config.temperature
if self.config.normalize:
# back through x / |x|: remove the part along the unit vector, then divide by the length
g_a = (g_a - ua * (g_a * ua).sum(axis=1, keepdims=True)) / na
g_b = (g_b - ub * (g_b * ub).sum(axis=1, keepdims=True)) / nb
return g_a, g_b
def accuracy(self, a: np.ndarray, b: np.ndarray) -> float:
"""Share of rows of `a` whose most similar row of `b` is their own pair (top-1 retrieval accuracy)."""
logits = self._prepare(a, b)[4]
return float((logits.argmax(axis=1) == np.arange(logits.shape[0])).mean())
__call__ = forward- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 7, run with
python3 -m unittest -v
Practice
Build InfoNCE(InfoNCEConfig(temperature=0.07)). Draw a of shape (8, 16), set b to a plus small noise, and report forward and accuracy. Then shuffle the rows of b and report both again. Compare the shuffled loss with , and inspect logits to see why.
Check on learning
- With random, untrained embeddings and a moderate temperature, what loss do you expect for a batch of 256?
A way to think about it
If no candidate stands out, each has probability about . Compute and use it as a sanity check for a fresh model.
- Your batch contains two different photos of the same dog. What does the loss ask the model to do with them?
A way to think about it
Each is the other's negative. Follow the gradient: it pushes apart two inputs that should be close. Think about how common this is as the batch grows.
- Lowering the temperature from 0.5 to 0.05 multiplies every logit by 10. How does that change which negatives receive gradient?
A way to think about it
Softmax over larger gaps is closer to one-hot on the largest entry. The gradient concentrates on the single most similar negative.
- Why normalise embeddings to unit length before taking dot products?
A way to think about it
Without normalising, the model can raise the diagonal just by making vectors longer. Ask whether that teaches anything about direction, which is what retrieval uses.
- The symmetric option averages two losses that share one logit matrix. When would the two directions give different values?
A way to think about it
One normalises over rows and the other over columns. Picture one that is close to many rows: it hurts column-wise and row-wise competition differently.