AI Logic

Loss Functions

Supervised Contrastive

Updated:

Diagram of Supervised Contrastive. The left side shows embeddings on the unit circle: the anchor z_i (dog), same-class candidates 1–3 (1 is another view of the same image as the anchor), and candidates 4–7 from other classes (cat, car). The right side stacks two bar charts of probabilities obtained by dividing dot products by the temperature τ = 0.1 and applying softmax: the top is the self-supervised loss, which treats only candidate 1 as positive (loss 0.33), and the bottom is SupCon, which treats same-class 1, 2, and 3 as positives (loss 1.51). The denominator is shared; only the candidates treated as positives differ. The legend and formula are on the far right

Background and Overview

Supervised Contrastive (SupCon) is a contrastive loss function that uses labels to treat every example of the anchor's class as a positive and every example of other classes as a negative, comparing them with a softmax. Khosla et al. (2020, Google Research and others) proposed it as an extension of the contrastive loss used in self-supervised learning (the form of NT-Xent) to labeled classification.

In the self-supervised loss, the only positive is "another view made from the same image as the anchor," and other images of the same class are pushed away as negatives. SupCon uses labels to treat all images of the same class as positives, comparing many positives and many negatives against one anchor at once. The loss is as follows.

Loutsup=∑i∈I−1∣P(i)∣∑p∈P(i)log⁡exp⁡(zi⋅zp/τ)∑a∈A(i)exp⁡(zi⋅za/τ)\mathcal{L}^{\text{sup}}_{\text{out}} = \sum_{i \in I} \frac{-1}{\lvert P(i) \rvert} \sum_{p \in P(i)} \log \frac{\exp(z_i \cdot z_p / \tau)}{\sum_{a \in A(i)} \exp(z_i \cdot z_a / \tau)}

zz is an embedding normalized to unit length, τ\tau is the temperature, A(i)A(i) is the set of all candidates other than anchor ii, and P(i)P(i) is the subset of those with the same label as the anchor. As in the figure at the top, the denominator (all candidates) is the same as in the self-supervised loss; only the candidates placed in the numerator as positives differ.

With a linear classifier on top of the learned representation, ResNet-200 on ImageNet reached 81.4% top-1 accuracy, 0.8 points above the best reported value for cross-entropy with the same architecture. The paper describes it as the first contrastive loss to consistently outperform cross-entropy on large-scale classification.

Theory (How the Loss Is Computed)

SupCon training has two stages: representation learning and classifier learning. In representation learning, the loss is computed in the following steps.

  1. Take NN labeled examples and apply data augmentation twice to each, creating 2N2N views (a "multiviewed batch" in the paper's terms). Each view carries the label of its original example.
  2. Pass each through an encoder (such as a ResNet) and normalize to unit length, then pass it through a projection network (an MLP with a 2048-unit hidden layer and 128 outputs, or a linear layer with 128 outputs) and normalize again to obtain zz.
  3. For each anchor ii, divide the dot products zi⋅zaz_i \cdot z_a with all other candidates a∈A(i)a \in A(i) by τ\tau and turn them into probabilities with a softmax.
  4. For each candidate in P(i)P(i) with the anchor's label (another view of the same image, and views of other images of the same class), take −log⁡-\log of the probability, and average by dividing by ∣P(i)∣\lvert P(i) \rvert.
  5. Sum over all anchors and train the encoder and projection network.

After representation learning, the projection network is discarded, the encoder is frozen, and a linear classifier is trained on its output with cross-entropy. At inference time, the model is the same size as the same encoder trained with cross-entropy.

In the example in the figure at the top (τ=0.1\tau = 0.1), the probability of candidate 1 (another view of the same image) is 0.720.72, and those of same-class candidates 2 and 3 are 0.070.07 and 0.210.21. The self-supervised loss looks only at candidate 1, giving −log⁡0.72≈0.33-\log 0.72 \approx 0.33, while SupCon averages over the three, giving 1.511.51. This is because it asks for candidates 2 and 3 to be pulled closer to the anchor.

If there is only one positive (another view of the same image), SupCon coincides with the self-supervised loss (the NT-Xent form). The paper shows in its appendix that SupCon includes the self-supervised loss, the N-pairs loss, and Triplet Loss as special cases.

Why Average Outside the Log

When there are several positives, there are two ways to average. The paper compared both and showed that the form that averages outside the log (Loutsup\mathcal{L}^{\text{sup}}_{\text{out}}) is much better.

Linsup=∑i∈I−log⁡{1∣P(i)∣∑p∈P(i)exp⁡(zi⋅zp/τ)∑a∈A(i)exp⁡(zi⋅za/τ)}\mathcal{L}^{\text{sup}}_{\text{in}} = \sum_{i \in I} -\log \left\{ \frac{1}{\lvert P(i) \rvert} \sum_{p \in P(i)} \frac{\exp(z_i \cdot z_p / \tau)}{\sum_{a \in A(i)} \exp(z_i \cdot z_a / \tau)} \right\}

Linsup\mathcal{L}^{\text{sup}}_{\text{in}} sums the positive probabilities before taking the log. With ResNet-50 on ImageNet (batch size 6144), Loutsup\mathcal{L}^{\text{sup}}_{\text{out}} reached 78.7% and Linsup\mathcal{L}^{\text{sup}}_{\text{in}} 67.4%.

The paper's explanation is as follows.

  • The 1/∣P(i)∣1/\lvert P(i) \rvert inside the log does not affect the gradient: Multiplying by a constant inside the log just adds a constant to the loss, so the gradient is unchanged.
  • Summing inside the log is more sensitive to bias among positives: In the paper's gradient expressions, each positive's weight in Linsup\mathcal{L}^{\text{sup}}_{\text{in}} is proportional to exp⁡(zi⋅zp/τ)\exp(z_i \cdot z_p/\tau), so positives closer to the anchor get larger weights. In Loutsup\mathcal{L}^{\text{sup}}_{\text{out}}, every positive has the same weight 1/∣P(i)∣1/\lvert P(i) \rvert. The paper concludes that this stabilization by averaging over positives helps training.

Both forms keep the following properties.

  • They handle any number of positives: All same-class candidates enter the numerator, and training gathers the embeddings of each class in one place.
  • More negatives increase discriminative power: The denominator keeps the sum over all negatives.
  • Hard positives and negatives are weighted automatically: With normalized embeddings, positives far from the anchor and negatives close to it have large gradients, while easy pairs have small gradients. So there is no need to select hard combinations as in Triplet Loss.

As an analogy, the self-supervised loss is the task "from a crop of a photo, find the other crop of the same photo," while SupCon is the task "gather all photos of the same dog breed onto the same shelf."

Experimental Results

The paper compares top-1 accuracy with a linear classifier on top of ResNet representations (Table 2). The compared methods were re-implemented and tuned by the paper's authors (Max-Margin uses values reported in its paper).

DatasetSimCLRCross-entropyMax-MarginSupCon
CIFAR-1093.6%95.0%92.4%96.0%
CIFAR-10070.7%75.3%70.5%76.5%
ImageNet70.2%78.2%78.0%78.7%

The comparison on ImageNet with different data augmentations and architectures (Table 3) is as follows.

LossArchitectureData augmentationTop-1Top-5
Cross-entropy (authors' implementation)ResNet-50AutoAugment77.6%95.3%
SupConResNet-50AutoAugment78.7%94.3%
Cross-entropy (authors' implementation)ResNet-200Stacked RandAugment80.9%95.2%
SupConResNet-200Stacked RandAugment81.4%95.9%

The appendix varies the cap on the number of positives per anchor (ImageNet, ResNet-50).

Cap on positives13579No cap (13)
Top-1 accuracy69.3%76.6%78.0%78.4%78.3%78.5%

With one positive it is the same as the self-supervised loss, and accuracy rose as positives were added. Other reported results include:

  • Robustness to image corruption: The mean corruption error on ImageNet-C (mCE, lower is better) was 67.2 for SupCon vs. 68.6 for cross-entropy with ResNet-50, and 50.6 vs. 52.4 with ResNet-200.
  • Stability to hyperparameters: When data augmentation, optimizer, and learning rate were varied one at a time, SupCon's accuracy varied less than cross-entropy's.
  • Comparison with the N-pairs loss: In the same framework (batch size 6144), the N-pairs loss reached only 57.4%.
  • Transfer learning: Transfer to 12 datasets was on par with cross-entropy and SimCLR (ResNet-50 averages: SupCon 84.27, cross-entropy 84.67, SimCLR 84.81).

On ImageNet with ResNet-50, the gap is small: 78.7% vs. 78.2% reported for cross-entropy. Also, these numbers reflect not only the SupCon loss but also the two-stage training, data augmentation, and long training of 700 epochs (ResNet-200) or 350 epochs (smaller models).

Practical Considerations

Large batches are required. Both positives and negatives come from within the mini-batch, so if the batch size is small relative to the number of classes, few same-class positives are included. The paper trained with batches of up to 6144 and says 2048 is enough in many cases. When large batches are difficult, a memory that stores past embeddings can be used, as the paper also tried (79.1% with a memory of 8192 and a batch of 256).

Keep the following points in mind as well.

  • Use a small temperature by default: All results in the paper use τ=0.1\tau = 0.1. Smaller temperatures work better, but the paper reports that extremely small ones become numerically unstable. Because the gradient scales with 1/τ1/\tau, the paper multiplies the loss by τ\tau during training to stabilize it.
  • Always normalize the embeddings: Normalize both the encoder output and the projection network output to unit length. The paper states that the automatic weighting of hard positives and negatives arises only with normalization.
  • Average outside the log: When implementing it yourself, using the form that sums positive probabilities before the log (Linsup\mathcal{L}^{\text{sup}}_{\text{in}}) greatly lowers accuracy.
  • Train in two stages: After representation learning, freeze the encoder and train a linear classifier (the paper says about 10 epochs suffice). Put the frozen encoder in eval() so that the batch normalization statistics do not change.
  • Optimizer: On ImageNet, the best results came from LARS for representation learning and RMSprop for the linear classifier; on CIFAR, SGD with momentum was best.
  • PyTorch has no built-in version: The authors' PyTorch implementation is public. It can be written in a few lines (see the implementation example).

Comparison with Other Methods

SupCon, losses that compare positives and negatives, and the classification loss are lined up from the same viewpoint.

Loss functionLabelsPositivesNegativesComparisonMain use
Supervised ContrastiveUsedAll with the same labelAll with a different labelSoftmax over cosine similarity ÷ τ\tau (averaged per positive)Representation learning for classification (two-stage)
NT-XentNot usedOne other view of the same imageAll views of other images (including the same class)Softmax over cosine similarity ÷ τ\tauRepresentation learning without labels
InfoNCENot used1N−1N-1Softmax over dot productsLearning to predict the future from context
Triplet LossUsed11Difference of squared distances with a marginFace verification, image retrieval
Cross-entropyUsed——Softmax against per-class weightsOrdinary classification (single-stage)

Guidelines for choosing:

  • If labels are available and representation quality and robustness matter, consider SupCon: In the paper it matched or exceeded cross-entropy in accuracy and was also robust to image corruption and hyperparameter changes.
  • If simplicity matters, use cross-entropy: SupCon requires two-stage training and large batches, and the gap on ImageNet with ResNet-50 is modest.
  • Without labels, use NT-Xent: It corresponds to SupCon with only the other view of the same image as the positive.
  • To avoid the effort of selecting hard combinations, use SupCon rather than Triplet Loss: It compares many positives and negatives together through a softmax, so no special care in choosing combinations is needed.

PyTorch example

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

# Supervised Contrastive (Eq. (2) of Khosla et al. 2020, L_out)
def supcon_loss(features, labels, tau=0.1):
    # features: (B, V, D) projections z of V views per example. labels: (B,)
    B, V, D = features.shape
    z = F.normalize(features, dim=2).reshape(B * V, D)       # normalize to unit length
    y = labels.repeat_interleave(V)                           # each view gets its original label
    logits = z @ z.T / tau                                    # z_i · z_a / τ
    self_mask = torch.eye(B * V, dtype=torch.bool, device=z.device)
    logits = logits.masked_fill(self_mask, float("-inf"))     # A(i): exclude self
    log_prob = logits - torch.logsumexp(logits, dim=1, keepdim=True)
    pos_mask = (y[:, None] == y[None, :]) & ~self_mask        # P(i): same label (excluding self)
    # average −log p over positives outside the log (L_out)
    loss_i = -log_prob.masked_fill(~pos_mask, 0.0).sum(1) / pos_mask.sum(1).clamp(min=1)
    return loss_i.mean()                                      # the paper sums over i; the mean is used here

# Stage 1: train the encoder and projection network with SupCon
encoder = nn.Sequential(nn.Flatten(), nn.Linear(3 * 32 * 32, 512), nn.BatchNorm1d(512), nn.ReLU())
proj = nn.Sequential(nn.Linear(512, 512), nn.ReLU(), nn.Linear(512, 128))
opt = torch.optim.SGD(list(encoder.parameters()) + list(proj.parameters()), lr=0.05, momentum=0.9)

x1 = torch.randn(64, 3, 32, 32)            # the same 64 images under two different augmentations
x2 = torch.randn(64, 3, 32, 32)
labels = torch.randint(0, 10, (64,))
encoder.train(); proj.train()
h = F.normalize(encoder(torch.cat([x1, x2])), dim=1)          # normalize the encoder output too
z = proj(h)
feats = torch.stack([z[:64], z[64:]], dim=1)                  # (64, 2, 128)
loss = supcon_loss(feats, labels, tau=0.1)
opt.zero_grad(); loss.backward(); opt.step()

# Stage 2: discard the projection network and train a linear classifier on the frozen encoder
encoder.eval()                                                # freeze batch norm statistics
clf = nn.Linear(512, 10)
opt2 = torch.optim.SGD(clf.parameters(), lr=0.1, momentum=0.9)
with torch.no_grad():
    h = F.normalize(encoder(x1), dim=1)
loss2 = F.cross_entropy(clf(h), labels)
opt2.zero_grad(); loss2.backward(); opt2.step()

FAQ

Q. How does it differ from training with cross-entropy?
A.

Cross-entropy predicts the class by comparing the embedding with per-class weights. SupCon compares examples within the mini-batch with each other, pulling embeddings of the same class together and pushing different classes apart. A linear classifier is then trained, giving two stages. In the paper, accuracy was on par or better, and it was more robust to image corruption and hyperparameter changes.

Q. When should it be used instead of the self-supervised loss (NT-Xent)?
A.

Use SupCon if labels are available and NT-Xent if not. In NT-Xent, other images of the same class are also pushed away as negatives. SupCon makes them positives, so embeddings of the same class cluster together. In the paper's appendix, increasing the positives from one (the same as self-supervised) raised accuracy from 69.3% to 78.5%.

Q. What temperature τ should be used?
A.

All results in the paper use τ=0.1\tau = 0.1. Smaller temperatures tend to work better, but extremely small ones are numerically unstable. Also, a smaller temperature makes the gradient larger, so the paper multiplies the loss by τ\tau to stabilize training.

References

  1. P. Khosla, P. Teterwak, C. Wang, A. Sarna, Y. Tian, P. Isola, A. Maschinot, C. Liu, and D. Krishnan, "Supervised Contrastive Learning," NeurIPS, 2020.
  2. T. Chen, S. Kornblith, M. Norouzi, and G. Hinton, "A Simple Framework for Contrastive Learning of Visual Representations," ICML, 2020.
  3. SupContrast (PyTorch implementation by the authors)