Sign in

InfoNCE

Information Noise-Contrastive Estimation loss

An in-batch contrastive loss: each item must pick out its own partner among all the partners in the batch, scored as a classification.

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 ii on one side, the classes are all NN items on the other side, and the correct class is partner ii. The other N−1N - 1 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

  1. Take two batches of embeddings aa and bb of shape (N, D), where row ii of each forms a matching pair.
  2. When normalize is on, scale every embedding to unit length so that dot products are cosine similarities.
  3. Build the N by N matrix of similarities and divide by the temperature. This is what logits returns.
  4. Treat each row as a classification over the columns with the diagonal as the correct class, and take the mean cross-entropy.
  5. When symmetric is on, do the same down the columns and average the two losses.
  6. In backward, the gradient on the logits is softmax minus identity, divided by NN. 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 ln⁡N\ln N, 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 aa rows only with bb 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

IfUse instead
Batches must be small and you can mine hard examplesTriplet loss
Negatives come from a known sampling distribution over a huge catalogueSampled softmax with its correction term
You only have pairs labelled similar or dissimilarContrastive loss

Math foundations

  1. The similarity logits

    Sij=a^i⊤b^jτ,a^i=ai∥ai∥S_{ij} = \frac{\hat{a}_i^{\top}\hat{b}_j}{\tau}, \qquad \hat{a}_i = \frac{a_i}{\lVert a_i \rVert}

    The cosine similarity of every aa with every bb, divided by the temperature. Matching pairs sit on the diagonal.

  2. The loss in one direction

    La→b=−1N∑i=1Nln⁡eSii∑j=1NeSij\mathcal{L}_{a \to b} = -\frac{1}{N}\sum_{i=1}^{N} \ln \frac{e^{S_{ii}}}{\sum_{j=1}^{N} e^{S_{ij}}}

    Cross-entropy over each row with the diagonal as the target. It is small when each aia_i is much more similar to its own bib_i than to any other.

  3. The symmetric loss

    L=12(La→b+Lb→a)\mathcal{L} = \tfrac{1}{2}\big(\mathcal{L}_{a \to b} + \mathcal{L}_{b \to a}\big)

    The same loss with the roles swapped, which normalises over columns instead of rows. Averaging trains both retrieval directions.

  4. Gradient with respect to the logits

    ∂La→b∂Sij=1N(Pij−1[i=j]),Pij=eSij∑keSik\frac{\partial \mathcal{L}_{a \to b}}{\partial S_{ij}} = \frac{1}{N}\big(P_{ij} - \mathbf{1}[i = j]\big), \qquad P_{ij} = \frac{e^{S_{ij}}}{\sum_{k} e^{S_{ik}}}

    Softmax minus one-hot. Each negative is pushed away in proportion to the probability it currently steals, so hard negatives get the most attention.

  5. The link to mutual information

    I(a;b)  ≥  ln⁡N−La→bI(a; b) \;\ge\; \ln N - \mathcal{L}_{a \to b}

    The loss gives a lower bound on the mutual information between the two sides. The bound cannot exceed ln⁡N\ln N, one reason larger batches can help.

Symbols

ai,bia_i, b_i
the i-th matching pair of embeddings
a^i,b^j\hat{a}_i, \hat{b}_j
the embeddings scaled to unit length
SijS_{ij}
the logit comparing a_i with b_j
τ\tau
the temperature, temperature in the config, default 0.07
NN
the batch size, which is also the number of candidates
PijP_{ij}
softmax probability that a_i picks b_j
La→b\mathcal{L}_{a \to b}
the loss when a retrieves b
I(a;b)I(a; b)
the mutual information between the two sides
1[i=j]\mathbf{1}[i = j]
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 τ=0.5\tau = 0.5. Use e−1.4=0.2466e^{-1.4} = 0.2466.

S=(1.80.40.41.8)S = \begin{pmatrix} 1.8 & 0.4 \\ 0.4 & 1.8 \end{pmatrix}
−ln⁡e1.8e1.8+e0.4=ln⁡ ⁣(1+e−1.4)=ln⁡1.2466=0.2204-\ln\frac{e^{1.8}}{e^{1.8} + e^{0.4}} = \ln\!\big(1 + e^{-1.4}\big) = \ln 1.2466 = 0.2204
P11=11.2466=0.8022P_{11} = \frac{1}{1.2466} = 0.8022

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 ln⁡8\ln 8, and inspect logits to see why.

Check on learning

  1. 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 1/N1/N. Compute ln⁡256\ln 256 and use it as a sanity check for a fresh model.

  2. 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.

  3. 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.

  4. 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.

  5. 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 bb that is close to many aa rows: it hurts column-wise and row-wise competition differently.