REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Train paired embeddings with symmetric InfoNCE

A contrastive batch declares which two observations belong together and treats the other in-batch candidates as negatives.

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: Train paired embeddings with symmetric InfoNCE →

Your task

For finite nonzero aligned [N,D] embeddings, N>=2, L2-normalize each row, form a@b.T / temperature and average row-wise and column-wise cross entropy against diagonal pair identities. Return a differentiable scalar; gradients must reach both encoders. Reject zero vectors, bad shapes and nonpositive/nonfinite temperature.

Starter

import torch


def symmetric_contrastive(a, b, temperature):
    return None
Inspect the worked answer
import math
import torch
from torch.nn import functional as F


def symmetric_contrastive(a, b, temperature):
    if a.ndim != 2 or a.shape != b.shape or a.shape[0] < 2 or a.shape[1] < 1:
        raise ValueError('two aligned embedding matrices with at least two pairs required')
    if not math.isfinite(temperature) or temperature <= 0:
        raise ValueError('positive finite temperature required')
    if any(not bool(torch.isfinite(x).all()) or bool((x.norm(dim=-1) == 0).any()) for x in (a, b)):
        raise ValueError('finite nonzero embeddings required')
    scores = F.normalize(a, dim=-1) @ F.normalize(b, dim=-1).T / temperature
    labels = torch.arange(a.shape[0], device=a.device)
    return (F.cross_entropy(scores, labels) + F.cross_entropy(scores.T, labels)) / 2

About this algorithm

How Train paired embeddings with symmetric InfoNCE works

The idea

Contrastive learning needs no class labels. The batch itself says what belongs together: row i of a and row i of b are two views of the same thing, such as an image and its caption, and every other row in the batch is treated as a mismatch.

After L2 normalization, a @ b.T is an N by N table of cosine similarities with the true pairs on the diagonal. The insight is to read each row as a classification problem whose correct class is its own index, so plain cross entropy does the work. Scoring rows (a to b) and columns (b to a) and averaging makes the loss symmetric. Dividing by temperature sharpens the softmax.

How it works

  1. Check for two aligned [N, D] matrices with N of at least 2, finite values, no zero rows and a positive temperature.
  2. L2-normalize every row of a and b, so a dot product is a cosine similarity.
  3. Compute scores = a @ b.T / temperature, an N by N matrix with the matching pairs on its diagonal.
  4. Set labels = torch.arange(N): the correct column for row i is i.
  5. Take cross entropy over the rows of scores and again over its columns using scores.T.
  6. Return the average of the two losses, which sends gradients into both encoders.

What it costs

Per batch
O(N²·D)
Memory
O(N²) scores
Negatives
N - 1 per row

The score matrix needs N squared dot products of length D, so doubling the batch quadruples the work while giving every pair about twice as many negatives.

Where it is used

  • OpenAI's CLIP trained an image encoder and a text encoder with this symmetric loss on 400 million image and caption pairs.
  • SimCLR learns image features with the same in-batch contrast, applied to two augmented views of each picture.
  • Sentence-Transformers' MultipleNegativesRankingLoss trains text embedding models for search using in-batch negatives.

Watch out for

  • Skipping normalization: vector length then drives the scores, and the model can lower the loss by growing norms instead of aligning directions.
  • Leaving out the temperature: cosine scores stay between -1 and 1, the softmax is nearly flat and the loss cannot get small.
  • Putting duplicate or near-identical pairs in one batch: they are scored as negatives and pushed apart although they match.