REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Handle multiple positives and singleton anchors in SupCon

Normalize finite nonzero [N,D] embeddings, exclude self pairs from every softmax denominator, and average log probability over all same-label non-self positives for each anchor. Average only anchors that have a positive; singleton embeddings still appear as negatives for other anchors. Require N>=2, aligned int64 labels, temperature>0, and at least one positive pair. Preserve gradients to every participating embedding. Avoid zero times negative infinity on masked diagonals.

Run this Lab in Pythilo

Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.

No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.

PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.

Pythilo on the App Store →

Read lesson: Handle multiple positives and singleton anchors in SupCon →

Your task

Normalize finite nonzero [N,D] embeddings, exclude self pairs from every softmax denominator, and average log probability over all same-label non-self positives for each anchor. Average only anchors that have a positive; singleton embeddings still appear as negatives for other anchors. Require N>=2, aligned int64 labels, temperature>0, and at least one positive pair. Preserve gradients to every participating embedding. Avoid zero times negative infinity on masked diagonals.

Starter

import math
import torch
from torch.nn import functional as F

def supervised_contrastive(embeddings, labels, temperature=.1):
    # TODO: implement supervised_contrastive under the declared contract.
    return None
Inspect the worked answer
import math
import torch
from torch.nn import functional as F

def supervised_contrastive(embeddings, labels, temperature=.1):
    if embeddings.ndim!=2 or len(embeddings)<2 or embeddings.shape[1]==0 or labels.shape!=(len(embeddings),) or labels.dtype!=torch.long:raise ValueError('Expected [N>=2,D] embeddings and aligned int64 labels.')
    if not embeddings.is_floating_point() or not torch.isfinite(embeddings).all() or (embeddings.norm(dim=1)==0).any() or not math.isfinite(temperature) or temperature<=0:raise ValueError('Embeddings must be finite and nonzero; temperature must be positive.')
    diagonal=torch.eye(len(embeddings),dtype=torch.bool,device=embeddings.device)
    positive=(labels[:,None]==labels[None,:])&~diagonal
    counts=positive.sum(-1)
    valid=counts>0
    if not valid.any():raise ValueError('At least one non-self positive pair is required.')
    z=F.normalize(embeddings,dim=-1)
    scores=(z@z.T/temperature).masked_fill(diagonal,float('-inf'))
    log_prob=scores-torch.logsumexp(scores,-1,keepdim=True)
    selected=torch.where(positive,log_prob,torch.zeros_like(log_prob))
    per_anchor=-selected.sum(-1)/counts.clamp_min(1)
    return per_anchor[valid].mean()

About this algorithm

How Handle multiple positives and singleton anchors in SupCon works

The idea

Supervised contrastive learning trains embeddings so that examples with the same label lie close together and those with different labels lie apart, measured by cosine similarity. Each example in turn is the anchor. A softmax over its similarities to all other examples gives each a probability, and the loss is the negative log probability of the same-label examples, averaged over that anchor's positives.

Two details carry the Lab. The anchor is left out of its own softmax, because it is always most similar to itself. An anchor whose label appears only once has no positive to average, so it is skipped as an anchor but still serves as a negative for the others. Positives are picked with torch.where, because the masked diagonal holds -inf and zero times -inf is NaN.

How it works

  1. Validate finite nonzero [N, D] embeddings with N >= 2, int64 labels of length N, and a positive temperature.
  2. Build positive, true for pairs with equal labels off the diagonal, and counts, the number of positives per anchor.
  3. Normalize every embedding to unit length so z @ z.T holds cosine similarities, and divide by temperature.
  4. Fill the diagonal with -inf and subtract torch.logsumexp of each row to get log_prob.
  5. Select the positive entries with torch.where, sum each row, negate and divide by counts.
  6. Return the mean over the anchors that have at least one positive.

What it costs

Time
O(N²·D)
Memory
O(N²) similarity matrix

Every pair of embeddings in the batch is compared, so cost grows with the square of the batch size, and a larger batch gives each anchor more negatives.

Where it is used

  • Khosla et al. introduced the loss in 'Supervised Contrastive Learning' (NeurIPS 2020).
  • SimCLR trains on the single-positive form of this loss, using two augmented views of each image as the positive pair.
  • The pytorch-metric-learning library provides it as SupConLoss.

Watch out for

  • Leaving the anchor in its own denominator: its similarity to itself is the largest in the row and distorts every probability.
  • Multiplying log_prob by the positive mask: the diagonal holds -inf, and zero times -inf is NaN. Select with torch.where instead.
  • Removing singleton examples from the batch: they cannot be anchors, but they must remain as negatives and still receive gradients.