tarekziade HF Staff
Publish MIC usage, slim fixture and reviewed Transformers expectations
f7daf66 verified |
Download integrations/transformers/usage.md from huggingface-mic/dinov2-small-mic: direct link, hf CLI and curl.
- Browser
- Download file 4.4 kB
-
https://huggingface.co/huggingface-mic/dinov2-small-mic/resolve/main/integrations/transformers/usage.md
- Command line
-
hf download hf://huggingface-mic/dinov2-small-mic/integrations/transformers/usage.md
-
curl -L -o usage.md https://huggingface.co/huggingface-mic/dinov2-small-mic/resolve/main/integrations/transformers/usage.md
4.4 kB
DINOv2: image features with Transformers
This page is the Transformers contract of the DINOv2 MIC and also a usage example. doc-builder renders the runnable blocks below as documentation, and its pytest plugin runs them as written against facebook/dinov2-small. 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.
Extract image features
import numpy as np
import torch
from transformers import AutoImageProcessor, AutoModel, set_seed
from PIL import Image
import json # doc-builder: hide
import os # doc-builder: hide
model_id = "facebook/dinov2-small"
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 any dropout draw random numbers
processor = AutoImageProcessor.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()
def textured_image(height, width, colour, seed):
# The base colour plus a gradient and seeded noise: every patch differs, so patch order, crops and resizing all change the pixels.
rng = np.random.default_rng(seed)
y, x = np.mgrid[0:height, 0:width]
ramp = (48 * (x / width + y / height) - 48)[..., None]
pixels = np.asarray(colour, dtype=np.float64) + ramp + rng.normal(0, 24, (height, width, 3))
return Image.fromarray(np.clip(pixels, 0, 255).astype(np.uint8))
# Two textured synthetic images, one red and one blue, distinct enough that a batch probe is meaningful.
images = [textured_image(224, 224, (200, 30, 30), seed=0), textured_image(224, 224, (30, 30, 200), seed=1)]
inputs = processor(images=images, return_tensors="pt")
inputs = inputs.to(device, dtype=model.dtype) # pixel_values are float: cast to the model dtype
with torch.no_grad():
outputs = model(**inputs)
# 16 CLS features spread across the hidden size, and the norm of every 8th patch token (patch order shows here).
hidden = outputs.last_hidden_state.float()
cls_features = hidden[:, 0, torch.linspace(0, hidden.shape[-1] - 1, 16).long()]
patch_features = hidden[:, 1::8].norm(dim=-1)
print("cls:", cls_features.tolist())
print("patches:", patch_features.tolist())
One training step
# A small seeded SGD step on the CLS token: the target is the mean of the batch's own CLS features,
# so the loss is well defined without external labels.
model.train()
optimizer = torch.optim.SGD([p for p in model.parameters() if p.requires_grad], lr=0.01)
with torch.no_grad():
target = outputs.last_hidden_state[:, 0, :].mean(dim=0, keepdim=True).detach()
loss = torch.nn.functional.mse_loss(model(**inputs).last_hidden_state[:, 0, :], target.expand_as(model(**inputs).last_hidden_state[:, 0, :]))
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 = ("embeddings.patch_embeddings.projection.weight", "encoder.layer.0.attention.q_proj.weight")
result = {
"runtime": {
"device": model.device.type,
"dtype": str(model.dtype).removeprefix("torch."),
"attn_implementation": model.config._attn_implementation,
},
"cls_features": cls_features.tolist(),
"patch_features": patch_features.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))