tarekziade HF Staff
Publish MIC usage, slim fixture and reviewed Transformers expectations
de5f6eb verified |
Download integrations/transformers/usage.md from huggingface-mic/owlv2-base-patch16-ensemble-mic: direct link, hf CLI and curl.
- Browser
- Download file 5.41 kB
-
https://huggingface.co/huggingface-mic/owlv2-base-patch16-ensemble-mic/resolve/main/integrations/transformers/usage.md
- Command line
-
hf download hf://huggingface-mic/owlv2-base-patch16-ensemble-mic/integrations/transformers/usage.md
-
curl -L -o usage.md https://huggingface.co/huggingface-mic/owlv2-base-patch16-ensemble-mic/resolve/main/integrations/transformers/usage.md
5.41 kB
| # OWLv2: open-vocabulary object detection with Transformers | |
| This page is the Transformers contract of the OWLv2 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 `google/owlv2-base-patch16-ensemble`. 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. | |
| ## Detect objects from text queries | |
| ```py runnable:owlv2 | |
| import torch | |
| from transformers import Owlv2ForObjectDetection, Owlv2Processor, set_seed | |
| import json # doc-builder: hide | |
| import os # doc-builder: hide | |
| model_id = "google/owlv2-base-patch16-ensemble" | |
| 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 = Owlv2Processor.from_pretrained(model_id) | |
| model = Owlv2ForObjectDetection.from_pretrained(model_id).to(device) | |
| if variant: # doc-builder: hide | |
| del model # doc-builder: hide | |
| model = Owlv2ForObjectDetection.from_pretrained(model_id, **variant).to(device) # doc-builder: hide | |
| model.eval() | |
| # Two small synthetic images and two text queries per image. | |
| images = [torch.rand(3, 224, 224), torch.rand(3, 224, 224)] | |
| texts = [["a photo of a cat", "a photo of a dog"], ["a photo of a cat", "a photo of a dog"]] | |
| inputs = processor(text=texts, images=images, return_tensors="pt") | |
| # BatchFeature.to casts only floating tensors (pixel_values); token ids and masks stay integer. | |
| inputs = inputs.to(device, dtype=model.dtype) | |
| with torch.no_grad(): | |
| outputs = model(**inputs) | |
| target_sizes = torch.tensor([[224, 224], [224, 224]]) | |
| results = processor.post_process_grounded_object_detection( | |
| outputs=outputs, target_sizes=target_sizes, threshold=0.1, text_labels=texts | |
| ) | |
| # Keep each image's five highest-scoring detections. | |
| detections = [] | |
| for result in results: | |
| top = result["scores"].argsort(descending=True)[:5].tolist() | |
| detections.append( | |
| { | |
| "boxes": result["boxes"][top].tolist(), | |
| "scores": result["scores"][top].tolist(), | |
| "text_labels": [result["text_labels"][i] for i in top], | |
| } | |
| ) | |
| print(json.dumps({"detections": detections})) | |
| ``` | |
| ## One training step | |
| ```py runnable:owlv2:2 | |
| # Detection labels: one dict per image with class labels and normalized cx, cy, w, h boxes. | |
| labels = [ | |
| { | |
| "class_labels": torch.tensor([0], dtype=torch.int64, device=device), | |
| "boxes": torch.tensor([[0.5, 0.5, 0.4, 0.4]], dtype=torch.float32, device=device), | |
| }, | |
| { | |
| "class_labels": torch.tensor([1], dtype=torch.int64, device=device), | |
| "boxes": torch.tensor([[0.3, 0.3, 0.2, 0.2]], dtype=torch.float32, device=device), | |
| }, | |
| ] | |
| model.train() | |
| optimizer = torch.optim.SGD([p for p in model.parameters() if p.requires_grad], lr=0.01) | |
| # Owlv2ForObjectDetection has no training loss in Transformers: match each target | |
| # box to its nearest predicted box, then score that query's class logits (binary | |
| # cross-entropy per text query) and regress its box (L1). | |
| train_outputs = model(**inputs) | |
| loss = 0 | |
| for i, target in enumerate(labels): | |
| query = (train_outputs.pred_boxes[i].detach() - target["boxes"][0]).abs().sum(-1).argmin() | |
| logits = train_outputs.logits[i, query].float() | |
| wanted = torch.nn.functional.one_hot(target["class_labels"][0], logits.shape[-1]).float() | |
| loss = loss + torch.nn.functional.binary_cross_entropy_with_logits(logits, wanted) | |
| loss = loss + (train_outputs.pred_boxes[i, query].float() - target["boxes"][0]).abs().sum() | |
| 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 = ( | |
| "owlv2.vision_model.encoder.layers.0.self_attn.q_proj.weight", | |
| "owlv2.text_model.encoder.layers.0.self_attn.q_proj.weight", | |
| "class_head.dense0.weight", | |
| ) | |
| result = { | |
| "runtime": { | |
| "device": model.device.type, | |
| "dtype": str(model.dtype).removeprefix("torch."), | |
| "attn_implementation": model.config._attn_implementation, | |
| }, | |
| "detections": detections, | |
| "logits_probe": outputs.logits[0, :2, :2].float().tolist(), | |
| "boxes_probe": outputs.pred_boxes[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)) | |
| ``` | |