tarekziade HF Staff
Publish MIC usage, slim fixture and reviewed Transformers expectations
ab267bc verified |
Download integrations/transformers/usage.md from huggingface-mic/docling-layout-heron-mic: direct link, hf CLI and curl.
- Browser
- Download file 5.45 kB
-
https://huggingface.co/huggingface-mic/docling-layout-heron-mic/resolve/main/integrations/transformers/usage.md
- Command line
-
hf download hf://huggingface-mic/docling-layout-heron-mic/integrations/transformers/usage.md
-
curl -L -o usage.md https://huggingface.co/huggingface-mic/docling-layout-heron-mic/resolve/main/integrations/transformers/usage.md
5.45 kB
| # RT-DETR v2: document layout detection with Transformers | |
| This page is the Transformers contract of the RT-DETR v2 layout 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 `docling-project/docling-layout-heron`. 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 layout regions | |
| ```py runnable:layout_detection | |
| import numpy as np | |
| import torch | |
| from PIL import Image | |
| from transformers import AutoImageProcessor, AutoModelForObjectDetection, set_seed | |
| import json # doc-builder: hide | |
| import os # doc-builder: hide | |
| model_id = "docling-project/docling-layout-heron" | |
| 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, dropout, and data augmentation draw random numbers | |
| image_processor = AutoImageProcessor.from_pretrained(model_id) | |
| model = AutoModelForObjectDetection.from_pretrained(model_id).to(device) | |
| if variant: # doc-builder: hide | |
| del model # doc-builder: hide | |
| model = AutoModelForObjectDetection.from_pretrained(model_id, **variant).to(device) # doc-builder: hide | |
| model.eval() | |
| # Two synthetic document-like pages: a header band, a body block, and a footer band. | |
| def make_page(header_rgb, body_rgb, seed): | |
| page = np.full((256, 192, 3), 255.0) | |
| page[8:40, 8:184] = header_rgb | |
| page[56:200, 8:184] = body_rgb | |
| page[216:248, 8:184] = (200, 200, 200) | |
| # A gradient and seeded noise on top: every patch differs, so patch order, crops and resizing all change the pixels. | |
| rng = np.random.default_rng(seed) | |
| y, x = np.mgrid[0:256, 0:192] | |
| page += (32 * (x / 192 + y / 256) - 32)[..., None] + rng.normal(0, 16, page.shape) | |
| return Image.fromarray(np.clip(page, 0, 255).astype(np.uint8)) | |
| images = [make_page((30, 60, 200), (240, 240, 240), seed=0), make_page((200, 40, 40), (220, 230, 250), seed=1)] | |
| inputs = image_processor(images=images, return_tensors="pt").to(device, dtype=model.dtype) | |
| with torch.no_grad(): | |
| outputs = model(**inputs) | |
| # Keep only a few probes for every image: full logits are (batch, 300 queries, num_labels). | |
| logits_probe = outputs.logits[:, :3, :4].float().tolist() | |
| boxes_probe = outputs.pred_boxes[:, :3, :].float().tolist() | |
| target_sizes = torch.tensor([image.size[::-1] for image in images]) | |
| results = image_processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.3) | |
| print([len(r["scores"]) for r in results]) | |
| ``` | |
| ## One training step | |
| ```py runnable:layout_detection:2 | |
| # Object-detection labels: a list of dicts with int64 class labels and normalized (cx, cy, w, h) boxes. | |
| num_labels = len(model.config.id2label) | |
| labels = [] | |
| for _ in images: | |
| labels.append({ | |
| "class_labels": torch.tensor([7, 9], dtype=torch.int64, device=device), | |
| "boxes": torch.tensor([[0.5, 0.09375, 0.9167, 0.125], [0.5, 0.5, 0.9167, 0.5625]], dtype=torch.float32, device=device), | |
| }) | |
| model.train() | |
| optimizer = torch.optim.SGD([p for p in model.parameters() if p.requires_grad], lr=0.01) | |
| with torch.autocast(device, dtype=model.dtype, enabled=model.dtype != torch.float32): | |
| loss = model(**inputs, labels=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()) # doc-builder: hide | |
| checked = ( # doc-builder: hide | |
| "model.decoder.class_embed.0.weight", # doc-builder: hide | |
| # The box MLP's output layer is zero-initialized, so only it gets a gradient on the first step. # doc-builder: hide | |
| "model.decoder.bbox_embed.0.layers.2.weight", # doc-builder: hide | |
| "model.decoder.layers.0.self_attn.q_proj.weight", # doc-builder: hide | |
| ) # 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": {"probe": logits_probe}, # doc-builder: hide | |
| "boxes": {"probe": boxes_probe}, # doc-builder: hide | |
| "detections": {"count": [len(r["scores"]) for r in results]}, # 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 | |
| ``` | |