tarekziade's picture
tarekziade HF Staff
Publish MIC usage, slim fixture and reviewed Transformers expectations
f6ba88a verified
|
Raw History Blame Contribute Delete
3.94 kB

SigLIP: zero-shot image classification with Transformers

This page is the Transformers contract of the SigLIP MIC and also a usage example. doc-builder renders the runnable blocks below as documentation, and its pytest plugin runs them as written against google/siglip-base-patch16-224. The MIC runner runs the same blocks against the slim fixture and the checkpoint in integration.json. Lines marked # doc-builder: hide only matter there: they swap in the pinned checkpoint or variant and print the result record.

Score images against candidate texts

import torch
from transformers import AutoModel, AutoProcessor, set_seed
import json  # doc-builder: hide
import os  # doc-builder: hide

model_id = "google/siglip-base-patch16-224"
model_id = os.environ.get("MIC_MODEL", model_id)  # doc-builder: hide
variant = json.loads(os.environ.get("MIC_MODEL_KWARGS", "{}"))  # doc-builder: hide
device = "cuda" if torch.cuda.is_available() else "cpu"
set_seed(0)  # seeds torch, NumPy, and Python: loading and dropout draw random numbers

processor = AutoProcessor.from_pretrained(model_id)
model = AutoModel.from_pretrained(model_id).to(device)
if variant:  # doc-builder: hide
    del model  # doc-builder: hide
    model = AutoModel.from_pretrained(model_id, **variant).to(device)  # doc-builder: hide
model.eval()

# Two small synthetic images (RGB) and three candidate captions.
images = [torch.randint(0, 256, (3, 224, 224), dtype=torch.uint8) for _ in range(2)]
texts = ["a photo of a cat", "a photo of a dog", "a photo of a plane"]
inputs = processor(text=texts, images=images, padding="max_length", return_tensors="pt")
inputs = inputs.to(device, dtype=model.dtype)  # casts floating tensors (pixel_values) only

with torch.no_grad():
    outputs = model(**inputs)

logits_per_image = outputs.logits_per_image
probs = torch.sigmoid(logits_per_image)
print(probs)

One contrastive training step

# SigLIP's contrastive loss pairs each image with its caption; use one caption per image.
train_texts = ["a photo of a cat", "a photo of a dog"]
train_inputs = processor(text=train_texts, images=images, padding="max_length", return_tensors="pt")
train_inputs = train_inputs.to(device, dtype=model.dtype)

model.train()
optimizer = torch.optim.SGD([p for p in model.parameters() if p.requires_grad], lr=0.01)
loss = model(**train_inputs, return_loss=True).loss
loss.backward()
before = {n: p.detach().cpu().clone() for n, p in model.named_parameters() if p.requires_grad}  # doc-builder: hide
optimizer.step()
print(f"loss: {loss.item():.4f}")

if os.environ.get("MIC_RUNNER"):  # doc-builder: hide
    named = dict(model.named_parameters())
    checked = ("vision_model.encoder.layers.0.self_attn.q_proj.weight", "text_model.encoder.layers.0.self_attn.q_proj.weight")
    result = {
        "runtime": {
            "device": model.device.type,
            "dtype": str(model.dtype).removeprefix("torch."),
            "attn_implementation": model.config._attn_implementation,
            "attn_implementations": {n: getattr(model.config, n)._attn_implementation for n in sorted(model.config.sub_configs) if getattr(getattr(model.config, n, None), '_attn_implementation', None)},
        },
        "logits_per_image": logits_per_image.float().tolist(),
        "logits_per_text": outputs.logits_per_text.float().tolist(),
        "probs": probs.float().tolist(),
        "training": {
            "loss": loss.item(),
            "gradients": {n: bool(named[n].grad is not None and torch.count_nonzero(named[n].grad) > 0 and torch.isfinite(named[n].grad).all()) for n in checked},
            "updated": any(not torch.equal(p.detach().cpu(), before[n]) for n, p in model.named_parameters() if n in before),
        },
    }
    print(json.dumps(result))