Compute the supervised contrastive loss
Why it matters Embedding models for search and classification heads are pretrained with this loss.
Supervised contrastive learning pulls together every pair with the same label.
Write supcon(E, labels, temp). Normalise rows of E to unit length. S = E E^T / temp. For anchor i, the denominator sums exp(S[i, a]) over a != i. Its positives P(i) are j != i with the same label. Loss_i = -(1 / |P(i)|) sum over p in P(i) of log(exp(S[i, p]) / denominator). Return the mean over anchors with at least one positive.
def supcon(E, labels, temp)Example
two identical unit vectors with the same label and temp 1 give loss 0, because each anchor's only other item is its positive.
Understand the idea
Supervised contrastive loss pulls every same-label pair together and pushes everything else apart, using a softmax over cosine similarities. For each anchor, each positive should take a large share of the anchor's softmax over all other items. Worked example: unit vectors e1 = [1, 0], e2 = [1, 0], e3 = [0, 1], labels [0, 0, 1], temp 1. Similarities: S[0] = [1, 1, 0]. Anchor 0 excludes itself, so the denominator is e^1 + e^0 = 3.718. Its only positive is item 1: log(e^1 / 3.718) = 1 - 1.313 = -0.313, so loss_0 = 0.313. Anchor 1 is the same, 0.313. Anchor 2 has no positive and is skipped. Mean = 0.313. Rule: normalise rows to unit length, S = E E^T / temp, denominator_i = sum over a != i of exp(S[i, a]), loss_i = -(1 / |P(i)|) * sum over positives p of (S[i, p] - log denominator_i), averaged over anchors with at least one positive. Never include the anchor in its own denominator. Used in: representation pretraining with labels, and embedding models for retrieval.
Shapes and data flow
E (n, d) normalised -> S (n, n) mask diagonal -> log-sum-exp per row (n,) positives mask (n, n) -> mean log-prob per anchor