Skip to main content
Open In Colab The representation learning section trained an encoder with a contrastive loss. Two augmented views of the same image formed a positive pair, the other images of the batch were negatives, and the augmentation decided which properties of the image the embedding kept. CLIP (Contrastive Language-Image Pretraining) keeps the loss and changes the views (Radford et al., 2021). One view is an image, and the other is a piece of text written about it on the web, usually a caption or alt text. The embedding then keeps what the text talks about: the objects, their attributes and the scene, in the vocabulary of natural language. This section shows the CLIP loss in code and measures it on a pretrained model, then explains the parts that decide how well it trains: the learnable temperature and the number of negatives in a batch. It then probes the known weaknesses of the embedding and ends with SigLIP, the variant whose image encoder is used by many current vision language models, including SmolVLM.

Two encoders and one embedding space

CLIP has an image encoder fℓf_\ell and a text encoder ftf_t. The image encoder is a ResNet or a vision transformer, and the text encoder is a transformer that reads the caption. Each output passes through a linear projection to a shared dimension dzd_z (512 for the model used here) and is normalized to unit length. Image ii becomes zℓ(i)\mathbf{z}_\ell^{(i)}, caption jj becomes zt(j)\mathbf{z}_t^{(j)}, and the cosine similarity of the two is their dot product. A batch of six image and caption pairs. Each image embedding is compared with each caption embedding in a 6 by 6 grid of dot products. The six diagonal entries are the true pairs (green), and the thirty off-diagonal entries are negatives (red). One training batch of six pairs. The diagonal holds the true pairs, and every other entry of the grid is a negative. Figure from Torralba, Isola and Freeman (Foundations of Computer Vision, n.d.), after Radford et al. For a batch of NN pairs, CLIP computes all N2N^2 similarities and multiplies them by a scale ss: Lij=s zℓ(i)⋅zt(j).L_{ij} = s \, \mathbf{z}_\ell^{(i)} \cdot \mathbf{z}_t^{(j)}. Row ii of the matrix LL scores image ii against every caption, and the correct caption is in column ii. That is a classification problem with NN classes, and the loss is the cross-entropy with target ii. Column jj scores caption jj against every image, which is a second classification problem with target jj. The CLIP loss is the average of the two: L=12N∑i=1N[−log⁡eLii∑jeLij  −  log⁡eLii∑jeLji].\mathcal{L} = \frac{1}{2N} \sum_{i=1}^{N} \left[ -\log \frac{e^{L_{ii}}}{\sum_{j} e^{L_{ij}}} \; - \; \log \frac{e^{L_{ii}}}{\sum_{j} e^{L_{ji}}} \right]. Each half is the InfoNCE loss of the representation learning section, with the image as the anchor in the first and the caption as the anchor in the second. In code it is four lines.

The loss on a pretrained model

The cell loads the CLIP model with a ViT-B/32 image encoder, released by OpenAI, and builds a batch of ten pairs from CIFAR-10: one test image of each class, with the caption a photo of a \{class\}. The images are 32×3232 \times 32 and are enlarged to the 224×224224 \times 224 that the encoder expects, so they are harder to recognize than the photos CLIP was trained on.
Output from cell 5 The loss on this batch is 0.27, far below the 2.30 of a model that has learned nothing. Each image is most similar to its own caption, which gives the bright diagonal, but the similarities themselves are small and close together. They range from about 0.16 to 0.29, and the airplane image is almost as similar to the caption of the bird as to its own. The next part explains why such small differences still give a low loss.

Temperature

The scale ss is the inverse of a temperature, s=1/τs = 1/\tau. Cosine similarities lie between −1-1 and 11, and in practice the similarities of one image with a set of captions differ by a few hundredths. Fed to a softmax as they are, they give nearly equal probabilities to every caption, and the cross-entropy cannot fall much below log⁡N\log N however good the embedding is. Multiplying by ss stretches these small differences. CLIP learns ss along with the encoders. It is stored as log⁡s\log s, initialized to log⁡(1/0.07)\log(1/0.07), and clipped so that ss never exceeds 100. The model used here ended training at that limit. The cell shows the probabilities that image 0 (an airplane) assigns to the ten captions at three values of ss.

Negatives and batch size

Every other pair in the batch is a negative, so a batch of NN pairs gives each image N−1N - 1 negative captions. The loss of a model that has learned nothing is log⁡N\log N, and the more negatives there are, the more the loss rewards fine distinctions: telling a photo of a dog from 9 random captions is easy, telling it from 32,767 captions, some of which describe other dogs, is not. CLIP was trained with batches of 32,768 pairs on 400 million image and text pairs collected from the web. Such batches do not fit on one GPU. Each GPU embeds its share of the batch, and all embeddings are gathered on every GPU to build the full N×NN \times N matrix. A large batch also has a cost that the CIFAR-10 example makes visible. Some negatives are not really negative. In a batch with two photos of dogs, the caption of one also describes the other, and the loss pushes them apart anyway. With 32,768 web captions this matters less, because captions are rarely identical, but it is the reason why class-label captions such as the ones above make poor training data for CLIP.

What the embedding is used for

After training, the two encoders are used separately or together. Zero-shot classification embeds one caption per class and assigns an image to the class whose caption is most similar; the zero-shot section builds this classifier and measures it. A linear probe trains a logistic regression on the frozen image embeddings with labeled examples, and measures how much information the embedding holds about a task. Retrieval ranks a collection of images by their similarity to a text query, or the reverse. Vision language models such as LLaVA keep only the image encoder and feed its patch features, not the single pooled embedding, to a language model.

Failure modes

CLIP’s embedding inherits the strengths and the gaps of its training signal. A caption names what is in a photo far more often than how many there are or where they are, and the loss rewards a caption embedding that identifies the right image among NN candidates, which a bag of the right words often does. Radford et al. report weak zero-shot accuracy on counting objects and on estimating distances, and on handwritten digits, which are rare on the web. Three more failures are easy to show with a few lines of code. Word order. Yuksekgonul et al. found that CLIP and similar models often cannot tell “the horse is eating the grass” from “the grass is eating the horse”, and behave like bags of words (arXiv:2210.01936). The cell compares pairs of captions with the same words in a different order.
Swapping the roles of the words barely moves the embedding, with similarities from 0.96 to 0.99, while a caption with different content is clearly farther away (0.81). For this text encoder, which words occur matters far more than how they are arranged. The modality gap. The two encoders are trained so that true pairs are more similar than false ones, not so that an image and its caption land on the same point. Liang et al. showed that the image embeddings and the text embeddings occupy two separate regions of the sphere, the modality gap (arXiv:2203.02053). The cell compares the average similarity within each modality and across them, for the ten images and captions above.
Two different images are more similar to each other (0.75 on average) than an image is to its own caption (0.26), and two different captions are more similar still (0.84). Zero-shot classification and retrieval work anyway, because they only compare the candidates of one row: the true caption has to beat the false ones (0.26 against 0.19), not reach a fixed level. A consequence is that a similarity threshold chosen for image-to-image search does not carry over to image-to-text search. Typographic attacks. CLIP learned to read, because web images often contain text that matches their captions. Goh et al. showed that a handwritten label stuck on an apple can make CLIP classify it as the labeled object (Multimodal Neurons in Artificial Neural Networks). The cell writes a class name in white letters on CIFAR-10 test images of other classes and checks how often the zero-shot prediction follows the word.
Output from cell 10 Without the word, the zero-shot classifier gets 91% of these 200 images right. With a wrong class name written on them, it gets 3% right, and 97% of its predictions are the written word. The word fills a large part of a blurry 32×3232 \times 32 image here, which makes the attack easier than on a sharp photo, but the result shows how strongly the image embedding responds to text. Bias. The training pairs come from the web, and the embedding reflects how the web describes people. Radford et al. measured this themselves. When they added labels such as “criminal” and “animal” to a zero-shot classifier for photos of faces, a share of the photos were assigned to them, at rates that differed between racial groups and between age groups. A zero-shot classifier can be built for any list of words, including words that should not be applied to people, and nothing in the model prevents it.

SigLIP: a sigmoid loss

The softmax in the CLIP loss couples all the pairs of a batch: the probability of the true caption depends on the scores of all NN captions, so the loss of one pair cannot be computed without the whole N×NN \times N matrix, and the result depends on the batch size. SigLIP replaces it with an independent binary decision for every entry of the matrix (Zhai et al., 2023). Entry (i,j)(i, j) is a positive example if i=ji = j and a negative one otherwise, with label yij=1y_{ij} = 1 or −1-1: L=−1N∑i=1N∑j=1Nlog⁡σ ⁣(yij(s zℓ(i)⋅zt(j)+b)).\mathcal{L} = -\frac{1}{N} \sum_{i=1}^{N} \sum_{j=1}^{N} \log \sigma\!\left( y_{ij} \left( s \, \mathbf{z}_\ell^{(i)} \cdot \mathbf{z}_t^{(j)} + b \right) \right). There is a learned scale ss, as in CLIP, and a learned bias bb. Because N−1N - 1 of every NN entries are negatives, the loss would be dominated by them at the start of training, so bb is initialized to −10-10, which makes every pair start as a confident negative. Each entry is a separate term, so each GPU can compute the loss for its own block of the matrix and exchange embeddings with its neighbors, without a softmax over the whole batch. Zhai et al. found that the sigmoid loss beats the softmax loss at batch sizes below about 16,000, and that the benefit of larger batches levels off around 32,000. The cell measures the loss with SigLIP 2, which keeps the sigmoid loss and adds further training objectives (arXiv:2502.14786). The same change shows up at inference. The scores of a SigLIP model are independent probabilities, one per image and caption, and they do not have to sum to one. An image can match several captions or none.
SigLIP 2 learned a scale of 112.7 and a bias of −16.8-16.8. CLIP’s probabilities for an image sum to one by construction. SigLIP’s do not, and on these blurry thumbnails they are close to zero: the true caption of the airplane image gets a probability below 0.01, and that of the automobile 0.03. The loss of 4.06 is high for the same reason, since every true pair is scored as unlikely. The ranking is still right: for nine of the ten images, the true caption has the highest probability. A softmax would have turned the same ranking into confident probabilities. The sigmoid reports instead that none of the captions fits the image well, which is the more honest answer for a 32×3232 \times 32 picture enlarged to 224×224224 \times 224.

Exercises

  1. Compute the CLIP loss of the CIFAR-10 batch with two images of the same class (for example two cats, with two identical captions). What happens to the loss, and why is this a false negative?
  2. Train the contrastive encoder of the representation learning section with the temperature fixed at 1, 0.2 and 0.05. Plot the final loss and the embedding for each, and explain the role of the temperature.
  3. Repeat the word-order test with SigLIP. Does the sigmoid loss help? Explain why the loss alone should not be expected to fix it.
  4. Measure the typographic attack as a function of the size of the written word.

Key references

Radford et al. introduced CLIP and evaluated it on more than 30 data sets, including its failures and biases (Radford et al., 2021). Zhai et al. introduced the sigmoid loss of SigLIP (Zhai et al., 2023). Chapter 51 of Torralba, Isola and Freeman covers vision and language (Foundations of Computer Vision, n.d.).

References

  • Radford, A., Kim, J., Hallacy, C., Ramesh, A., Goh, G., et al. (2021). Learning transferable visual models from natural language supervision. arXiv [cs.CV]. Link
  • (n.d.). Foundations of Computer Vision. Link
  • Zhai, X., Mustafa, B., Kolesnikov, A., Beyer, L. (2023). Sigmoid Loss for Language Image Pre-Training. arXiv [cs.CV]. Link

Found an error on this page? Report an issue.