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