Skip to main content

Zero-shot classifiers

Author

Marie-Hélène Burle

The whole course so far trained models: loop, loss, epochs. This closing section of the transfer-learning part uses none of that. CLIP-style multimodal models were trained to place images and text in one shared embedding space, and that single trick turns them into classifiers that were never told our classes: describe the classes in words, encode the description, and match.

We try it on EuroSAT, and we compare with the model we fine-tuned.

A model that was never told our classes

We use the original OpenAI CLIP with a ViT-B/32 image encoder, through open_clip, a library dedicated to these models:

model, _, preprocess = open_clip.create_model_and_transforms(
    "ViT-B-32-quickgelu", pretrained="openai"
)
tokenizer = open_clip.get_tokenizer("ViT-B-32-quickgelu")
model = model.to(device).eval()
  • The first call downloads about 350 MB of weights into the Hugging Face cache; later calls hit the cache.
  • The -quickgelu suffix selects the activation of the original OpenAI training run: same architecture, subtly different network.
  • The third return value is CLIP’s own preprocessing. Unlike the ResNet-18 experiment, where we kept our 64 × 64 images, here we use it as-is: it resizes to 224 pixels and normalizes with its own statistics, not ImageNet’s.

Resizing to 224 is not a choice this time. The image encoder is a vision transformer: it cuts the image into patches and adds a learned position embedding to each, and those embeddings exist for exactly one resolution.

The weights come from the Hugging Face Hub. As in the Datasets section, we point the Hugging Face cache to a shared directory, so that everybody does not download the same 350 MB:

export HF_HUB_CACHE=/project/def-sponsor00/hub

On the Alliance clusters whose compute nodes cannot access the internet (see the fine-tuning section), download the weights once from a login node before submitting jobs:

python -c "import open_clip; open_clip.create_model_and_transforms('ViT-B-32-quickgelu', pretrained='openai')"

The zero-shot script

Our class names are CamelCase identifiers (AnnualCrop); text encoders want words. A regular expression splits a name wherever an uppercase letter starts a new word. The classifier itself is a list of sentences, one per class, described the way a caption would describe them. The script encodes the sentences, encodes the validation images, and matches:

nano zero_shot.py
import re  # to split CamelCase class names into words
from pathlib import Path

import open_clip
import torch
from torch.utils.data import DataLoader, Subset
from torchvision.datasets import EuroSAT


def to_words(name):
    # insert a space before each capital (except the first), then lowercase
    return re.sub(r"(?<!^)(?=[A-Z])", " ", name).lower()


def main():
    device = (
        torch.accelerator.current_accelerator()
        if torch.accelerator.is_available()
        else torch.device("cpu")
    )
    print(f"Torch version: {torch.__version__}\nDevice: {device}")

    root = Path("/project/def-sponsor00/data")

    model, _, preprocess = open_clip.create_model_and_transforms(
        "ViT-B-32-quickgelu", pretrained="openai"
    )
    tokenizer = open_clip.get_tokenizer("ViT-B-32-quickgelu")
    model = model.to(device).eval()
    print(f"CLIP: {sum(p.numel() for p in model.parameters()) / 1e6:.0f}M parameters")
    print(f"Preprocessing: {preprocess}")

    classes = EuroSAT(root=root).classes
    idx = torch.load(root / "split.pt", weights_only=True)

    # CLIP's preprocessing, not ours: its encoder expects 224 x 224 images
    val = Subset(EuroSAT(root=root, transform=preprocess), idx["val"])

    loader_kwargs = {
        "batch_size": 128,
        "num_workers": 3,
        "persistent_workers": True,
        "pin_memory": True,
    }
    val_loader = DataLoader(val, **loader_kwargs)
    print(f"Validation images: {len(val)}")

    # the image side: one pass over the validation set, no training anywhere
    feats, targets = [], []
    with torch.inference_mode():
        for x, y in val_loader:
            f = model.encode_image(x.to(device, non_blocking=True))
            # normalized, and back on the CPU: the similarity math is tiny
            feats.append(torch.nn.functional.normalize(f, dim=-1).cpu())
            targets.append(y)
    img_features, targets = torch.cat(feats), torch.cat(targets)
    print(f"Image features: {tuple(img_features.shape)}")

    # the text side: each template turns the 10 class names into 10 sentences
    acc = {}
    for template in ("{}", "a photo of {}", "a satellite image of {}"):
        prompts = [template.format(to_words(c)) for c in classes]
        tokens = tokenizer(prompts).to(device)
        with torch.inference_mode():
            text = model.encode_text(tokens)
            text_features = torch.nn.functional.normalize(text, dim=-1).cpu()
        # cosine similarities between every image and every sentence: highest wins
        preds = (img_features @ text_features.T).argmax(dim=1)
        acc[template] = (preds == targets).float().mean()
        print(f"{template:>28}: {acc[template]:5.1%}")

    print(f"\nFirst prompts: {prompts[:3]}")

    # per-class recall of the last template
    recall = torch.stack([(preds[targets == c] == c).float().mean() for c in range(10)])
    for cls, r in zip(classes, recall):
        print(f"{cls:>22} {r:6.1%}")

    torch.save({"classes": classes, "recall": recall}, root / "zero_shot.pt")


if __name__ == "__main__":
    main()
  • to_words() inserts a space before each capital of a class name (except the first) and lowercases the result: HerbaceousVegetation becomes herbaceous vegetation.
  • The image side is one pass over the validation set with CLIP’s preprocessing: encode_image() turns every image into a vector of 512 numbers, which is then normalized (given a length of 1). The vectors come back to the CPU: the similarity math is tiny.
  • The text side: each template turns the 10 class names into 10 sentences (the prompts). tokenizer converts them to token ids and encode_text() returns one normalized vector per prompt.
  • img_features @ text_features.T is the dot product of every image vector with every prompt vector. With normalized vectors, a dot product is a cosine similarity: argmax picks the class of the best match for each image.
  • The script prints the accuracy obtained with 3 templates, then the per-class recall of the last one. Both are saved to zero_shot.pt for the figure below.

Run it:

export HF_HUB_CACHE=/project/def-sponsor00/hub  # share the download, as in the Datasets section
srun --mem=10000 --gpus-per-node=1 --cpus-per-task=3 python zero_shot.py

The run takes about 30 seconds on a GPU node, but the script saves its results to a file in our shared root folder: if 2 people run it in parallel, there could be conflicts writing to the same file.

When both GPU nodes are taken, the script also runs on a CPU node, in about 2.5 minutes with 3 CPUs and with the same results:

srun --mem=11500 --cpus-per-task=3 python zero_shot.py

Results

This is what I got on the training cluster:

Torch version: 2.14.1
Device: cuda
CLIP: 151M parameters
Preprocessing: Compose(
    Resize(size=224, interpolation=bicubic, max_size=None, antialias=True)
    CenterCrop(size=(224, 224))
    <function _convert_to_rgb at 0x14a8a469d850>
    ToTensor()
    Normalize(mean=(0.48145466, 0.4578275, 0.40821073), std=(0.26862954, 0.26130258, 0.27577711))
)
Validation images: 5400
Image features: (5400, 512)
                          {}: 35.4%
               a photo of {}: 32.6%
     a satellite image of {}: 39.0%

First prompts: ['a satellite image of annual crop', 'a satellite image of forest', 'a satellite image of herbaceous vegetation']
            AnnualCrop  28.7%
                Forest  42.1%
  HerbaceousVegetation   0.3%
               Highway  67.2%
            Industrial  74.0%
               Pasture  39.6%
         PermanentCrop  27.1%
           Residential  86.3%
                 River  21.9%
               SeaLake   7.0%

And on my laptop:

Torch version: 2.13.0+cu130
Device: cuda
CLIP: 151M parameters
Preprocessing: Compose(
    Resize(size=224, interpolation=bicubic, max_size=None, antialias=True)
    CenterCrop(size=(224, 224))
    MaybeConvertMode()
    MaybeToTensor()
    Normalize(mean=(0.48145466, 0.4578275, 0.40821073), std=(0.26862954, 0.26130258, 0.27577711))
)
Validation images: 5400
Image features: (5400, 512)
                          {}: 35.5%
               a photo of {}: 32.6%
     a satellite image of {}: 39.0%

First prompts: ['a satellite image of annual crop', 'a satellite image of forest', 'a satellite image of herbaceous vegetation']
            AnnualCrop  28.7%
                Forest  42.1%
  HerbaceousVegetation   0.3%
               Highway  67.2%
            Industrial  73.8%
               Pasture  39.9%
         PermanentCrop  27.1%
           Residential  86.3%
                 River  22.1%
               SeaLake   7.0%

About 39%: remarkable for a classifier that learned our ten classes a minute ago, and far from the 96% of the fine-tuned model. Both halves of that sentence are the lesson of this page; let us look closer at each.

Phrasing matters

The prompt list is the classifier, so its wording matters. The same image features, three phrasings:

  • CLIP’s canonical prompt, “a photo of …”, underperforms the bare class names here (32.6% against about 35%): it steers the text towards web photography, away from our domain.
  • The domain-aware phrasing buys a few points (39.0%). Real gains come from describing the classes like captions do, not from prefix tuning.

A standard trick we are skipping: prompt ensembling, averaging the text embeddings of several templates per class. It stabilizes zero-shot classifiers on natural photos. On EuroSAT we measured it within a point of the best single template: with this domain gap, phrasing is not the bottleneck.

Where does it break?

Per-class recall shows the shape of the failure much better than the 39% average. Back in a JupyterHub session, we can draw it.

The recalls get loaded from the zero_shot.pt file saved by the script.

If you don’t want to switch back to JupyterHub, you can save the plot to file instead with fig.savefig('zero_shot_recall.png') and then transfer it to your machine with (from a terminal on your machine):

scp <username>@<hostname>:/remote/path/file /local/path

Example:

scp userxx@xxx.xxx.xxx:pytorch_course/zero_shot_recall.png .
from pathlib import Path

import matplotlib.pyplot as plt
import torch

root = Path("/project/def-sponsor00/data")
results = torch.load(root / "zero_shot.pt", weights_only=True)
classes, recall = results["classes"], results["recall"]

fig, ax = plt.subplots(figsize=(7, 4))
ax.barh(classes, recall.tolist())
ax.invert_yaxis()  # first class at the top, as in the printout
ax.set_xlabel("zero-shot recall")
ax.set_xlim(0, 1)

  • Classes whose names describe scenes that fill web photo captions do fine: residential neighbourhoods (86% found), industrial buildings (74%), highways (67%).
  • Classes whose names are remote-sensing jargon collapse: “herbaceous vegetation” is not how anyone captions an image (0.3% found), and SeaLake, trivially easy for every trained model in this course, is nearly never predicted by CLIP (7%). The classifier is only as good as the meeting point between our vocabulary and the model’s training captions.

This is domain shift in its plainest form, and the field answers it the same way each time: fine-tune the multimodal model on domain data. Remote-sensing CLIPs exist (see for instance RemoteCLIP), built with exactly the recipe of our transfer-learning section, one level up.

When to reach for zero-shot

Zero-shot costs no labels, no training, and one line of change to retarget: a different prompt list is a different classifier. That makes it the cheapest first experiment in applied deep learning: a floor under any labelling effort, a way to explore what a model knows about a domain before investing, and occasionally (web-adjacent domains, open-ended label spaces) the final solution.

Specialized domains pull the other way. On EuroSAT, 39% zero-shot against 96% fine-tuned is the real comparison, and the reason the fine-tuning section of this course exists.

Where this is heading is bigger than classification: the same image encoders, paired with language models, answer free-form questions about images. Our webinar The LLM era picks up that thread.

Your turn:

Class names are jargon; captions are plain language. Replace each class name with a plain-language descriptor of what the patch shows (e.g. “residential neighbourhood houses” for Residential), keep the “a satellite image of” template, and measure again.

  • First hint: start from zero_shot.py: the list of prompts is the only thing to change.
  • Second hint: a descriptor is a list of 10 strings in class order, and the prompts are then [f"a satellite image of {d}" for d in descriptors].