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

TIPSv2: image and text embeddings with Transformers

This page is the Transformers contract of the TIPSv2 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/tipsv2-b14. The MIC runner runs the same blocks against each slim fixture and each 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.

TIPSv2 is a dual image-text encoder: Transformers loads it natively, so the checkpoint's remote code (auto_map) is not needed. The bfloat16 variant is not measured yet: in bfloat16, Tipsv2Model's text pooling returns float32 embeddings (a float32 pooling mask promotes them), and the image-text product then fails with expected m1 and m2 to have the same dtype. It is re-enabled once Transformers fixes it.

Embed an image and some text

import json  # doc-builder: hide
import os  # doc-builder: hide

import numpy as np
import torch
from PIL import Image
from transformers import AutoProcessor, Tipsv2Model, set_seed

model_id = "google/tipsv2-b14"
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 = Tipsv2Model.from_pretrained(model_id).to(device)
if variant:  # doc-builder: hide
    del model  # doc-builder: hide
    model = Tipsv2Model.from_pretrained(model_id, **variant).to(device)  # doc-builder: hide
model.eval()

# Two synthetic images that differ in colour, as (H, W, 3) uint8 arrays.
rng = np.random.default_rng(0)
noise = rng.integers(0, 50, (2, 224, 224, 3), dtype=np.uint8)
images = [Image.fromarray(noise[0] + np.array([200, 0, 0], np.uint8)), Image.fromarray(noise[1] + np.array([0, 0, 200], np.uint8))]
classes = ["a photo of a red square", "a photo of a blue square"]

inputs = processor(text=classes, images=images, return_tensors="pt", padding=True)
inputs = inputs.to(device, dtype=model.dtype)

with torch.no_grad():
    outputs = model(**inputs)
similarity = outputs.logits_per_image
print(classes[similarity[0].argmax()])

One training step

# return_loss=True adds the image-text contrastive loss over the batch.
model.train()
optimizer = torch.optim.SGD([p for p in model.parameters() if p.requires_grad], lr=0.01)
loss = model(**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())  # doc-builder: hide
    checked = [n for n in named if n.endswith("weight") and named[n].requires_grad]  # doc-builder: hide
    checked = [next(n for n in checked if n.startswith("vision")), next(n for n in checked if n.startswith("text"))]  # doc-builder: hide
    result = {  # doc-builder: hide
        "runtime": {  # doc-builder: hide
            "device": model.device.type,  # doc-builder: hide
            "dtype": str(model.dtype).removeprefix("torch."),  # doc-builder: hide
            "attn_implementation": model.config._attn_implementation,  # doc-builder: hide
        },  # doc-builder: hide
        "logits": {"per_image": similarity.float().tolist()},  # doc-builder: hide
        "embeds": {"image_probe": outputs.image_embeds[:, :4].float().tolist(), "text_probe": outputs.text_embeds[:, :4].float().tolist()},  # doc-builder: hide
        "training": {  # doc-builder: hide
            "loss": loss.item(),  # doc-builder: hide
            "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},  # doc-builder: hide
            "updated": any(not torch.equal(p.detach().cpu(), before[n]) for n, p in model.named_parameters() if n in before),  # doc-builder: hide
        },  # doc-builder: hide
    }  # doc-builder: hide
    print(json.dumps(result))  # doc-builder: hide