Sub topic 3
CLIP and Joint Image-Text Embeddings: Prompt Templates and Beyond
This chapter assumes you know PyTorch tensors, cosine similarity, and the basic idea of a CLIP model, which maps images and text into one shared vector space. Code runs with transformers and torch installed.
Prompt templates and prompt ensembling
A prompt template is a sentence pattern, such as "a photo of a {}.", that wraps a class name before it goes to the text encoder. Small wording changes can shift the score. Prompt ensembling averages the embeddings from several templates, which gives a steadier class embedding.
import torch
import torch.nn.functional as F
from transformers import CLIPModel, CLIPProcessor
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
templates = ["a photo of a {}.", "a blurry photo of a {}.", "a close-up photo of a {}."]
classes = ["cat", "dog", "car"]
with torch.no_grad():
class_embs = []
for name in classes:
inputs = processor(text=[t.format(name) for t in templates],
return_tensors="pt", padding=True)
emb = F.normalize(model.get_text_features(**inputs), dim=-1)
class_embs.append(F.normalize(emb.mean(dim=0), dim=-1))
text_matrix = torch.stack(class_embs) # (num_classes, dim)Image-text retrieval and semantic search
Retrieval ranks items by cosine similarity between an image embedding and text embeddings, or the reverse. For small collections, a matrix product is enough. For millions of items, store the normalized vectors in an approximate nearest-neighbor index such as FAISS.
Linear probes and evaluating learned features
A linear probe freezes the image encoder and trains a single linear classifier, such as logistic regression, on its embeddings. Accuracy from a probe measures how much useful information the features contain. Zero-shot accuracy measures the text-driven classifier without any training.
Limitations, biases, and failure modes
CLIP inherits biases from its web-scraped captions, including stereotypes about gender, race, and occupation. It often fails at counting, reading text in images, and fine-grained distinctions, such as specific bird species. It can also match an image to text that describes a different object, so treat its scores as relative rankings, not calibrated probabilities.
Successors and variants: OpenCLIP, ALIGN, SigLIP
OpenCLIP is an open-source reimplementation trained on public datasets such as LAION. ALIGN, from Google, trains on a very large set of noisy alt-text pairs. SigLIP replaces the softmax contrastive loss with a per-pair sigmoid loss, which removes the need for a large normalized batch softmax.
Using CLIP embeddings in other systems
CLIP embeddings work as generic features. Common uses include storing vectors in a database for search, clustering photo collections, adding a lightweight classifier on top, and filtering or ranking images in multimodal pipelines.
Exercise
Exercise
Why does prompt ensembling average normalized embeddings rather than raw text embeddings before comparing a class to an image?
Show answer
Normalizing each template embedding gives every prompt equal weight, so no template dominates because of its vector length. Normalizing the average then keeps the class vector on the unit sphere, so the dot product with a normalized image embedding equals cosine similarity.