# CLIP vision: image embeddings with Transformers This page is the Transformers contract of the CLIP vision MIC and also a usage example. [doc-builder](https://github.com/huggingface/doc-builder/blob/main/docs/runnable-code-blocks.md) renders the `runnable` blocks below as documentation, and its pytest plugin runs them as written against `kunalkanaujiya/clip-vit-base-patch32-vision`. The MIC runner runs the same blocks against each slim fixture and each checkpoint in [`integration.json`](../../integration.json). Lines marked `# doc-builder: hide` only matter there: they swap in the pinned checkpoint or variant and print the result record. ## Embed two images ```py runnable:embed import torch import numpy as np from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection, set_seed import json # doc-builder: hide import os # doc-builder: hide model_id = "kunalkanaujiya/clip-vit-base-patch32-vision" 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 = CLIPImageProcessor.from_pretrained(model_id) # The checkpoint is stored in float16; train in float32 so the SGD step needs no loss scaling. model = CLIPVisionModelWithProjection.from_pretrained(model_id, dtype=torch.float32).to(device) if variant: # doc-builder: hide del model # doc-builder: hide model = CLIPVisionModelWithProjection.from_pretrained(model_id, **{"dtype": torch.float32, **variant}).to(device) # doc-builder: hide # Two (H, W, 3) uint8 images that differ in colour, not only in texture. rng = np.random.default_rng(0) red = np.zeros((224, 224, 3), dtype=np.uint8) red[..., 0] = 200 red[64:160, 64:160, 1] = 180 blue = np.zeros((224, 224, 3), dtype=np.uint8) blue[..., 2] = 200 blue[32:96, 128:192, 0] = 180 images = [red, blue] inputs = processor(images=images, return_tensors="pt") inputs = inputs.to(device, dtype=model.dtype) model.eval() with torch.no_grad(): image_embeds = model(**inputs).image_embeds print(image_embeds.shape) ``` ## One training step ```py runnable:embed:2 # Train only the projection head: a real CLIP vision tower is large and the # projection is the task head this checkpoint was trained for. for name, param in model.named_parameters(): param.requires_grad_(name.startswith("visual_projection")) model.train() optimizer = torch.optim.SGD([p for p in model.parameters() if p.requires_grad], lr=0.1) # Contrastive loss on the two L2-normalized embeddings, temperature 0.5: pull each toward its own row. targets = torch.eye(len(images), device=device, dtype=model.dtype) embeds = torch.nn.functional.normalize(model(**inputs).image_embeds, dim=-1) logits = embeds @ embeds.t() / 0.5 loss = torch.nn.functional.cross_entropy(logits, targets.argmax(dim=-1)) 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 = ("visual_projection.weight",) # 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 "image_embeds": image_embeds.float().tolist(), # doc-builder: hide "embedding_norms": image_embeds.float().norm(dim=-1).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 ```