AI Logic

Loss Functions

InfoNCE

Updated๏ผš

Diagram of InfoNCE. On the left, an example candidate set X (N = 8) placed on a plane: the arrow from the origin is the prediction from the context W_k c_t, the light-blue point is the positive z_{t+k}, and the navy points 1โ€“7 are negatives. The score is the inner product zแต€W_k c_t. On the right, a bar chart of the probability of choosing each candidate as the positive, obtained by applying a softmax to the scores; the positive's probability is 0.34 and the loss is โˆ’log 0.34 = 1.08. Legend and formula at the far right

Background and Overview

InfoNCE is a loss function defined as the cross-entropy of a classification problem that picks out the positive from NN candidates consisting of one positive and Nโˆ’1N-1 negatives. van den Oord, Li, and Vinyals (2018, DeepMind) proposed it as part of Contrastive Predictive Coding (CPC), a method for learning representations without labels. The form of the loss is based on Noise-Contrastive Estimation (NCE), a way of learning probabilistic models by comparing samples against each other.

In CPC, the representation zt+kz_{t+k} kk steps ahead is predicted from a context ctc_t that summarizes a sequence up to time tt. The candidate set X={x1,โ€ฆ,xN}X = \{x_1, \dots, x_N\} contains one true future (the positive) and Nโˆ’1N-1 negatives drawn from elsewhere. The loss is:

LN=โˆ’โ€‰EX[logโกfk(xt+k,ย ct)โˆ‘xjโˆˆXfk(xj,ย ct)],fk(x,ct)=expโกโ€‰โฃ(zโŠคWkโ€‰ct)\mathcal{L}_N = -\,\mathbb{E}_X \left[ \log \frac{f_k(x_{t+k},\ c_t)}{\sum_{x_j \in X} f_k(x_j,\ c_t)} \right], \qquad f_k(x, c_t) = \exp\!\left( z^\top W_k\, c_t \right)

fkf_k is a score expressing how likely a candidate is to be the positive, zz is the representation of candidate xx produced by the encoder, and WkW_k is a matrix kept separately for each prediction step kk. The fraction is the softmax of the scores, giving "the probability that this candidate is the positive." The figure at the top shows how probabilities are computed from the scores of 8 candidates and how the โˆ’logโก-\log of the positive's probability becomes the loss.

The paper shows that minimizing InfoNCE corresponds to maximizing a lower bound on the mutual information between the context ctc_t and the future xt+kx_{t+k}. Much of the later contrastive learning inherits this form: NT-Xent in SimCLR replaces the score with cosine similarity and a temperature, and Supervised Contrastive further allows multiple positives.

Theory (Computing the Loss)

CPC computes InfoNCE in the following steps.

  1. The encoder gencg_{\text{enc}} turns the input sequence xtx_t into a sequence of representations zt=genc(xt)z_t = g_{\text{enc}}(x_t).
  2. An autoregressive model garg_{\text{ar}} (a GRU in the paper) summarizes zโ‰คtz_{\le t} up to time tt into a context ct=gar(zโ‰คt)c_t = g_{\text{ar}}(z_{\le t}).
  3. For each step kk ahead, it forms the prediction WkctW_k c_t.
  4. It gathers the true zt+kz_{t+k} (the positive) and Nโˆ’1N-1 zz's taken from other time steps or other sequences (the negatives) into the candidate set XX.
  5. It applies a softmax to each candidate's score zjโŠคWkctz_j^\top W_k c_t and uses the โˆ’logโก-\log of the positive's probability as the loss. The loss is averaged over time steps tt and steps kk, and the encoder and the autoregressive model are trained jointly.

For example, with N=4N = 4 candidates whose scores are 22 for the positive and 1,ย 0,ย 01,\ 0,\ 0 for the negatives, the positive's probability is e2/(e2+e1+e0+e0)โ‰ˆ0.610e^2 / (e^2 + e^1 + e^0 + e^0) \approx 0.610, and the loss is โˆ’logโก0.610โ‰ˆ0.49-\log 0.610 \approx 0.49. The closer the negatives' scores are to the positive's, the lower the probability and the larger the loss.

The paper describes this loss as "the categorical cross-entropy of classifying the positive sample correctly." If the list of scores is treated as logits and the position of the positive as the target class, the computation is the same as ordinary NN-class cross-entropy. In PyTorch, it can be passed directly to F.cross_entropy.

The score function fkf_k can be any positive function and does not need to be normalized as a probability. As the simplest choice, CPC uses the exponential of the inner product between the representation and the prediction, expโก(zโŠคWkct)\exp(z^\top W_k c_t) (a log-bilinear model).

Why Identifying the Positive Teaches Representations

The key point of InfoNCE is that it extracts only the information shared by the context and the future, without generating the future itself.

The paper first points out how hard it is to predict high-dimensional data directly. An image carries thousands of bits of information, whereas high-level information such as a class label carries only 10 bits even with 1,024 classes. Trying to reproduce every detail with something like mean squared error spends much of the model's capacity on reproducing details unrelated to the context. CPC therefore maps xx (the future) and cc (the context) to representations and trains them to preserve as much as possible of their mutual information

I(x;ย c)=โˆ‘x,ย cp(x,c)logโกp(xโˆฃc)p(x)I(x;\ c) = \sum_{x,\ c} p(x, c) \log \frac{p(x \mid c)}{p(x)}

There are two reasons InfoNCE connects to this.

  • The optimal score is a density ratio: The score that minimizes the loss is fk(xt+k,ct)โˆp(xt+kโˆฃct)/p(xt+k)f_k(x_{t+k}, c_t) \propto p(x_{t+k} \mid c_t) / p(x_{t+k}) (Eq. (5) of the paper). It is the ratio of "how much more likely that future becomes given the context," and does not depend on the number of negatives Nโˆ’1N-1. Training only needs to compare samples drawn from these distributions (positives and negatives), without computing p(x)p(x) or p(xโˆฃc)p(x \mid c) directly.
  • The loss value gives a lower bound on mutual information: I(xt+k;ย ct)โ‰ฅlogโกNโˆ’LNI(x_{t+k};\ c_t) \ge \log N - \mathcal{L}_N holds. The lower the loss, the higher the bound, and the larger NN, the tighter (closer to the true value) the bound. For the numerical example above (N=4N = 4, loss 0.490.49), the bound is logโก4โˆ’0.49โ‰ˆ0.89\log 4 - 0.49 \approx 0.89 nats.

As an analogy, it is an NN-choice quiz asking "Which of these continues this passage?" To pick the right answer, grasping information shared across the passage, such as the flow of the story, helps more than memorizing fine wording. The paper notes that the farther ahead the prediction, the less information is shared, so the model must capture larger structures (phonemes and intonation in speech, objects in images).

Because the loss cannot go below 0, the mutual information that can be estimated as logโกNโˆ’LN\log N - \mathcal{L}_N is at most logโกN\log N. When the true mutual information is large, the bound cannot reach the true value unless the number of candidates NN is increased. The paper likewise notes that a larger NN tightens the bound, so using a large NN is beneficial.

Experimental Results

The CPC paper evaluates representations learned with InfoNCE in four domains: speech, images, natural language, and reinforcement learning. The basic protocol freezes the representation and trains only a linear classifier on top (linear evaluation).

Domain and taskCompared methodsCPC
Speech (LibriSpeech) phone classification, 41 classesRandom initialization 27.6%, MFCC 39.7%, supervised 74.6%64.6%
Speech (LibriSpeech) speaker classification, 251 classesRandom initialization 1.87%, MFCC 17.6%, supervised 98.5%97.4%
Images (ImageNet) linear evaluation, top-1Colorization (ResNet-V2) 39.6%48.7%
Images (ImageNet) linear evaluation, top-5Combination of four self-supervised methods 69.3%73.6%
Natural-language sentence classification (MR๏ผCR๏ผSubj๏ผMPQA๏ผTREC)Skip-thought 75.5๏ผ79.3๏ผ92.1๏ผ86.9๏ผ91.476.9๏ผ80.1๏ผ91.2๏ผ87.7๏ผ96.8

For speech phone classification, the paper also compares how many steps ahead to predict and how to draw negatives.

ConditionPhone classification accuracy
Predict up to 2 steps ahead28.5%
Up to 4 steps ahead57.6%
Up to 8 steps ahead63.6%
Up to 12 steps ahead64.6%
Up to 16 steps ahead63.8%
Negatives from mixed speakers64.6%
Negatives from the same speaker65.5%
From mixed speakers, excluding the current sequence57.3%
From the same speaker, excluding the current sequence64.6%
Only from within the current sequence65.2%

Predicting only the near future (2 steps) yields almost useless representations, showing that predicting multiple steps ahead matters. In reinforcement learning (five DeepMind Lab tasks), adding InfoNCE as an auxiliary loss to A2C training substantially improved performance on four of the five tasks.

These are results for CPC as a whole (encoder, autoregressive model, data augmentation, and so on), not comparisons of InfoNCE alone against other losses under identical conditions.

Practical Considerations

The number of negatives and how they are drawn change what representations are learned. With few negatives, the mutual information bound logโกNโˆ’LN\log N - \mathcal{L}_N saturates at logโกN\log N. Also, as in the table above, excluding the current sequence when drawing negatives from mixed speakers lowered accuracy from 64.6% to 57.3% (the paper does not explain why in detail). Where negatives come from needs to be verified for each task.

Keep the following points in mind as well.

  • Always include the positive among the candidates: The sum in the denominator includes the positive. Without it, the expression is not a probability, and neither the loss value nor the bound holds.
  • Using other examples in the mini-batch as negatives is convenient: In CPC's speech experiments, negatives are drawn from each GPU's mini-batch (8 examples). Building a Bร—BB \times B score matrix from BB contexts and BB positives in the batch makes the diagonal the positives and everything else the negatives.
  • Watch the magnitude of the scores: expโก(zโŠคWkct)\exp(z^\top W_k c_t) overflows quickly when the inner product is large. Do not compute the exponential yourself; pass the logits as they are to F.cross_entropy (which computes log-sum-exp stably internally).
  • The name is used loosely: The NT-Xent form, which uses cosine similarity and a temperature, is also widely called "InfoNCE." When reading papers or code, check the score function (inner product or normalized cosine similarity) and whether a temperature is used.
  • PyTorch has no dedicated class: Build the logit matrix and the positions of the positives, and pass them to F.cross_entropy.

Comparison with Other Methods

The table below compares InfoNCE with other losses that learn embeddings by contrasting positives and negatives, from the same viewpoints.

Loss functionNumber of positivesNegativesScore (similarity)How they are comparedMain uses
InfoNCE1Nโˆ’1N-1expโก(zโŠคWkct)\exp(z^\top W_k c_t) (unnormalized inner product)Softmax over NN candidatesSelf-supervised learning that predicts the future from context, such as CPC
NT-Xent1 (another view of the same image)2(Nโˆ’1)2(N-1) in the mini-batchCosine similarity รท temperature ฯ„\tauSame as aboveSelf-supervised image learning such as SimCLR
Supervised ContrastiveAll with the same labelAll with a different labelCosine similarity รท temperature ฯ„\tauSame as above (averaged per positive)Representation learning for labeled classification
Contrastive LossPer pairPer pairEuclidean distanceDistance and marginDeciding whether two inputs are the same
Triplet Loss11Squared distanceDistance gap and marginFace verification, image retrieval

Rough guidelines for choosing among them:

  • If there are no labels and you only know which pairs "come from the same thing," use the InfoNCE form: InfoNCE (CPC) is the representative choice for adjacent parts of a sequence, and NT-Xent for two views of an image.
  • If you want to compare many negatives at once, use the softmax form: Contrastive Loss and Triplet Loss compare only one or two items at a time and need separate tricks to select informative pairs. InfoNCE compares all negatives together through the softmax.
  • If labels are available, consider Supervised Contrastive: It avoids pushing apart examples of the same class as negatives.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F

# InfoNCE (van den Oord et al. 2018, Eq. (4)).
# Cross-entropy with the candidate scores as logits and the positive's position as the target class
def info_nce(scores, pos_index):
    # scores: (B, N), each row holds N candidate scores z_j^T W_k c_t. pos_index: (B,) position of the positive
    return F.cross_entropy(scores, pos_index)

# Numerical example from the text: N = 4, scores 2 for the positive and 1, 0, 0 for the negatives
s = torch.tensor([[2.0, 1.0, 0.0, 0.0]])
loss = info_nce(s, torch.tensor([0]))
print(loss.item())                                   # about 0.494
print(torch.log(torch.tensor(4.0)).item() - loss.item())   # lower bound on mutual information log N โˆ’ L โ‰ˆ 0.89

# A tiny CPC-style example: predict z_{t+k}, k steps ahead, from the context c_t.
# Negatives are the z at the same time step from the other sequences in the mini-batch (the diagonal of the B ร— B matrix is positive)
class TinyCPC(nn.Module):
    def __init__(self, z_dim=64, c_dim=128, max_k=4):
        super().__init__()
        self.enc = nn.Sequential(                      # g_enc: turns the waveform into a sequence of representations 1/16 as long
            nn.Conv1d(1, z_dim, kernel_size=8, stride=4, padding=2), nn.ReLU(),
            nn.Conv1d(z_dim, z_dim, kernel_size=8, stride=4, padding=2), nn.ReLU(),
        )
        self.ar = nn.GRU(z_dim, c_dim, batch_first=True)   # g_ar: c_t from z_{<=t}
        self.W = nn.ModuleList([nn.Linear(c_dim, z_dim, bias=False) for _ in range(max_k)])  # a separate W_k for each step k
        self.max_k = max_k

    def forward(self, wav):                             # wav: (B, 1, T)
        z = self.enc(wav).transpose(1, 2)               # (B, L, z_dim)
        c, _ = self.ar(z)                               # (B, L, c_dim)
        B, L, _ = z.shape
        t = L - self.max_k - 1                          # compute at a single time step t, as an example
        labels = torch.arange(B)
        loss = 0.0
        for k in range(1, self.max_k + 1):
            pred = self.W[k - 1](c[:, t])               # W_k c_t : (B, z_dim)
            target = z[:, t + k]                        # z_{t+k} : (B, z_dim)
            scores = pred @ target.T                    # scores[i, j] = z_j^T W_k c_i
            loss = loss + info_nce(scores, labels)      # the diagonal (i = j) is positive
        return loss / self.max_k

model = TinyCPC()
wav = torch.randn(8, 1, 4096)                           # 8 sequences (a mini-batch)
loss = model(wav)
loss.backward()

FAQ

Q. Are InfoNCE and NT-Xent the same thing?
A.

They have the same form: 'cross-entropy that picks the one positive out of a softmax over candidates including negatives.' The difference is the score function. InfoNCE (CPC) uses the unnormalized inner product zโŠคWkctz^\top W_k c_t, while NT-Xent uses the cosine similarity of โ„“2\ell_2-normalized vectors divided by a temperature ฯ„\tau. In practice, the NT-Xent form is also often called InfoNCE.

Q. How many negatives should I prepare?
A.

There is no fixed number, but more tends to help. Since the mutual information bound logโกNโˆ’LN\log N - \mathcal{L}_N cannot exceed logโกN\log N, a small NN caps the information that can be learned. In CPC's speech experiments, negatives were drawn from each GPU's mini-batch (8 examples). Besides the number, it is also important to choose negatives that are not too easy.

Q. How does it differ from ordinary classification cross-entropy?
A.

The computation is the same; the difference is that the 'classes' are not fixed. Ordinary classification picks the answer from a fixed set of classes, whereas InfoNCE picks the positive from NN candidates (one positive and the negatives) built for each input. As a result, it can learn without labels as long as it knows which pairs 'come from the same thing.'

References

  1. A. van den Oord, Y. Li, and O. Vinyals, "Representation Learning with Contrastive Predictive Coding," arXiv:1807.03748, 2018.
  2. T. Chen, S. Kornblith, M. Norouzi, and G. Hinton, "A Simple Framework for Contrastive Learning of Visual Representations," ICML, 2020.
  3. PyTorch Documentation, "torch.nn.functional.cross_entropy."