Train embeddings with the InfoNCE contrastive loss
CLIP and most embedding models learn by contrast: in a batch of n pairs, query i should match key i and not the other n - 1 keys.
Write info_nce(q, k, temperature) for q and k of shape (n, d):
1. L2-normalise every row of q and k.
2. logits = q @ k.T / temperature, shape (n, n).
3. loss = mean cross-entropy where the correct class for row i is column i.
Return the loss as a float. Use a stable log-softmax.
def info_nce(q, k, temperature)Understand the idea
InfoNCE trains embeddings by contrast. In a batch of n pairs, query i should be most similar to key i, and the other n - 1 keys act as wrong answers. Each row becomes an n-way classification where the correct class is the diagonal. Normalising rows first makes the dot product a cosine, so vector length does not matter. Temperature divides the scores; a small temperature makes the softmax sharper. Worked example: n = 2, q = k = [[1, 0], [0, 1]] (already unit length), temperature 1. Logits = [[1, 0], [0, 1]]. Row 0 loss = -log(e^1 / (e^1 + e^0)) = log(1 + e^-1) = 0.313; row 1 is the same, so the mean is 0.313. With temperature 0.1 the logits become [[10, 0], [0, 10]] and the loss drops to about 0.00005. Rule: normalise, logits = q k^T / T, loss = mean over rows of cross-entropy with label i, using a stable log-softmax. CLIP and sentence embedding models train this way.