Multimodal Foundations › A Worked Example: Batch Contrastive Loss
Language AI HandbookAll chapters Multimodal Foundations › A Worked Example: Batch Contrastive LossOne section · Sections in this chapter8 / 13 ↓
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
Let us walk through the computation of the InfoNCE loss for a small batch of three image-text pairs to make the mathematics concrete. This example contains every step with explicit numbers so that the relationship between the geometry of the embedding space and the value of the loss is clear.
Suppose after encoding and L2-normalizing, we have embeddings in (two dimensions for visualization purposes):
- Image embeddings: , , (all unit vectors)
- Text embeddings: (similar to ), (similar to ), (similar to ), all after L2-normalization.
where are matched pairs.
Step 1: Compute the similarity matrix .
For our example (using approximate values after normalizing ):
The diagonal entries are large and positive (high similarity for matched pairs) while off-diagonal entries are smaller or negative (low similarity for mismatched pairs).
Step 2: Scale by temperature .
The temperature scaling amplifies the differences, making the softmax much more peaked.
Step 3: Compute row-wise softmax for the image-to-text direction.
For image :
Since and and , the softmax is approximately . Almost all probability mass sits on the matched pair (index 1).
Step 4: Compute cross-entropy loss for image 1.
Very low loss because the matched pair has very high similarity and temperature scaling made the difference extremely sharp.
Step 5: Repeat symmetrically for text-to-image. The structure is identical by the construction of our example.
Step 6: Average all terms to get the final loss. In this idealized example, after several steps of training that pushed embeddings toward high similarity for matched pairs, the loss is very near zero.
Now contrast this with an untrained model where embeddings are random. Random unit vectors in high dimensions have expected cosine similarity near zero, so all entries of are near zero and the softmax distribution is nearly uniform. In that case, and the loss is approximately , which for a batch of 32,768 is about 10.4. Training drives the loss from toward zero.