tarekziade HF Staff
Publish MIC usage, slim fixture and reviewed Transformers expectations
851c4b7 verified |
Download integrations/transformers/usage.md from huggingface-mic/mask2former-swin-tiny-coco-instance-mic: direct link, hf CLI and curl.
- Browser
- Download file 4.32 kB
-
https://huggingface.co/huggingface-mic/mask2former-swin-tiny-coco-instance-mic/resolve/main/integrations/transformers/usage.md
- Command line
-
hf download hf://huggingface-mic/mask2former-swin-tiny-coco-instance-mic/integrations/transformers/usage.md
-
curl -L -o usage.md https://huggingface.co/huggingface-mic/mask2former-swin-tiny-coco-instance-mic/resolve/main/integrations/transformers/usage.md
4.32 kB
Mask2Former: instance segmentation with Transformers
This page is the Transformers contract of the Mask2Former 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/mask2former-swin-tiny-coco-instance. 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.
Predict instances on a batch of images
import torch
from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation, set_seed
import json # doc-builder: hide
import os # doc-builder: hide
model_id = "facebook/mask2former-swin-tiny-coco-instance"
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 = AutoImageProcessor.from_pretrained(model_id)
model = Mask2FormerForUniversalSegmentation.from_pretrained(model_id).to(device)
if variant: # doc-builder: hide
del model # doc-builder: hide
model = Mask2FormerForUniversalSegmentation.from_pretrained(model_id, **variant).to(device) # doc-builder: hide
# Two small synthetic images so the batch perturbation is meaningful.
images = [torch.randint(0, 256, (3, 64, 64), dtype=torch.uint8) for _ in range(2)]
inputs = processor(images=images, return_tensors="pt")
inputs = inputs.to(device, dtype=model.dtype)
model.eval()
with torch.no_grad():
outputs = model(**inputs)
# class_queries_logits: (batch, num_queries + 1); masks_queries_logits: (batch, num_queries, h, w)
class_logits = outputs.class_queries_logits
mask_logits = outputs.masks_queries_logits
print(class_logits.shape, mask_logits.shape)
One training step
# Mask2Former trains on per-image binary masks (at the pixel_values resolution) and
# their int64 class ids, passed as mask_labels / class_labels lists.
height, width = inputs["pixel_values"].shape[-2:]
masks = torch.zeros(2, height, width, device=device)
masks[0, height // 4 : 3 * height // 4, width // 4 : 3 * width // 4] = 1
masks[1, : height // 4, : width // 4] = 1
mask_labels = [masks.to(model.dtype) for _ in range(2)]
class_labels = [torch.tensor([0, 2], dtype=torch.int64, device=device) for _ in range(2)]
model.train()
optimizer = torch.optim.SGD([p for p in model.parameters() if p.requires_grad], lr=0.01)
with torch.autocast(device_type=model.device.type, dtype=model.dtype, enabled=model.dtype != torch.float32):
loss = model(**inputs, mask_labels=mask_labels, class_labels=class_labels).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 = (
"class_predictor.weight",
"model.pixel_level_module.decoder.mask_projection.weight",
"model.pixel_level_module.encoder.swin.encoder.layers.0.blocks.0.attention.q_proj.weight",
)
result = {
"runtime": {
"device": model.device.type,
"dtype": str(model.dtype).removeprefix("torch."),
"attn_implementation": model.config._attn_implementation,
},
"class_logits_probe": class_logits[0, :4].float().tolist(),
"mask_logits_probe": mask_logits[0, 0, :2, :2].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))