Sub topic 1
Embeddings: representing images and text as vectors
Prerequisites
This chapter assumes basic Python and PyTorch tensor operations. You should also know that neural networks learn numeric representations and that a vector has both a direction and a length.
What an embedding represents
An embedding is a vector that represents an object in a way useful for comparison. An image embedding represents visual content. A text embedding represents the meaning of a phrase. The vector contains numbers such as [0.12, -0.44, 0.87, ...], but each individual number usually has no simple human-readable meaning.
An encoder is a neural network that converts an input into an embedding. CLIP uses one encoder for images and another for text. The encoders produce vectors with the same number of dimensions, such as 512 or 768. This shared size allows the vectors to be compared.
The goal is not to make every image or sentence unique. The goal is to arrange related concepts near one another. An image of a golden retriever should be closer to “a dog” than to “a mountain,” assuming the model has learned those distinctions.
Geometry of the shared space
An embedding space is the mathematical space containing the vectors. Similarity in this space is measured with a function such as the dot product or cosine similarity.
For vectors \(x\) and \(y\), cosine similarity is:
\operatorname{cos}(x,y) = \frac{x \cdot y}{\|x\|\|y\|}Here, \(x \cdot y\) is the dot product, and \(\|x\|\) is the vector's length. The result ranges from -1 to 1. A value near 1 means the vectors point in similar directions.
CLIP commonly normalizes both embeddings before comparison. Normalization changes each vector to length 1. After normalization, the dot product equals cosine similarity. This prevents a vector's magnitude from dominating the comparison.
import torch
import torch.nn.functional as F
image_embedding = torch.tensor([0.8, 0.2, 0.1])
text_embedding = torch.tensor([0.7, 0.3, 0.2])
image_embedding = F.normalize(image_embedding, dim=0)
text_embedding = F.normalize(text_embedding, dim=0)
similarity = image_embedding @ text_embedding
print(f"cosine similarity: {similarity.item():.3f}")The encoders learn this geometry during training. Matching image-text pairs are encouraged to have high similarity. Unrelated pairs are pushed apart. The resulting space supports comparisons across modalities, meaning across different input types such as images and language.
| Input | Encoder output | Possible comparison |
|---|---|---|
| Image of a bicycle | Image vector | Text vectors for “a bicycle” and “a boat” |
| “A red bus” | Text vector | Image vectors from a collection |
| Image and caption pair | Two vectors | Whether the caption describes the image |
Exercise
Exercise
Why does CLIP need image and text embeddings to have the same dimensionality?
Show answer
Equal dimensionality lets the model compare the vectors with the same similarity operation in one shared space.