Sub topic 12
Prompt templates and prompt ensembling
This chapter assumes you have read the zero-shot classification chapter. You should know that a CLIP classifier is built by embedding class names as text and comparing them to an image embedding by cosine similarity. You should also be comfortable with PyTorch tensors and L2 normalization.
Why the wording of a prompt matters
In zero-shot classification, the text encoder is the classifier. Each class is a text embedding, and the "weights" of the classifier are whatever the text encoder outputs for the string you give it. Change the string and you change the classifier.
CLIP was trained on full captions such as "a dog playing in the snow", not on single words. A bare label like "dog" is out of distribution for the text encoder. A bare label is also ambiguous. The word "crane" can mean a bird or a construction machine, and "boxer" can mean a dog breed or an athlete. A caption-like sentence gives the encoder context to resolve this.
The CLIP paper reports that the template "a photo of a {label}." improved ImageNet zero-shot accuracy by about 1.3 points over using the bare class name. Using many templates and averaging them added more. Together the two techniques gained almost 5 points on ImageNet. No weights are trained. The gain comes only from building a better text-side classifier.
Prompt templates
A prompt template is a string with a placeholder for the class name. You fill it in for every class:
template = "a photo of a {}."
prompts = [template.format(name) for name in ["cat", "dog", "car"]]Good templates share these properties:
- They look like captions that could plausibly appear next to an image on the web.
- They name the image type when it is known, for example "a satellite photo of {}." or "a sketch of a {}.".
- They add task context when the label alone is thin, for example "a photo of a {}, a type of pet." for a pet-breed dataset.
The paper's authors wrote dataset-specific templates by hand for many benchmarks. This is prompt engineering in the literal sense: you try phrasings on a labeled validation set and keep what works.
Templates use the same model but different embeddings
Each template yields a different point in the joint embedding space for the same class. The points are close but not identical. Each one carries some template-specific noise, such as a bias toward "blurry" or "drawing". Averaging many of them cancels part of that noise and keeps the shared meaning of the class.
Prompt ensembling
Prompt ensembling builds one embedding per class from many templates. The procedure for each class is:
- Fill every template with the class name.
- Encode all the prompts with the text encoder.
- L2-normalize each embedding.
- Average the normalized embeddings.
- L2-normalize the average again.
The result is one unit vector per class. The classifier then has the same shape as a single-prompt classifier, a matrix of shape (num_classes, dim). Ensembling therefore costs nothing at inference time. You pay the text-encoding cost once, when you build the matrix.
Implementation
The code below builds an ensembled classifier and applies it to an image. It uses the Hugging Face CLIP model from earlier chapters.
import torch
import torch.nn.functional as F
from PIL import Image
from transformers import CLIPModel, CLIPProcessor
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32").eval()
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
classnames = ["cat", "dog", "car"]
templates = [
"a photo of a {}.",
"a blurry photo of a {}.",
"a close-up photo of a {}.",
"a low resolution photo of a {}.",
"a drawing of a {}.",
"a photo of the small {}.",
]
@torch.no_grad()
def build_classifier(classnames, templates):
weights = []
for name in classnames:
prompts = [t.format(name) for t in templates]
inputs = processor(text=prompts, return_tensors="pt", padding=True)
emb = F.normalize(model.get_text_features(**inputs), dim=-1) # (T, dim)
mean = F.normalize(emb.mean(dim=0), dim=-1) # (dim,)
weights.append(mean)
return torch.stack(weights) # (C, dim)
@torch.no_grad()
def classify(image, weights):
inputs = processor(images=image, return_tensors="pt")
img = F.normalize(model.get_image_features(**inputs), dim=-1) # (1, dim)
logits = model.logit_scale.exp() * img @ weights.t() # (1, C)
return logits.softmax(dim=-1)[0]
weights = build_classifier(classnames, templates)
probs = classify(Image.open("photo.jpg"), weights)
print(dict(zip(classnames, probs.tolist())))Build weights once and reuse it for every image. Only the image encoder runs per input.
Common errors
Averaging without normalizing first
If you average raw embeddings, templates whose embeddings happen to have larger norms dominate the mean. Normalize each embedding before averaging, as in the code above. Cosine similarity ignores the norm, so the norm carries no class information.
Forgetting to renormalize the mean
The mean of unit vectors is shorter than a unit vector, and the shortfall depends on how much the templates disagree. If you skip the second normalization, classes with more diverse templates get smaller norms and therefore smaller logits. Your softmax then favors the wrong classes for reasons unrelated to the image.
Tuning templates on the test set
If you pick templates by accuracy on your test images, your reported zero-shot number is optimistic. Choose templates on a separate validation split, or fix them in advance. The paper's dataset-specific templates were developed with some access to the benchmarks, so treat headline zero-shot numbers with that in mind.
Ambiguous or unnatural class names
Dataset label strings are often terse or odd, such as "crane", "maillot", or "tank_top". Templates cannot fix a label that means two things. Rewrite the class name itself: "crane (bird)" or "construction crane". Replace underscores with spaces, since the model saw natural text.
Padding and truncation
CLIP's text encoder has a fixed context length of 77 tokens. Long templates plus long class names get truncated, and the end of the string is lost. Keep prompts short. Pass padding=True so a batch of different-length prompts becomes one tensor.
Choosing a template set
| Approach | Cost | Typical effect | Risk |
|---|---|---|---|
| Bare class name | None | Lowest accuracy | Ambiguity, out-of-distribution text |
| One generic template | One text pass per class | Clear gain over bare names | Template-specific bias |
| Generic ensemble | T text passes per class, once | Further gain, more stable | Some templates may hurt a domain |
| Dataset-specific ensemble | Manual effort and validation data | Best on that domain | Overfitting to validation set |
Use a small generic ensemble as the default. Add domain-specific templates when you know the image type, such as medical scans, aerial photos, or product shots. Drop any template that lowers validation accuracy.
Edge cases
- Class-name synonyms. You can treat a synonym as another prompt for the same class. Encode "sofa" and "couch" with all templates, normalize, and average everything into the one class vector.
- Few templates. With only two or three, ensembling helps little. The gain comes from covering varied image styles, so use templates that differ in style rather than minor word swaps.
- Different models. Template quality depends on the model. A set tuned for one checkpoint is a good starting point for another, but check it on validation data.
- Prompt learning. Methods that learn the prompt tokens as parameters (such as CoOp) go beyond hand-written templates. They need labeled data, so they are no longer purely zero-shot.
Exercise
You build a class embedding by averaging six template embeddings, but you forget to L2-normalize each template embedding before averaging, and you also skip the final renormalization. Name two distinct problems this can cause for classification.
Show answer
First, templates whose embeddings have larger norms dominate the mean, so the class vector is biased toward those templates rather than the shared meaning. Second, the mean's norm is not 1 and varies by class, so the dot product with a normalized image embedding is no longer a cosine similarity. Classes with a smaller mean norm get smaller logits regardless of image content, which skews the softmax.
Exercise
A classifier for a "crane" class keeps misclassifying construction-site images as the bird. Adding more templates barely helps. What is the most likely cause and the right fix?
Show answer
The class name is ambiguous, and templates cannot resolve an ambiguous word. Change the label text itself, for example to "construction crane" and "crane (bird)" as separate classes or descriptions, then rebuild the ensembled embedding.