Sub topic 12
Prompt Templates and Prompt Ensembling
This chapter assumes that you understand CLIP embeddings, cosine similarity, softmax, and basic PyTorch tensor operations. It also assumes that a pretrained CLIP model can map images and text into the same vector space.
Why prompt wording matters
In zero-shot classification, CLIP does not receive a trained classifier for each class. Instead, you provide class names as text prompts, such as “a photo of a cat” and “a photo of a dog.” CLIP embeds the image and each prompt, then chooses the prompt with the highest similarity.
The class name alone may be ambiguous or unlike the captions used during training. A template adds context:
- “a photo of a cat”
- “a blurry photo of a cat”
- “a close-up photo of a cat”
- “a picture of a cat”
These prompts describe the same class, but they produce different text embeddings. A prompt that matches the image style and the model’s training distribution can improve accuracy.
Prompt templates
A prompt template is a sentence pattern with a class name inserted into it. For a classification task, use the same templates for every class.
For example, suppose the classes are bird, airplane, and ship:
| Template | Bird prompt |
|---|---|
| “a photo of a {}” | “a photo of a bird” |
| “a blurry photo of a {}” | “a blurry photo of a bird” |
| “a close-up photo of a {}” | “a close-up photo of a bird” |
Do not use a different number or style of prompts for different classes. That can give some classes an unfair advantage.
Prompt ensembling
Prompt ensembling combines several prompts for one class. A common method is:
- Create one prompt for every class-template combination.
- Encode all prompts with the text encoder.
- Normalize each text embedding.
- Average the embeddings belonging to each class.
- Normalize each class average again.
- Compare the image embedding with the resulting class embeddings.
The final normalization keeps cosine similarity meaningful. Another option is to compute image-to-prompt similarities first and average the logits. Embedding averaging is simple, but the two methods are not exactly equivalent.
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")
classes = ["cat", "dog", "car"]
templates = [
"a photo of a {}",
"a blurry photo of a {}",
"a close-up photo of a {}",
]
prompts = [template.format(name) for name in classes for template in templates]
text_inputs = processor(text=prompts, return_tensors="pt", padding=True)
image_inputs = processor(images=image, return_tensors="pt")
with torch.no_grad():
text_features = model.get_text_features(**text_inputs)
image_features = model.get_image_features(**image_inputs)
text_features = F.normalize(text_features, dim=-1)
image_features = F.normalize(image_features, dim=-1)
# Reshape from (classes * templates, dimensions) to
# (classes, templates, dimensions).
text_features = text_features.view(len(classes), len(templates), -1)
class_features = F.normalize(text_features.mean(dim=1), dim=-1)
similarities = image_features @ class_features.T
probabilities = similarities.softmax(dim=-1)[0]
print(dict(zip(classes, probabilities.tolist())))The prompt pipeline
Common errors
- Averaging unnormalized vectors can let vector magnitude affect the result.
- Forgetting the final normalization changes cosine similarity into a magnitude-sensitive dot product.
- Using prompts with inconsistent class wording can introduce artificial class differences.
- Treating softmax values as calibrated probabilities is unsafe. They are scores normalized across the supplied classes.
Exercise
Why should the same prompt templates be applied to every class in a zero-shot classifier?
Show answer
Unequal templates can change the quality or number of text representations for each class, giving some classes an artificial scoring advantage.