Sub topic 13
Image-text retrieval and semantic search
This chapter assumes you know how CLIP produces normalized image and text embeddings, what cosine similarity measures, and basic PyTorch tensor operations. It builds on those ideas to show how retrieval works: you rank items by similarity in the joint embedding space. It also covers how to scale the ranking and where it goes wrong.
Retrieval as nearest-neighbor search
CLIP maps images and text into one vector space. A caption and a matching photo end up close together, so retrieval reduces to one question: which stored vectors are nearest to the query vector?
There are two common directions:
- Text-to-image retrieval. The query is text. The candidates are image embeddings.
- Image-to-text retrieval. The query is an image. The candidates are text embeddings, such as captions or labels.
A third case, image-to-image search, works because both vectors come from the same image encoder. It does not use text at all.
Because the vectors are normalized, cosine similarity equals the dot product. Scoring one query against N candidates is therefore one matrix multiplication.
The two-stage pattern: index offline, query online
The dual-encoder design makes retrieval cheap. The image encoder and text encoder never look at each other's input. You can therefore split the work in two.
- Offline. Encode every image once and store the embeddings.
- Online. Encode only the query, then compare it with the stored vectors.
The expensive step, running a Vision Transformer over every image, happens once. A query costs one text-encoder pass plus a similarity search.
Building a small search index
The code below indexes a folder of images and answers text queries. It processes images in batches and keeps the embeddings in one tensor.
from pathlib import Path
import torch
import torch.nn.functional as F
from PIL import Image
from transformers import CLIPModel, CLIPProcessor
device = "cuda" if torch.cuda.is_available() else "cpu"
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32").to(device).eval()
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
@torch.no_grad()
def embed_images(paths, batch_size=32):
chunks = []
for start in range(0, len(paths), batch_size):
batch = [Image.open(p).convert("RGB") for p in paths[start:start + batch_size]]
inputs = processor(images=batch, return_tensors="pt").to(device)
emb = model.get_image_features(**inputs)
chunks.append(F.normalize(emb, dim=-1).cpu())
return torch.cat(chunks)
@torch.no_grad()
def embed_text(queries):
inputs = processor(text=queries, return_tensors="pt", padding=True, truncation=True).to(device)
return F.normalize(model.get_text_features(**inputs), dim=-1).cpu()
def search(query, image_emb, paths, k=5):
q = embed_text([query]) # (1, dim)
scores = (q @ image_emb.t()).squeeze(0) # (num_images,)
top = scores.topk(min(k, len(paths)))
return [(paths[i], s) for s, i in zip(top.values.tolist(), top.indices.tolist())]
paths = sorted(Path("images").glob("*.jpg"))
image_emb = embed_images(paths)
torch.save(image_emb, "image_index.pt")
for path, score in search("a dog playing in the snow", image_emb, paths):
print(f"{score:.3f} {path}")Note three details:
- Embeddings are normalized once at index time. If you skip this, dot products no longer equal cosine similarity, and images with large vector norms win the ranking regardless of content.
- The scores here are raw cosine similarities, not logits scaled by the temperature. For ranking you do not need the scale, since multiplying all scores by a positive constant never changes their order.
topkreturns the highest-scoring items already sorted.
Scoring and what the numbers mean
Raw CLIP cosine similarities for good matches are often low. Values around 0.2 to 0.35 are typical for the ViT-B/32 model. This is a property of the contrastive training: the model only learns that the true pair scores higher than the others in the batch, not that it reaches some absolute value.
This has two consequences.
- Ranks are meaningful, absolute scores are not. A score of 0.28 is not "28% match." Compare scores only within one model and one query.
- A fixed threshold is fragile. If you want to return "only good matches," calibrate the threshold on labeled examples from your own data. Do not copy a number from another project.
Scores from different queries are also not comparable. A short, generic query such as "dog" can produce a different score range than a long, specific caption.
Evaluating retrieval: Recall@K
The standard metric for retrieval benchmarks such as Flickr30k and MS-COCO is Recall@K. For each query, check whether a correct item appears in the top K results. Then average over all queries.
import torch
def recall_at_k(sim, k):
"""sim: (num_queries, num_items); the correct item for query i is item i."""
ranks = sim.argsort(dim=1, descending=True)
targets = torch.arange(sim.size(0)).unsqueeze(1)
hits = (ranks[:, :k] == targets).any(dim=1)
return hits.float().mean().item()
# Example with random normalized embeddings plus matched noise
torch.manual_seed(0)
base = torch.nn.functional.normalize(torch.randn(100, 64), dim=-1)
noisy = torch.nn.functional.normalize(base + 0.3 * torch.randn(100, 64), dim=-1)
sim = base @ noisy.t()
for k in (1, 5, 10):
print(f"R@{k}: {recall_at_k(sim, k):.2f}")Report both directions, text-to-image and image-to-text, because they differ. In image-to-text retrieval, each image usually has about five reference captions, and a hit on any one counts. In text-to-image retrieval, each caption has exactly one correct image. The two tasks are therefore not symmetric, and their numbers should not be compared directly.
Scaling beyond brute force
A matrix multiplication against 100,000 vectors of dimension 512 is fast. At tens of millions of vectors, memory and latency become the problem. You then trade exactness for speed with approximate nearest-neighbor (ANN) search.
| Approach | How it works | Trade-off |
|---|---|---|
| Exact (flat) search | Compare the query with every vector | Perfect recall, cost grows linearly with the collection |
| IVF | Cluster vectors, search only the nearest clusters | Fast, misses items near cluster borders |
| HNSW | Navigate a layered graph of neighbors | Very fast queries, higher memory use |
| Product quantization | Compress vectors into short codes | Small memory, lower accuracy |
Libraries such as FAISS implement all of these. For normalized vectors, use an inner-product index, which is equivalent to cosine similarity.
import faiss
import numpy as np
emb = np.load("image_embeddings.npy").astype("float32") # (N, dim), already normalized
index = faiss.IndexFlatIP(emb.shape[1]) # exact inner-product search
index.add(emb)
query = np.random.randn(1, emb.shape[1]).astype("float32")
query /= np.linalg.norm(query, axis=1, keepdims=True)
scores, ids = index.search(query, 5)
print(ids[0], scores[0])Start with exact search and switch only when measured latency requires it. ANN indexes lose some recall, and you should measure that loss against the exact results on a sample of queries.
Improving search quality
Several practical changes help without retraining.
- Prompt the query. Short labels work better when wrapped in a caption-like form, for example "a photo of a red bicycle." CLIP was trained on captions, not keywords.
- Average multiple phrasings. Encode several versions of a query, average the normalized vectors, then normalize again.
- Rerank. Use CLIP to fetch the top 100 candidates, then apply a slower and more precise model to reorder them.
- Combine with metadata filters. Filter by date, owner, or category first, then rank by similarity within the filtered set. Embeddings should not replace structured filters.
- Query by image and text together. Add the image embedding and the text embedding, then renormalize. This gives "like this picture, but at night." Results are approximate, since the sum has no guaranteed meaning.
Common errors and failure modes
- Forgetting to normalize. Query vectors and index vectors must be normalized the same way. A mismatch silently distorts the ranking.
- Truncated text. CLIP's text encoder accepts at most 77 tokens. Longer captions are cut off, so details at the end are ignored. Pass
truncation=Trueto avoid errors, and keep queries short. - Counting and spatial relations. Queries like "three cats on the left" often return images with cats in any arrangement. CLIP behaves partly like a bag of concepts.
- Negation. "A street without cars" tends to retrieve streets with cars, since the word "cars" dominates the embedding.
- Text in images. CLIP can read some printed text, which sometimes drives results. A photo of a sign saying "dog" may match the query "dog."
- Dataset bias. Web-scale training data carries social biases. Search results for terms about people can reflect stereotypes, so audit results before putting them in front of users.
- Hubness. In high-dimensional spaces, a few vectors appear in the top results for many unrelated queries. If the same images show up everywhere, consider normalizing scores per item against a set of reference queries.
Exercise
You normalize image embeddings at index time but forget to normalize the text query embedding. The ranking of images for that single query is unchanged. Why, and what does change?
Show answer
Dividing the query vector by its norm multiplies every dot product by the same positive constant, so the order of the images for that one query stays the same. What changes is the score values: they are no longer cosine similarities, so they cannot be compared across queries or used with a fixed threshold. Ranking is safe. Thresholding and cross-query comparison are not.
Exercise
A text-to-image search system has 20 million images. Exact search takes 400 ms per query, and your target is 50 ms. Name one approach to try first, and one check you must run before deploying it.
Show answer
Try an approximate index such as HNSW or IVF with a FAISS inner-product index on normalized vectors. Before deploying, compare its top-K results against exact search on a sample of real queries, and measure the recall loss, so you know how many correct results the faster index misses.