Practice in Lab: Handle multiple positives and singleton anchors in SupCon →
Handle multiple positives and singleton anchors in SupCon
Pairwise contrastive learning assigns one positive per observation; supervised contrastive learning can assign several. Averaging individual positive log probabilities differs from taking the logarithm of their summed probability. A singleton label has no positive anchor loss but can still be a useful negative for another class. Removing its entire row and column would change the objective. Masked numerical operations also matter: multiplying an invalid diagonal by zero can still propagate NaNs.
Prepare offline
Choose Download entire course or Download entire category first. After completion, code and checks run locally on CPU. The independent example needs no account, remote service or API key.
import torch
labels = torch.tensor([0, 0, 1])
same = labels[:, None] == labels[None, :]
print(same & ~torch.eye(3,dtype=torch.bool))Review the evidence
Review positive identity and augmentation policy separately from class labels. Test invariance to joint permutation and positive scaling, then assess representation quality on a genuinely held-out downstream task.
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.
The explanation opens here once every check passes.