Sub topic 9
The Symmetric Contrastive Loss, Step by Step
Assume you know basic Python and PyTorch tensors, embeddings, dot products, softmax, and cross-entropy loss. You should also know that CLIP has an image encoder and a text encoder. Each encoder turns its input into a vector.
Building a batch of comparisons
Suppose a batch contains \(B\) matching image-caption pairs:
- Image 0 matches caption 0.
- Image 1 matches caption 1.
- The other image-caption combinations are treated as non-matching examples.
The image encoder produces an image embedding for each image. The text encoder produces a text embedding for each caption. CLIP normalizes these embeddings so that their lengths are 1.
For normalized vectors, the dot product equals cosine similarity:
s(i,t) = i \cdot tA value near 1 means the vectors point in similar directions. A value near 0 means little alignment. The training goal is to make each matching pair more similar than every mismatched pair in the batch.
The similarity matrix
Stack the image embeddings into a matrix \(I\) and the text embeddings into a matrix \(T\). The matrix product
I T^\mathsf{T}produces a \(B \times B\) similarity matrix. Entry \((r,c)\) compares image \(r\) with caption \(c\).
The correct matches are on the diagonal:
| Row | Correct target |
|---|---|
| Image 0 | Caption 0 |
| Image 1 | Caption 1 |
| Image 2 | Caption 2 |
The other entries are in-batch negatives. They are negative examples created from the other items already present in the batch.
Scaling similarities with a learned temperature
CLIP multiplies each cosine similarity by a positive scale:
z_{r,c} = \exp(a) \, (I_r \cdot T_c)Here, \(a\) is a learned logit-scale parameter. Writing the scale as \(\exp(a)\) guarantees that it stays positive.
A larger scale makes the softmax distribution sharper. A smaller scale makes it softer. The model learns this value along with the encoder parameters.
Computing the symmetric loss
First, treat every image as a query and every caption as a candidate answer. Cross-entropy should select the diagonal caption for each image. This is the image-to-text loss.
Then transpose the matrix. Now every caption is a query, and cross-entropy should select the matching image. This is the text-to-image loss.
The final CLIP loss is their average:
L = \frac{L_{\text{i2t}} + L_{\text{t2i}}}{2}import torch
import torch.nn.functional as F
def clip_loss(image_emb, text_emb, logit_scale):
# Row i of each input is a matching image-caption pair.
image_emb = F.normalize(image_emb, dim=-1)
text_emb = F.normalize(text_emb, dim=-1)
logits = logit_scale.exp() * image_emb @ text_emb.t()
labels = torch.arange(logits.size(0), device=logits.device)
loss_i2t = F.cross_entropy(logits, labels)
loss_t2i = F.cross_entropy(logits.t(), labels)
return (loss_i2t + loss_t2i) / 2
batch_size = 4
embedding_dim = 8
images = torch.randn(batch_size, embedding_dim)
texts = torch.randn(batch_size, embedding_dim)
logit_scale = torch.tensor(2.0, requires_grad=True)
loss = clip_loss(images, texts, logit_scale)
loss.backward()
print(loss.item())Why use both directions?
Using both directions gives each encoder a direct training signal. Image embeddings must identify their captions, and text embeddings must identify their images. This symmetry also makes the shared embedding space useful for both image-to-text and text-to-image retrieval.
Exercise
For a batch of six matching pairs, what label tensor should be used for the image-to-text cross-entropy loss when the pairs are stored in matching order?
Show answer
torch.arange(6), which represents targets [0, 1, 2, 3, 4, 5].