Sub topic 3
The idea of a joint image-text embedding space
This chapter assumes you know basic PyTorch tensor operations, what an embedding is, and how the dot product and vector norm work. It also assumes you understand softmax and cross-entropy at a high level. It covers one idea: why one vector space can hold both images and text, and what that space lets you do. Later chapters cover the architecture and the loss in detail.
From two spaces to one
A single-modality model maps its input to a vector. An image classifier's penultimate layer gives a vector for each image. A language model gives a vector for each sentence. These two spaces are unrelated. The axes of the image space mean nothing in the text space, and a distance between an image vector and a text vector is meaningless.
A joint embedding space is a single vector space where both kinds of input land. A photo of a dog and the caption "a dog running on grass" map to nearby points. The photo and the caption "a bowl of soup" map to distant points. Two separate encoders produce the vectors, but training forces them to agree on one geometry.
The word "joint" describes the shared coordinates. Dimension 17 of an image vector and dimension 17 of a text vector are comparable, because training made them so.
What the geometry means
In the joint space, similarity between vectors stands in for semantic agreement between an image and a text. The usual measure is cosine similarity, the dot product of two unit-length vectors. Its value lies between -1 and 1. A higher value means the image and text describe the same thing.
This gives you one operation that covers several tasks:
| Task | What you compare | What you pick |
|---|---|---|
| Zero-shot classification | One image against one text per class | The class with the highest similarity |
| Text-to-image retrieval | One text query against many images | The top-k most similar images |
| Image-to-text retrieval | One image against many captions | The top-k most similar captions |
| Image-image search | Image vectors against each other | The nearest neighbors |
Every row reduces to "embed, normalize, compare." No task needs its own output head.
Why this enables open-vocabulary recognition
A standard classifier has a fixed output layer with one row of weights per class. If it was trained on 1,000 classes, it can only name those 1,000. Adding a class means collecting labels and retraining.
In a joint space, the class is not a fixed output unit. It is a piece of text that you embed at inference time. To recognize "axolotl," you encode the prompt "a photo of an axolotl" and compare it with the image vector. The text encoder acts as a generator of classifier weights from natural language. This is called open-vocabulary recognition, because the label set is whatever you can write down.
This works only if the model saw enough varied text during training to place unseen phrases sensibly. The joint space is useful because language already carries structure. Words like "puppy" and "dog" are close in text space, so images of puppies land near images of dogs without anyone labeling that relationship.
A tiny numerical picture
Take a 2-dimensional space to see the mechanism. The numbers are made up for illustration.
import torch
import torch.nn.functional as F
# Pretend outputs of the two encoders, already in the same 2-D space.
image_emb = torch.tensor([[0.9, 0.1], # photo of a dog
[0.1, 0.9]]) # photo of a car
text_emb = torch.tensor([[1.0, 0.0], # "a photo of a dog"
[0.0, 1.0]]) # "a photo of a car"
image_emb = F.normalize(image_emb, dim=-1)
text_emb = F.normalize(text_emb, dim=-1)
sim = image_emb @ text_emb.t() # (2 images, 2 texts)
print(sim)
print(sim.argmax(dim=1)) # best text for each imageThe diagonal entries are close to 1 and the off-diagonal entries are close to 0. The argmax along each row gives the correct caption for each image. In a real model the space has 512 or more dimensions, but the comparison is the same.
Notice that the code never uses labels. It only compares vectors. This is the same computation CLIP performs for zero-shot classification at inference time.
How training builds the space
Nothing about two separate encoders creates a shared space on its own. Two randomly initialized networks produce unrelated outputs. The shared geometry comes from the training objective.
The objective takes a batch of N image-text pairs. It computes all N × N similarities between the batch's images and texts. Each image should be most similar to its own caption (the diagonal) and less similar to the other N − 1 captions. Each caption should likewise prefer its own image. Gradients flow into both encoders, so each one moves its outputs toward where the other puts the matching item.
The pressure runs both ways:
- Matching pairs are pulled together.
- Non-matching pairs in the batch are pushed apart.
After many steps on a large dataset, the encoders agree on a coordinate system. The later chapters on contrastive learning and the symmetric loss derive this precisely. For now, remember that the space is learned from pairing, and pairing is the only supervision.
Properties and edge cases
The joint space is useful, but it has features you should know before relying on it.
The modality gap
Image vectors and text vectors do not mix evenly. In practice, the image embeddings cluster in one region of the sphere and the text embeddings cluster in another, with a visible offset between them. This is called the modality gap. Matching pairs are still closer to each other than to non-matching pairs, so ranking works. But absolute similarity values are small. CLIP image-text cosine similarities for good matches are often around 0.2 to 0.35, not near 1. Do not treat a cosine of 0.3 as a weak match without comparing it against the alternatives.
Similarity is relative
Because of the gap and the temperature scaling used in training, raw cosine values from different models, or different prompts, are not comparable. Use them to rank candidates for one query. To get probabilities, softmax across the candidates, as zero-shot classification does. A softmax over one candidate is always 1, so a single-class check needs a reference set of alternatives or a calibrated threshold.
Text must be in the training distribution
The text encoder in CLIP has a limited context length of 77 tokens. Long descriptions are truncated. The model also learned from web captions, which are short and noun-heavy, so it responds better to "a photo of a red bus" than to a long paragraph. Phrasing matters, and a later chapter on prompts covers it.
Bag-of-words behavior
The space captures what objects and concepts are present better than how they relate. "A horse riding an astronaut" and "an astronaut riding a horse" often land at nearly the same point. The joint space compresses a lot of meaning into one vector, and word order and attribute binding suffer. The limitations chapter returns to this.
Normalization is part of the definition
Comparisons use unit-length vectors. If you skip normalization, vectors with a large norm dominate dot products, and the score no longer measures direction alone. Always normalize before you compare, as in the example above.
Two ways to use the space
It helps to separate how you use the space from how it was built.
- Cross-modal use compares an image vector with a text vector. This covers zero-shot classification and text-to-image search.
- Same-modality use compares two image vectors or two text vectors. This covers duplicate detection, clustering, and nearest-neighbor search. The shared training makes these vectors semantic, so they often work better than features from a classifier trained on a fixed label set.
Both rely on the same property: distance in the space tracks meaning.
Summary of the idea
A joint embedding space replaces a fixed classifier head with a similarity comparison between vectors from two encoders. Training on paired data aligns the encoders. After training, language works as an interface to vision, because any text you can write becomes a vector you can compare with images.
Exercise
Your teammate adds a new class, "axolotl," to a CLIP-based classifier by writing the prompt "a photo of an axolotl" and comparing it with image embeddings. They report that a photo of an axolotl scores a cosine similarity of 0.27 and conclude the model failed because 0.27 is far from 1. What is wrong with this conclusion, and how should they check whether the model worked?
Show answer
Absolute cosine values in CLIP are low even for correct matches, because of the modality gap and the temperature-scaled training, so 0.27 can be a good score. The right check is relative: compute the similarity of the image against the prompts for all candidate classes and see whether "axolotl" ranks highest, usually by taking a softmax over the scaled similarities. A single score has no meaning without the alternatives to compare it against.
Exercise
Why can a joint image-text space recognize a class that never appeared as a label during training, while a standard classifier with a fixed output layer cannot?
Show answer
A fixed classifier has one learned weight row per training class, so it can only output those classes. In a joint space, the class is represented by the text encoder's embedding of a prompt at inference time. Any phrase the text encoder can embed becomes a usable class vector, and the image is matched to it by similarity. This works to the extent that training on paired image-text data placed related concepts near each other.