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 "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.
Term by term
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.
The positive key: the embedding that should match , such as another view of the same image, or its caption. The is a label.
All candidate keys: the positive plus negatives (other images in the batch or a queue).
The similarity score, divided by a temperature (0.07 in MoCo and CLIP). A small sharpens the softmax so hard negatives count more.
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.
Logarithm · Exponential · Softmax · Summation
A small worked example
Similarities: positive , two negatives and . With the positive gets , loss . With the scores become , the positive gets and the loss drops to .
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
Other equations
- Scaled dot-product attention
- Softmax
- Cross-entropy loss
- Adam update
- Layer normalization
- RMSNorm
- The ELBO
- KL divergence
- Backpropagation through one layer
- LoRA
- GELU
- Dropout
- Batch normalization
- Rotary position embedding (RoPE)
- Multi-head attention
- PPO clipped objective
- DPO loss
- Policy gradient (REINFORCE)
- Bellman equation
- Q-learning update
- Diffusion forward process
- DDPM simplified loss
- VAE reparameterization trick
- GAN minimax objective
- AdamW
- Cosine learning-rate schedule
- Perplexity
- Logistic regression
- Normal equation (linear regression)
- Singular value decomposition (SVD)
- Principal component analysis (PCA)