Sub topic 13
Image-Text Retrieval and Semantic Search
Prerequisites and the retrieval problem
This chapter assumes that you know basic Python and PyTorch tensor operations, vector norms, dot products, and the main idea of CLIP's dual-encoder architecture.
Image-text retrieval means finding the most relevant text for an image or the most relevant images for a text query. Semantic search is retrieval based on meaning rather than exact words. For example, a query such as “children playing on a beach” can match an image captioned “kids running beside the ocean,” even though the words differ.
CLIP makes this possible by mapping images and text into the same vector space. Each item becomes an embedding, which is a vector of numbers representing its useful features.
Comparing normalized embeddings
Let an image embedding be v and a text embedding be u. CLIP first normalizes both vectors:
v' = v / ||v|| and u' = u / ||u||
Their dot product is then cosine similarity:
similarity(v, u) = v' · u'
For normalized vectors, the result is usually between -1 and 1. A larger value means that the image and text point in more similar directions in the shared space.
| Similarity score | Meaning |
|---|---|
| Higher score | The image and text are more semantically related |
| Lower score | The image and text are less related |
A retrieval system stores embeddings for a collection of images, captions, or documents. When a query arrives, it embeds the query, computes similarity with stored vectors, and returns the highest-scoring items.
Image-to-text retrieval
The following example embeds one image and ranks several text queries. The model does not compare raw pixels with raw words. It compares their learned representations.
import torch
import torch.nn.functional as F
from PIL import Image
from transformers import CLIPModel, CLIPProcessor
model_name = "openai/clip-vit-base-patch32"
model = CLIPModel.from_pretrained(model_name)
processor = CLIPProcessor.from_pretrained(model_name)
image = Image.open("photo.jpg").convert("RGB")
texts = [
"a dog playing in the snow",
"a plate of pasta on a table",
"a city skyline at night",
"a person riding a bicycle",
]
with torch.no_grad():
image_inputs = processor(images=image, return_tensors="pt")
text_inputs = processor(text=texts, return_tensors="pt", padding=True)
image_embedding = model.get_image_features(**image_inputs)
text_embeddings = model.get_text_features(**text_inputs)
image_embedding = F.normalize(image_embedding, dim=-1)
text_embeddings = F.normalize(text_embeddings, dim=-1)
scores = (image_embedding @ text_embeddings.T).squeeze(0)
ranking = scores.argsort(descending=True)
for index in ranking:
print(f"{scores[index].item():.3f} {texts[index]}")The highest-scoring text is the model's best match. The scores are useful for ranking, but they should not automatically be treated as calibrated probabilities.
Building a semantic search index
For a larger collection, compute and save each item's embedding once. At query time, compute only the new query embedding and compare it with the stored matrix.
If the stored text embeddings form a matrix E with shape (number_of_items, embedding_dimension), and the query embedding is q, then:
scores = E q
With normalized embeddings, this matrix multiplication produces cosine similarities for every item at once.
For millions of vectors, comparing against every stored vector can be slow. A vector database or an approximate nearest-neighbor index can search a smaller set of likely candidates. Approximate search is faster but can occasionally miss the exact nearest item.
Exercise
Exercise
Why should image and text embeddings be normalized before using their dot product for retrieval?
Show answer
Normalization removes the effect of vector length, so the dot product measures the angle between embeddings and therefore behaves like cosine similarity.