PythiloLesson 3 of 8 · progress kept in this browser

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.

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.

This lesson uses torch, which Python in this browser does not include. Read it here, and run and check it in the Pythilo app on iPhone or iPad.