A multimodal embedding model trains on pairs across modalities: an image and its caption, an audio clip and its transcript. Each side can be the query, so the loss is computed in both directions and averaged, and batches are kept to one modality pair so that the in-batch negatives are comparable. Implement both pieces in PyTorch.
symmetric_infonce(A, B, tau=0.05)
A and B have shape (N, d), row i of each being one pair. Normalize rows, compute logits = An @ Bn.T / tau, and return the tuple (loss, acc_a2b, acc_b2a): the loss is the mean of the cross-entropy of logits against arange(N) and the cross-entropy of logits.T against arange(N); the accuracies are the fraction of rows whose argmax is the diagonal, in each direction, as Python floats.modality_pure_batches(items, batch_size)
items is a list of (item_id, pair_kind) tuples such as ("img_0", "image-text"). Group the ids by pair_kind in order of first appearance, keep each group's ids in their original order, and chunk every group into lists of at most batch_size. Return the list of batches, all of the first group's batches first, then the second group's, and so on.clamped_scale(logit_scale, max_value=100.0)
torch.clamp(logit_scale.exp(), max=max_value) so the effective inverse temperature cannot exceed max_value.F.cross_entropy(logits, targets) and F.cross_entropy(logits.T, targets) share the same targets.dict preserves insertion order, which gives the order of first appearance for free.