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 NoneInspect 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()