Multimodal Contrastive Learning
A multimodal model places images, text, and audio in one representation space, so a picture and its caption land close together. This first part builds the contrastive route: the shared embedding space and its residual modality gap, the Vision Transformer image encoder (patch embedding, CLS token, position embeddings, with shapes), the symmetric InfoNCE loss that trains the CLIP dual encoder from a batch similarity matrix (with a worked numeric step), and zero-shot classification as a softmax over class-prompt embeddings.
╌╌╌╌
Large language models read one modality: text. A multimodal model maps inputs from several modalities, images, text, audio, into a single representation where comparison across modalities is a dot product, so that a photograph and the sentence describing it become neighbors. Everything in this lesson follows from one design problem: putting a image and a string of tokens into the same space, and then letting them interact.
The shared embedding space and the modality gap
The cleanest multimodal design gives each modality its own encoder and forces their outputs into one space. An image and a text become unit vectors , and their semantic agreement is the cosine similarity .
The alignment is imperfect. Even after contrastive training the two modalities occupy separate cones: image embeddings cluster on one side of the sphere and text embeddings on another, with a measurable angular separation between the two clouds. This is the modality gap, a consequence of separate encoders and random initialization that contrastive training narrows but never fully closes.1
The image encoder: a Vision Transformer
Before two modalities can share a space, the image needs an encoder that produces a single vector the way a text Transformer produces one from a sentence. The Vision Transformer (ViT) does this by cutting the image into fixed patches, treating each patch as a token, and running the ordinary Transformer encoder over that sequence.2 The only new step is turning a grid of pixels into a sequence of embeddings.
Take the standard configuration: a RGB image, patch size . The grid is , so patches, each flattened to pixel values, then projected to . The linear projection is literally a with kernel and stride both : one convolution stride per patch, output channels . The shapes flow as
Two additions finish the input. A learned CLS token is prepended to the sequence; after the encoder its output row is the image's single summary vector, the analogue of a sentence embedding. And because attention is permutation-invariant, a learned position embedding is added so the model can tell a top-left patch from a bottom-right one. The encoder input is
A stack of standard Transformer encoder blocks (multi-head self-attention, then an MLP, each with a residual and LayerNorm) maps to of the same shape. The image representation is the CLS output row , which a final linear head projects to the shared space. Nothing about attention changed; only the tokenizer did.
The patch count sets the compute: self-attention is , so halving the patch size () quadruples the token count () and raises attention cost roughly . That is the accuracy-versus-cost dial a ViT exposes, and it is why CLIP ships several patch sizes.
Contrastive vision-language pretraining
The dominant way to learn a shared space is contrastive language-image pretraining (CLIP).3 Two encoders, a Vision Transformer for the image and a Transformer for the text, map a large batch of paired (image, caption) examples into , and a contrastive loss pulls each image toward its own caption and pushes it away from every other caption in the batch.
The batch similarity matrix
Embed the batch and -normalize: let and , each on the unit sphere. The pairwise cosine similarities form an matrix , scaled by a learned temperature ,
The correct matches lie on the diagonal: should be large, every off-diagonal () should be small. The loss is a classification over the matrix that makes the diagonal win in both directions.
Deriving the symmetric InfoNCE loss
Read each row of as logits over the captions for one fixed image. The probability the model assigns to caption being the match for image is a softmax over the row,
The true caption for image is , so the image-to-text loss is the cross-entropy that the row softmax places all its mass on the diagonal,
This loss is InfoNCE: one positive () against in-batch negatives, with the temperature.4 The similarity matrix is not symmetric in its use: reading by columns instead gives the text-to-image direction, classifying each caption among the images,
CLIP averages the two so neither modality is privileged. The full objective is the symmetric contrastive loss.
The temperature is not a fixed hyperparameter. CLIP learns and clips it to avoid collapse: small sharpens the softmax (hard separation, unstable gradients), large flattens it (soft separation, weak signal). The gradient gives the intuition. Writing for the row softmax, the derivative of with respect to the logit is
so each step pushes the diagonal logit up (target ) and every off-diagonal logit down (target ), with force proportional to the current softmax mass on the wrong caption: large negatives are corrected hardest. The full dual-encoder training step is one algorithm block.
- 1image embeddings, rows
- 2text embeddings, rows
- 3-normalize every row of and
- 4similarity logits
- 5true match is the diagonal
- 6image to text
- 7text to image
- 8return
CLIP trains on M image-text pairs scraped from the web; the batch is the source of negatives, so very large batches (CLIP used ) sharpen the signal because each positive competes against tens of thousands of distractors.
A worked step
For example, take pairs, , and suppose the three normalized image vectors already sit near their captions so the cosine similarities come out as
Row is the logit vector for image against the three captions. Its softmax puts
so the image-to-text loss on this row is . Divide by ten (sharper) and the same row gives , essentially zero loss but a knife-edge gradient; multiply by ten (flatter) and falls toward , so the loss rises and the encoders get a larger, softer push. That single dial trades gradient sharpness against gradient signal, which is why CLIP learns it rather than fixing it.
The tensor shapes for one training step, with embedding dimension and batch , are
so the only object is the similarity matrix; everything else is a thin activation. The memory cost of the negatives is the matrix, cheap next to the two encoders, which is what makes tens-of-thousands batches affordable.
Zero-shot transfer
A CLIP model never sees class labels, only captions, yet it classifies images without any task-specific training. The method is to turn each class name into a caption and pick the caption the image embedding is closest to.
The prediction is a plain softmax classifier whose weight matrix is the stack of text embeddings. With the class-caption embeddings and the image embedding, the class posterior is
the same row-softmax as training, only now the columns are class prompts
instead of batch captions. No parameters change; the classifier weights
are computed once by running the text encoder over the prompts.
The choice of prompt template matters, because the text encoder was trained on
natural captions, not bare nouns. a photo of a dog
sits where dog photos sit;
the lone token dog
does not. Prompt ensembling averages the (normalized)
embeddings of many templates per class,
over templates such as a photo of a
, a blurry photo of a
, a in a video game
, then renormalizes. Averaging
in embedding space cancels template-specific noise while keeping the shared class
direction, and it recovers a few points of accuracy for free.
CLIP transfers zero-shot to ImageNet at accuracy competitive with a fully supervised ResNet-50, and is far more robust to distribution shift, because the caption supervision is broader than a fixed label set.3
ALIGN: the noisy-scale variant
CLIP curated its pairs. ALIGN drops the curation: it trains the same dual-encoder contrastive objective on over a billion image-alt-text pairs taken raw from the web, noise and all, showing that scale of data substitutes for quality of data.5 The architecture differs in detail (an EfficientNet image tower, a BERT text tower) but the loss is the same symmetric InfoNCE.
| Model | Image encoder | Text encoder | Pairs | Curation |
|---|---|---|---|---|
| CLIP | ViT / ResNet | Transformer | M | filtered |
| ALIGN | EfficientNet | BERT | B | raw alt-text |
Together, the two show that the contrastive recipe tolerates enormous label noise, provided the batch is large enough that the signal on the diagonal outvotes the noise off it.
Sharpening and scaling the contrastive recipe
CLIP fixed the recipe; the work since refined the loss and the data without touching the dual-encoder idea. Two changes are now standard.
SigLIP replaces the softmax with a sigmoid. CLIP's symmetric InfoNCE needs the full similarity matrix, because each row's softmax normalizes over every caption in the batch, which couples the whole batch and makes very large batches a memory and communication problem. SigLIP swaps the softmax cross-entropy for an independent sigmoid loss on each pair: every image-text pair is a binary match or not
decision, positive on the diagonal and negative off it, with no row-wise normalization.6 Because the pairs decouple, the loss shards cleanly across devices and trains well at both small and enormous batch sizes, and it tends to be more robust than the softmax at the batch sizes most teams can actually afford.
Contrastive encoders became the vision front-end of language models. The most consequential downstream use of CLIP is not zero-shot classification but the fact that a frozen CLIP vision tower is the standard image encoder feeding a language model — the bridge that part two builds. The contrastive objective produces exactly the property a language model needs from vision: patch features that already live in a space aligned to text, so a thin projector can map them into token space. The refinements above (a better loss, cleaner or larger data) propagate straight through: a stronger contrastive encoder makes a stronger vision-language model, which is why the contrastive route and the fusion route are two halves of one pipeline rather than competing designs.
In short, the dual-encoder contrastive model is the durable core of multimodal learning. Its loss got cheaper to scale (SigLIP), its data got larger (ALIGN and successors), and its output became the input to the fusion models of part two. The picture-and-caption-as-neighbors idea outlasted every specific architecture built on top of it.
Takeaways
- A multimodal model maps images, text, and audio into one space (contrastive) or interleaves them inside a network (fusion); the residual modality gap means matched pairs are pulled together without the two clouds merging.
- The Vision Transformer turns an image into tokens: cut it into patches ( for a image at ), linearly embed each to a -vector, prepend a CLS token, add learned position embeddings, and run a standard Transformer encoder; the CLS output is the image vector.
- CLIP trains two encoders so that, over a batch, the similarity matrix has its true pairs on the diagonal; the symmetric InfoNCE loss is the mean of the row and column cross-entropies, one positive against in-batch negatives, with a learned temperature .
- Zero-shot transfer classifies by embedding
a photo of a
prompts and taking ; no gradient step, just nearest-caption retrieval. ALIGN is the same recipe at raw web scale. - Since CLIP: SigLIP swaps the coupled softmax for an independent sigmoid loss that shards across devices and trains at any batch size, and the contrastive vision tower is what feeds the vision-language models of part two.
Footnotes
- Liang et al., Mind the Gap: Understanding the Modality Gap in Multi-modal Contrastive Representation Learning, NeurIPS 2022 — shows image and text embeddings occupy separate cones on the sphere, an offset set at initialization and only narrowed by contrastive training. ↩
- Dosovitskiy et al., An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale (ViT), ICLR 2021 — patch embedding, a prepended CLS token, learned position embeddings, and a standard Transformer encoder over the patch sequence. ↩
- Radford et al., Learning Transferable Visual Models From Natural Language Supervision (CLIP), ICML 2021 — the dual-encoder contrastive recipe on M pairs, learned temperature, and zero-shot transfer competitive with supervised baselines. ↩ ↩2
- van den Oord, Li & Vinyals, Representation Learning with Contrastive Predictive Coding, 2018 — introduces the InfoNCE loss, one positive against negatives, the contrastive objective CLIP applies across modalities. ↩
- Jia et al., Scaling Up Visual and Vision-Language Representation Learning With Noisy Text Supervision (ALIGN), ICML 2021 — trains the same contrastive objective on over a billion uncurated alt-text pairs, trading data quality for data scale. ↩
- Zhai et al., Sigmoid Loss for Language Image Pre-Training (SigLIP), ICCV 2023 — replaces CLIP's batch-coupled softmax with an independent per-pair sigmoid loss that decouples across the batch and trains robustly at any batch size. ↩
╌╌ END ╌╌