Sub topic 17
Using CLIP embeddings in other systems
This chapter covers how to take CLIP out of the notebook and use its embeddings as a component in search, filtering, classification, and generation systems. It assumes you can already compute image and text embeddings with a pretrained CLIP model (earlier chapters), that you know cosine similarity and normalization, and that you are comfortable with NumPy and PyTorch.
Why CLIP embeddings travel well
A pretrained CLIP model is a feature extractor with one useful property: images and text land in the same space. Several consequences follow.
- You can compute the image side once, store it, and answer many future text queries without touching the images again.
- Downstream code needs only vectors. It does not need the model's architecture, the training data, or the original class list.
- Any system that can compare, cluster, or index vectors can now work with images and text through the same interface.
Most uses fall into four patterns, shown below.
Pattern 1: A semantic search index
The most common use is text-to-image search. Embed every image once, normalize, and store the vectors. At query time, embed the text with the same model and find the nearest vectors.
Because the vectors are unit length, cosine similarity equals the dot product. This means an inner-product index gives you cosine ranking directly. In FAISS that is IndexFlatIP.
import glob
import faiss
import numpy as np
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).eval()
processor = CLIPProcessor.from_pretrained(MODEL_NAME)
@torch.no_grad()
def embed_images(paths, batch_size=32):
chunks = []
for start in range(0, len(paths), batch_size):
images = [Image.open(p).convert("RGB") for p in paths[start:start + batch_size]]
inputs = processor(images=images, return_tensors="pt")
emb = F.normalize(model.get_image_features(**inputs), dim=-1)
chunks.append(emb.cpu().numpy().astype("float32"))
return np.concatenate(chunks)
@torch.no_grad()
def embed_text(queries):
inputs = processor(text=queries, return_tensors="pt", padding=True)
emb = F.normalize(model.get_text_features(**inputs), dim=-1)
return emb.cpu().numpy().astype("float32")
paths = sorted(glob.glob("photos/*.jpg"))
vectors = embed_images(paths)
index = faiss.IndexFlatIP(vectors.shape[1]) # inner product == cosine on unit vectors
index.add(vectors)
faiss.write_index(index, "photos.index")
scores, ids = index.search(embed_text(["a dog playing in the snow"]), 5)
for score, i in zip(scores[0], ids[0]):
print(f"{score:.3f} {paths[i]}")FAISS returns row positions, not file names. The paths list is the mapping from row to image. Persist it next to the index (for example as a JSON file), and keep the order identical.
Choosing an index type
An exact (flat) index compares the query against every vector. That is fine up to roughly a few hundred thousand vectors on a CPU. Beyond that, use an approximate index.
| Index | Behavior | Typical use |
|---|---|---|
| Flat (exact) | Exact results, linear scan | Under ~100k to ~500k vectors, or as a ground truth for testing |
| IVF | Clusters vectors, searches only the nearest clusters | Millions of vectors, tunable recall versus speed |
| HNSW | Graph-based navigation | Low latency, high recall, more memory |
| Product quantization | Compresses vectors | Very large collections where memory is the limit |
Measure recall of an approximate index against the flat index on a sample of real queries before you ship it.
Pattern 2: Features for a supervised head
If you have labels, the embeddings work as input features. You can train logistic regression, a small MLP, or a k-nearest-neighbors classifier on frozen image vectors. This is the same idea as the linear-probe evaluation from the previous chapter, used here as a product component.
This approach has practical advantages:
- Training takes seconds to minutes, because the encoder is frozen and the vectors are cached.
- A few dozen labeled examples per class are often enough to beat zero-shot prompts on a narrow domain.
- You can initialize the classifier weights from the text embeddings of the class prompts, then fine-tune on the few labeled examples you have.
Cache the vectors on disk. Recomputing them for every experiment is the usual waste of time here.
Pattern 3: Scoring, filtering, and deduplication
Cosine similarity between an image and its caption measures how well they agree. Pipelines use this to clean data.
- Caption quality filtering. Drop pairs whose similarity is below a threshold. Public web-scale datasets have been filtered this way with CLIP scores.
- CLIPScore. An evaluation metric for generated captions and images. It is
max(0, 100 * cos)in the original reference-free definition, with a 2.5 weight in some formulations. State the formula you use, because papers differ. - Near-duplicate detection. Two images whose embeddings have cosine similarity near 1 are very likely the same or lightly edited. Compare within batches or use the index to find neighbors above a threshold.
import numpy as np
def near_duplicates(vectors, threshold=0.95):
"""Return (i, j, score) pairs with cosine similarity above threshold.
vectors: float32 array of shape (n, dim), already L2-normalized.
Uses a full n x n matrix, so use it only for a few thousand rows.
"""
sims = vectors @ vectors.T
rows, cols = np.where(np.triu(sims, k=1) > threshold)
return [(int(i), int(j), float(sims[i, j])) for i, j in zip(rows, cols)]Choose the threshold from data. Look at pairs around candidate cutoffs and decide where "same image" turns into "same subject". A threshold of 0.95 is a starting point, not a standard.
Pattern 4: Conditioning other models
Other models take CLIP outputs as inputs.
- Text-to-image diffusion models such as Stable Diffusion condition on the output of a CLIP text encoder. The model sees the token-level hidden states, not only the single pooled vector.
- Many vision-language chat models use a CLIP-style image encoder as their eyes. A projection layer maps the image features into the language model's input space.
- Guidance methods have used CLIP similarity as a signal to steer image generation toward a text prompt.
In these systems the CLIP part is usually frozen. Whatever biases and blind spots the encoder has, the downstream model inherits them.
Operating a CLIP-based system
Several rules prevent most production bugs.
- One model for both sides. Query vectors and stored vectors must come from the same checkpoint and preprocessing. Vectors from different checkpoints are not comparable, even when the dimensions match.
- Normalize at one place. Normalize when you write to the index, and again on every query. Normalizing twice is harmless. Forgetting it on one side silently changes the ranking.
- Version the index. Store the checkpoint name, embedding dimension, and normalization choice in the index metadata. Upgrading the model means re-embedding everything.
- Mind the modality gap. Image vectors and text vectors occupy different regions of the shared space. Text-to-image similarities are therefore small in absolute terms (often 0.2 to 0.35 for good matches). Compare scores only within the same kind of query, and do not use one global threshold for both text-to-image and image-to-image search.
- Batch and use half precision on GPU. Embedding is the expensive step. Batching and
float16roughly double throughput, with a small effect on ranking. - Combine with metadata. Pure embedding search ignores dates, owners, and permissions. Filter on metadata first or alongside the vector search, particularly where access control matters.
Common failure modes
- Counting and spatial queries. "Three red cups to the left of a book" retrieves images with cups and books, not the stated arrangement.
- Text in images. CLIP can read some large, clear text, but search by OCR content is unreliable. Use a dedicated OCR pipeline when the words matter.
- Domain shift. Medical, satellite, or industrial images may cluster poorly. Evaluate on your own labeled queries before committing.
- Prompt sensitivity. Short queries such as "dog" often rank differently from "a photo of a dog". Test a template on your queries, as in the prompt chapter.
Exercise
You built a text-to-image search with IndexFlatIP over normalized clip-vit-base-patch32 image vectors. A teammate upgrades the query service to a larger CLIP checkpoint with the same embedding dimension, but leaves the stored index unchanged. Results look plausible but are much worse. What went wrong, and what is the fix?
Show answer
The query vectors and the stored image vectors now come from different models. Their coordinate systems are unrelated, so the dot products no longer measure image-text agreement. The matching dimension hides the mismatch, so no error is raised. The fix is to re-embed all images with the new checkpoint and rebuild the index, or to keep using the original checkpoint for queries. Storing the checkpoint name in the index metadata and checking it at startup prevents this.