Multimodal learning: how CLIP puts images and text in one space

Once images and texts live in the same vector space, "which caption fits this photo?" and "which photo fits this caption?" both become a question of distance. Count CLIP's loss step by step on a table of 4 images × 4 texts.

Short answer. In CLIP, an image encoder and a text encoder each produce a vector, and training pulls matching image and text together and pushes non-matching ones apart within a batch. In the batch's N × N similarity table the diagonal holds the right answers, and the loss is the average of the cross-entropy along rows and along columns. Once trained, you can classify just by writing class names as sentences (zero-shot classification).

Rows are images and columns are texts. The darker the green, the larger the value. The orange outline marks the true pairs (the diagonal). The vectors are made up, three numbers each, and are not values produced by a real CLIP. So the numbers are illustrative (not real measurements).

Try this. 1) As it starts (τ = 0.10), press "Next": row 1 (red circle) gives its pair "a red circle" 93% and "a yellow star" 7%, and the loss is 0.07. Keep going: row 4 (the yellow star image) gives its pair 59% and "a green triangle" 37%, so its row loss, 0.53, is the largest. At the end, L_image 0.20, L_text 0.20, L = 0.20. 2) Lower τ to 0.05 and row 1 sharpens to 100% with L = 0.09. Raise it to 1 and row 1 flattens to 35% with L = 1.09. 3) At τ = 0.10, press "Misalign one text": the text "a yellow star" moves toward the red circle, row 1 splits 52% and 48%, and L rises from 0.20 to 0.65. In this state, lowering τ to 0.05 raises L further, to 1.01. A low temperature makes the loss smaller when right and larger when wrong.

Definitions

The text below explains with the three-entry vectors in the lab. Here are the definitions of the ideas this page uses. A batch has N image-text pairs, the vector of image i is Ii, and the vector of text j is Tj. The pair of image i is text i.

modality, multimodal learning
Each kind of data, such as images, text or sound, is a modality. Learning that handles two or more modalities together in one model is multimodal learning.
contrastive learning
A way of learning by comparison, so that the vectors of pairs to be close (positive pairs) land close and the vectors of the other pairs (negative pairs) land far apart. In CLIP, the N pairs in a batch are positive pairs and the other N² − N are negative pairs.
cosine similarity
The dot product of two vectors divided by the product of their lengths. It is the cos of the angle between them and lies between −1 and 1.

sij=Ii·Tj‖Ii‖‖Tj‖

temperature
A positive number τ that divides the similarities before the softmax. The smaller τ is, the more the probability gathers in the largest cell. The larger it is, the more evenly it spreads. The softmax pij within row i and qij within column j are below.

pij=exp(sij/τ)∑k=1Nexp(sik/τ)

qij=exp(sij/τ)∑k=1Nexp(skj/τ)

symmetric cross-entropy loss
A loss that takes the diagonal of the N × N similarity table as the right answers and averages the cross-entropy along rows (image → text) and along columns (text → image). CLIP trains both encoders together with this loss.

Limage=−1N∑i=1Nlogpii

Ltext=−1N∑i=1Nlogqii

L=Limage+Ltext2

zero-shot classification
Classifying without training on a single labeled example. In CLIP, each candidate class name is put into a prompt template to make a sentence, each sentence gets a text vector, and the answer is the class of the sentence whose cosine similarity with the image vector is largest. The answer can only come from the candidates you wrote.

1. What multimodal learning is: handling different kinds of data together

Each kind of data, such as images, text or sound, is called a modality. Handling different kinds of data together in one model is multimodal learning. Tasks that connect two modalities belong here, like "pick the text that describes this photo" or "find photos from a text".

The hard part is that the two kinds of data look nothing alike. An image is a grid of pixels and a text is a line of tokens. So usually each modality gets its own neural network, an encoder (the part that turns data into a vector). But if you train the two encoders separately, an image vector and a text vector can have the same length and still not mean the same thing slot by slot, so you cannot compare them. The two must be trained together to land in the same space. CLIP is one way to do that.

2. CLIP's idea: two encoders, one space

CLIP is a model trained from scratch on 400 million image-text pairs collected from the internet, by solving the task "which text goes with which image" (Radford et al., 2021). The image encoder turns an image, and the text encoder turns a text, into vectors of the same length: embeddings. Training changes both encoders together so that the two vectors land close when they are a pair and far apart when they are not. The pairs to pull together are positive pairs, the rest to push apart are negative pairs, and learning by comparing them like this is called contrastive learning.

image a red circle text image encoder text encoder one embedding space not a pair: far pair: close ● image vector ○ text vector
Each encoder turns its own data into a vector in the same space. Training places the red circle image close to the text "a red circle", and far from the blue square's text (the hollow blue dot). The dot positions are illustrative (not real measurements).

The paper stresses that it learned from natural language rather than a fixed set of labels. Because it learned from text, you can refer to visual concepts it has learned, or describe new ones, in words, and use that to solve other tasks. That is the zero-shot classification in section 4.

3. Training: the N × N similarity matrix and symmetric cross-entropy

A batch holds N image-text pairs. Put the N images into the image encoder and the N texts into the text encoder, and measure the cosine similarity (how much two vectors point the same way) between every image and every text: you get an N × N table. Image i's pair is text i, so the N diagonal cells are the right answers (positive pairs), and the other N² − N cells are negative pairs. The right answers come from inside the batch, with no extra labels.

Next, turn the similarities into probabilities and treat it as a guessing game. Row i asks "which of the N texts is image i's pair?", and column j asks "which of the N images is text j's pair?". Both directions get a cross-entropy loss, and the two are averaged.

similarity      s_ij = cos(I_i, T_j) = (I_i · T_j) ÷ (‖I_i‖ ‖T_j‖)
row softmax     p_ij = exp(s_ij / τ) ÷ (exp(s_i1 / τ) + … + exp(s_iN / τ))
column softmax  q_ij = exp(s_ij / τ) ÷ (exp(s_1j / τ) + … + exp(s_Nj / τ))
row loss        L_image = −(log p_11 + log p_22 + … + log p_NN) ÷ N
column loss     L_text = −(log q_11 + log q_22 + … + log q_NN) ÷ N
loss            L = (L_image + L_text) ÷ 2

Temperature τ. Dividing similarities by a small τ widens the gaps between cells, so the softmax piles onto the largest cell (sharp). A large τ spreads the probability evenly (flat). It is the same calculation as the temperature an LLM uses when picking the next token (sampling). Cosine similarity stays between −1 and 1, so with τ = 1 the probabilities stay close to even (the 35% in "Try this" 2). That is why a small τ is needed, and CLIP does not fix τ but learns it during training (paper section 2.3; section 2.5 says it starts at 0.07).

In code it is a few lines. Below is widely used PyTorch-style pseudocode (not code copied from the paper).

image_vectors = F.normalize(image_encoder(images), dim=-1)   # N × d, length 1
text_vectors = F.normalize(text_encoder(texts), dim=-1)      # N × d
logits = image_vectors @ text_vectors.T / tau                # N × N, cell = s_ij / τ
labels = torch.arange(N)                                     # right answers on the diagonal: image i pairs with text i
loss = (F.cross_entropy(logits, labels)                      # rows: image → text
        + F.cross_entropy(logits.T, labels)) / 2             # columns: text → image

The dot product of length-1 vectors equals their cosine similarity, so one matrix multiplication gives the whole N × N table. The rows of logits.T are the columns of the original table, so calling the same function again gives the column loss.

4. Zero-shot classification: class names as sentences

Here is how a trained CLIP classifies an image. It answers without being shown a single labeled example, so it is called zero-shot classification.

  1. Make sentences. Put each class name into a prompt template (a sentence pattern) such as a photo of a {class}.
  2. Turn them into vectors. The sentences go into the text encoder and the image to classify goes into the image encoder.
  3. Compare. Measure the cosine similarity between the image vector and each sentence vector, and turn them into probabilities with a softmax. This is the same as computing one row of the table in experiment 1.
  4. Answer. The class of the most similar sentence is the answer.
class and sentencesimilarityprobability

As in experiment 1, the image and sentence vectors are made up, three numbers each, and are not values produced by a real CLIP. The temperature is fixed at τ = 0.10.

Try this. 1) Pick the red circle: "circle" has similarity 0.99 and 60%, "heart" 0.95 and 39%. The answer is circle, but candidates with similar sentence vectors share the probability. 2) Pick the yellow star: there is no star among the candidates, so it answers "triangle" with 89%. Wrong, yet confident. 3) With the star still picked, press the add-class button: star becomes the answer with similarity 1.00 and 70%, and triangle drops to 27%. No training happened at all. Pick the green triangle: once star is in, triangle drops from 99% to 76%. Adding a candidate changes the other candidates' probabilities too.

Adding a new class means adding one sentence, and the weights of both encoders stay as they are. A classifier trained on a fixed set of labels would need labeled data for the new class and another round of training. On the other hand, as "Try this" 2 shows, zero-shot classification picks only from the candidates you write down. If the right class is not on the list, it answers with the closest other class.

The paper evaluated this on over 30 computer vision datasets (OCR, action recognition in videos, geo-localization, fine-grained object classification and more), and reports that its zero-shot accuracy on ImageNet matched the original ResNet-50, which was trained on 1.28 million labeled examples.

5. Which one when

OptionGoodBadUse when
Classifier trained on fixed labelsTrained for that class list and that dataAdding a class means collecting labeled data and training againThe classes are fixed and you have labeled data
CLIP zero-shot classificationWriting a class name as a sentence makes it a candidate. No trainingCannot answer outside the candidates you wrote, and picks the closest one even when it is wrong ("Try this" 2)You have no labeled data or the classes change often. Measure first, then use
Search with CLIP embeddingsImages and texts share one space, so a text can find images and an image can find similar imagesNeeds vectors made in advance and a separate way to find the close onesImage search, picking a caption that fits an image

Where it is used

Any neural network that turns data into a vector can sit in an encoder's place. Convolutional networks or a vision transformer on the image side, and a transformer on the text side, are examples.

Frequently asked

Does CLIP generate images?

No. CLIP turns images and texts into vectors and measures how similar two vectors are. So what it can do is pick and search. Making images is the job of generative models such as diffusion models.

Does zero-shot mean there is no training at all?

There is pre-training. CLIP was trained on 400 million image-text pairs collected from the internet. Zero-shot means it answers without seeing a single labeled example of the task at hand. A new class is just one more sentence, and the weights stay as they are.

Why compute the loss twice, along rows and along columns?

The row direction makes each image pick its text, and the column direction makes each text pick its image. Even on the same similarity table, the softmax divides by a different sum along a row than along a column, so the two numbers differ. Averaging them weighs both directions the same.

Words

Plain words used hereTextbook term
handling different kinds of data togethermultimodal learning
a kind of data (image, text, sound)modality
a neural network that turns data into a vectorencoder: image encoder, text encoder
the vector data is turned intoembedding
a pair to pull together · the rest to push apartpositive pair · negative pair
learning by comparing pairs with the restcontrastive learning
how much two vectors point the same waycosine similarity
turning scores into probabilities that add up to 1softmax
the number that sharpens or flattens the probabilitiestemperature
the average of the row loss and the column losssymmetric cross-entropy
the N pairs looked at at oncebatch
classifying from class names alone, with no exampleszero-shot classification
a sentence pattern to put the class name inprompt template

Sources

← Vision Transformer (ViT)Autoencoders and VAEs →