Equations · Oord, Li and Vinyals, “Representation Learning with Contrastive Predictive Coding” (2018); this temperature form as written in MoCo (He et al., 2020)

The InfoNCE contrastive loss, explained term by term

A contrastive loss: given a query embedding, pick out its one matching "positive" key from a set that also holds KK "negatives". It is cross-entropy over the similarity scores, with the positive as the correct class, and it pulls matching pairs together and pushes the rest apart.

LInfoNCE=−log⁡exp⁡(q⋅k+/τ)∑i=0Kexp⁡(q⋅ki/τ)\mathcal{L}_{\mathrm{InfoNCE}} = -\log \frac{\exp(\mathbf{q} \cdot \mathbf{k}_{+} / \tau)}{\sum_{i=0}^{K} \exp(\mathbf{q} \cdot \mathbf{k}_i / \tau)}

Open in the decoder →

Term by term

  1. q\mathbf{q}

    The query embedding, for example one augmented view of an image (or an image, in CLIP). Usually L2-normalized, so dot products are cosine similarities.

  2. k+\mathbf{k}_{+}

    The positive key: the embedding that should match q\mathbf{q}, such as another view of the same image, or its caption. The ++ is a label.

  3. ki, i=0,…,K\mathbf{k}_i, \ i = 0, \ldots, K

    All candidate keys: the positive plus KK negatives (other images in the batch or a queue).

  4. q⋅k/τ\mathbf{q} \cdot \mathbf{k} / \tau

    The similarity score, divided by a temperature τ\tau (0.07 in MoCo and CLIP). A small τ\tau sharpens the softmax so hard negatives count more.

  5. −log⁡exp⁡(…)∑exp⁡(…)-\log \frac{\exp(\ldots)}{\sum \exp(\ldots)}

    The negative log of the softmax probability given to the positive: exactly the cross-entropy loss with the positive as the label. Minimizing it is shown to maximize a lower bound on the mutual information between the paired views.

A small worked example

Similarities: positive 0.90.9, two negatives 0.10.1 and 0.30.3. With τ=1\tau = 1 the positive gets e0.9/(e0.9+e0.1+e0.3)≈0.50e^{0.9}/(e^{0.9} + e^{0.1} + e^{0.3}) \approx 0.50, loss ≈0.69\approx 0.69. With τ=0.1\tau = 0.1 the scores become 9,1,39, 1, 3, the positive gets ≈0.997\approx 0.997 and the loss drops to ≈0.003\approx 0.003.

In code

import torch
import torch.nn.functional as F

def info_nce(q, k, tau=0.07):
    # q, k: (N, d), L2-normalized; row i of k is the positive for row i of q
    logits = q @ k.T / tau               # (N, N); off-diagonal entries are negatives
    labels = torch.arange(q.shape[0])
    return F.cross_entropy(logits, labels)

Every symbol in it

x∈Rd\mathbf{x} \in \mathbb{R}^{d}Bold lowercase (vector)xi,  Wq,  pθ,  dmodelx_i,\; W_q,\; p_\theta,\; d_{\text{model}}Subscript (index or label)a⋅b\mathbf{a} \cdot \mathbf{b}Centre dotsoftmax⁡(z/τ)\operatorname{softmax}(z / \tau)Tau⟨x,y⟩\langle \mathbf{x}, \mathbf{y} \rangleInner product (angle brackets)log⁡pθ(x)\log p_\theta(x)Logarithmex=exp⁡(x)e^{x} = \exp(x)Exponentialsoftmax⁡(z)i=ezi∑jezj\operatorname{softmax}(\mathbf{z})_i = \frac{e^{z_i}}{\sum_j e^{z_j}}Softmax∑i=1Nxi\sum_{i=1}^{N} x_iSummation

Other equations