AI Logic

Loss Functions

NT-Xent

Updated:

Diagram of NT-Xent. On the left, 8 views placed on the unit circle: the anchor z_i, the positive z_j (another view of the same image), and negatives 1–6 (views of other images). On the right, bar charts of the probabilities obtained by dividing cosine similarities by a temperature and applying a softmax: top, τ = 0.5 (positive 0.34, loss 1.07); bottom, τ = 0.1 (positive 0.64, loss 0.44). Lowering τ concentrates probability on negative 6, which is close to the anchor. Legend and formula at the far right

Background and Overview

NT-Xent is a temperature-scaled softmax cross-entropy that identifies two views made from the same data point (a positive pair) among all the other views in the same mini-batch (the negatives). The name stands for Normalized Temperature-scaled Cross Entropy; Chen et al. (2020, Google) coined it in the paper on SimCLR, a self-supervised learning method for images.

The paper notes that the loss itself had been used in earlier work (Sohn 2016, Wu et al. 2018, and van den Oord et al. 2018, who proposed InfoNCE) and that it named the loss NT-Xent for convenience. It has the same "pick the one positive with a softmax over candidates" form as InfoNCE, and is distinguished by using the cosine similarity of vectors normalized to unit length as the score and a temperature τ\tau.

From the NN images in a mini-batch, 2N2N views are created, and for a positive pair (i,j)(i, j) the following loss is computed.

ℓi,j=−log⁡exp⁡ ⁣(sim(zi,zj)/τ)∑k=12N1[k≠i]exp⁡ ⁣(sim(zi,zk)/τ),sim(u,v)=u⊤v∥u∥∥v∥\ell_{i,j} = -\log \frac{\exp\!\left( \mathrm{sim}(z_i, z_j) / \tau \right)}{\sum_{k=1}^{2N} \mathbb{1}_{[k \ne i]} \exp\!\left( \mathrm{sim}(z_i, z_k) / \tau \right)}, \qquad \mathrm{sim}(u, v) = \frac{u^\top v}{\lVert u \rVert \lVert v \rVert}

1[k≠i]\mathbb{1}_{[k \ne i]} excludes the example itself (k=ik = i) from the denominator. The figure at the top places 8 views on the unit circle and shows how the probabilities of the positive and the negatives differ when only the temperature changes, with the same similarities.

Theory (Computing the Loss)

Following Algorithm 1 of the SimCLR paper, NT-Xent is computed in the following steps.

  1. Take NN images as a mini-batch and apply random data augmentation twice to each image, creating 2N2N views.
  2. Pass each through the encoder and the projection head to obtain vectors z1,…,z2Nz_1, \dots, z_{2N}.
  3. Compute the cosine similarity si,k=zi⊤zk/(∥zi∥∥zk∥)s_{i,k} = z_i^\top z_k / (\lVert z_i \rVert \lVert z_k \rVert) for every pair (i,k)(i, k).
  4. For each ii, apply a softmax over si,k/τs_{i,k} / \tau to the 2N−12N - 1 candidates excluding itself, and take the −log⁡-\log of the probability of its partner jj as ℓi,j\ell_{i,j}. 2(N−1)2(N-1) of the candidates are negatives.
  5. Average over all positive pairs in both directions, (i,j)(i, j) and (j,i)(j, i), to obtain the mini-batch loss.
L=12N∑k=1N[ℓ(2k−1, 2k)+ℓ(2k, 2k−1)]\mathcal{L} = \frac{1}{2N} \sum_{k=1}^{N} \bigl[ \ell(2k-1,\ 2k) + \ell(2k,\ 2k-1) \bigr]

A distinctive feature is that the views of the other images in the same mini-batch serve directly as negatives, with no separately prepared negatives. The paper varies the batch size from 256 to 8192; with 8192, each positive pair has 16,382 negatives.

In the example in the figure at the top, the cosine similarity between the anchor ziz_i and the positive zjz_j is 0.710.71, and that of the closest negative, 6, is 0.640.64. With τ=0.5\tau = 0.5, the positive's probability is 0.340.34 and the loss is 1.071.07; with τ=0.1\tau = 0.1, the probability is 0.640.64 and the loss is 0.440.44.

In practice, build the 2N×2N2N \times 2N similarity matrix, set the diagonal (self) to −∞-\infty, and pass it to F.cross_entropy with each row's target set to the position of its partner; this computes the formula above directly.

Why Normalization and Temperature Matter

The key point of NT-Xent is that normalization and temperature automatically set each negative's gradient weight according to "how confusing it is."

Table 2 of the paper gives the gradient of the loss with respect to the anchor uu, for an anchor uu, positive v+v^+, and negatives v−v^- all normalized to unit length. The direction that decreases the NT-Xent loss has the following form.

−∂ℓ∂u=1τ((1−p+) v+−∑v−p− v−),p−=exp⁡(u⊤v−/τ)∑v∈{v+, v−}exp⁡(u⊤v/τ)-\frac{\partial \ell}{\partial u} = \frac{1}{\tau} \Bigl( (1 - p^+)\, v^+ - \sum_{v^-} p^-\, v^- \Bigr), \qquad p^- = \frac{\exp(u^\top v^- / \tau)}{\sum_{v \in \{v^+,\ v^-\}} \exp(u^\top v / \tau)}

p+p^+ and p−p^- are the softmax probabilities of the positive and each negative. The anchor is pulled toward the positive and pushed away from each negative with a strength proportional to that negative's probability p−p^-. Negatives closer to the anchor (more confusing ones) have larger probabilities and are pushed away more strongly.

The temperature τ\tau determines how skewed these weights are. In the example in the figure at the top, the share of the total negative probability taken by the most confusing negative, 6, is about 46% at τ=0.5\tau = 0.5 and about 95% at τ=0.1\tau = 0.1. The lower the temperature, the more training concentrates on hard negatives. The paper states that an appropriate temperature helps the model learn from hard negatives.

In contrast, margin-based losses (such as Triplet Loss) and the logistic loss do not weight negatives by their relative hardness. The paper therefore points out that these losses need a separate semi-hard negative mining scheme that selects only the closest negatives inside the margin. In NT-Xent, this selection is built into the loss as softmax weights.

Normalization (cosine similarity) keeps similarities within the range −1-1 to 11. Dividing this range by the temperature lets a single parameter τ\tau control how sharp the softmax is. With unnormalized inner products, the sharpness would change simply because the vector lengths change.

Experimental Results

The SimCLR paper compares losses by the top-1 accuracy of a linear classifier trained on top of representations from a ResNet-50 trained on ImageNet.

Comparison with other losses (Table 4): For fairness, all losses use the same ℓ2\ell_2 normalization and tuned hyperparameters (in a setting where negatives are drawn only from one of the two views).

LossAccuracy (top-1)
Margin loss50.9%
NT-Logistic51.6%
Margin loss + semi-hard negative mining57.5%
NT-Logistic + semi-hard negative mining57.9%
NT-Xent63.9%

Effect of normalization and temperature (Table 5): The softmax has 4,096 candidates. "Contrastive accuracy" is the fraction of positives identified correctly during training.

ℓ2\ell_2 normalizationTemperature τ\tauContrastive accuracyLinear evaluation accuracy
Yes0.0590.5%59.7%
Yes0.187.8%64.4%
Yes0.568.2%60.7%
Yes159.1%58.0%
No1091.7%57.2%
No10092.1%57.0%

Without normalization, the accuracy of identifying positives during training was high, yet the quality of the representations (linear evaluation) dropped. Accuracy also dropped when the temperature was too small or too large; in this setting, τ=0.1\tau = 0.1 was best.

The final SimCLR reaches 69.3% with ResNet-50 and 76.5% with a 4× wider ResNet-50 (4×).

The best temperature depends on conditions. In the CIFAR-10 experiments in the paper's appendix, when trained to convergence, τ=0.5\tau = 0.5 was best among {0.1, 0.5, 1.0}\{0.1,\ 0.5,\ 1.0\} regardless of batch size, and τ=0.1\tau = 0.1 improved as the batch size increased. Do not reuse the ImageNet values from Table 5 as they are; tune the temperature to your data and batch size.

Practical Considerations

Because negatives come from within the mini-batch, a small batch size leaves too few negatives. In the SimCLR paper, larger batches gave a large advantage, especially with few training epochs (such as 100 epochs). The gap narrows as the number of epochs increases. To stabilize training with large batches, the paper uses LARS.

Keep the following points in mind as well.

  • Exclude the example itself from the denominator: Its similarity to itself is always 1, the maximum, so without exclusion most of the loss would come from the self term. In practice, set the diagonal of the similarity matrix to −∞-\infty.
  • Compute in both directions: Include both (i,j)(i, j) and (j,i)(j, i) in the loss. With only one direction, half of the views never act as anchors.
  • Watch the batch normalization statistics when training on multiple GPUs: Positive pairs are computed on the same GPU, so using per-GPU means and variances creates a cue for identifying positives without improving the representations (information leakage). SimCLR aggregates the means and variances across all GPUs.
  • A temperature that is too small also hurts: In Table 5, τ=0.05\tau = 0.05 gave lower accuracy than 0.10.1. A smaller temperature makes the logits larger, so beware of numerical overflow and pass them to F.cross_entropy rather than computing the exponentials yourself.
  • Other images of the same class also become negatives: Since no labels are used, another photo of the same dog is pushed away too. If labels are available, Supervised Contrastive, which treats them as positives, can be used.
  • PyTorch has no dedicated class: It takes only a few lines to write (see the code example).

Comparison with Other Methods

The table below compares NT-Xent with other losses that contrast positives and negatives through a softmax, and with a margin-based loss, from the same viewpoints.

Loss functionPositivesNegativesScoreTemperatureLabelsMain uses
InfoNCE1 (e.g., the true future)N−1N-1Unnormalized inner product z⊤Wkctz^\top W_k c_tNoNot usedLearning to predict 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 similarityYes (τ\tau)Not usedSelf-supervised image learning such as SimCLR
Supervised ContrastiveAll with the same labelAll with a different labelCosine similarityYes (τ\tau)UsedRepresentation learning for labeled classification
Triplet Loss11Squared distanceNo (margin α\alpha)UsedFace verification, image retrieval

Rough guidelines for choosing among them:

  • To learn representations from unlabeled images, use NT-Xent: All it needs is two views created by data augmentation.
  • If large batches are not feasible, consider a mechanism that stores negatives: NT-Xent relies on in-batch negatives, so with limited compute, methods such as MoCo, which keeps negatives in a memory, are an option (the SimCLR paper's comparison table also lists MoCo as a method that uses a memory bank).
  • If labels are available, consider Supervised Contrastive: It avoids pushing apart images of the same class as negatives.

PyTorch example

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

# NT-Xent (SimCLR, Eq. (1) and Algorithm 1 of Chen et al. 2020)
def nt_xent(z1, z2, tau=0.5):
    # z1, z2: (N, D) projections z of two views made from the same N images
    N = z1.shape[0]
    z = F.normalize(torch.cat([z1, z2], dim=0), dim=1)   # (2N, D), normalized to unit length
    sim = z @ z.T / tau                                   # cosine similarity ÷ τ, (2N, 2N)
    sim.fill_diagonal_(float("-inf"))                     # exclude self (k = i) from the denominator
    # partner of i: i in the first half pairs with i + N in the second half, and vice versa
    target = torch.cat([torch.arange(N, 2 * N), torch.arange(0, N)])
    return F.cross_entropy(sim, target)                   # mean over 2N anchors = mean over (i, j) and (j, i)

z1 = torch.randn(256, 128, requires_grad=True)
z2 = torch.randn(256, 128, requires_grad=True)
loss = nt_xent(z1, z2, tau=0.5)
loss.backward()

# Numerical example from the text: angles (degrees) on the unit circle. Anchor 30°, positive 75°, 6 negatives
import math
deg = torch.tensor([75.0, 100, 120, 190, 215, 300, 340])
sims = torch.cos(torch.deg2rad(deg - 30.0))              # positive 0.71, negative 6 is 0.64
for tau in (0.5, 0.1):
    p = torch.softmax(sims / tau, dim=0)
    print(tau, round(p[0].item(), 2), round(-math.log(p[0].item()), 2))   # 0.5 → 0.34, 1.07 / 0.1 → 0.64, 0.44

FAQ

Q. What value should the temperature τ be?
A.

It depends on the data and batch size. In SimCLR's ImageNet experiments (Table 5), τ=0.1\tau = 0.1 was best, and accuracy dropped at 0.050.05 and 0.50.5. In the CIFAR-10 experiments, on the other hand, τ=0.5\tau = 0.5 was best when trained to convergence. A safe approach is to start around 0.10.1 to 0.50.5 and tune on validation data.

Q. How does it differ from InfoNCE?
A.

They have the same form: cross-entropy that picks the one positive with a softmax over candidates. NT-Xent differs in using the cosine similarity of ℓ2\ell_2-normalized vectors as the score and dividing it by a temperature τ\tau. InfoNCE (CPC) uses the unnormalized inner product z⊤Wkctz^\top W_k c_t. NT-Xent also uses the other views in the mini-batch directly as negatives.

Q. Can it be used with a small batch size?
A.

Yes, but performance tends to drop because there are fewer negatives. In the SimCLR paper, large batches helped more in short training runs, and the gap narrowed with longer training. If large batches are difficult, train longer or consider methods such as MoCo, which keeps negatives in a memory.

References

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