opencode-skills-antigravity 1.0.39 → 1.0.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/bundled-skills/.antigravity-install-manifest.json +10 -1
  2. package/bundled-skills/docs/integrations/jetski-cortex.md +3 -3
  3. package/bundled-skills/docs/integrations/jetski-gemini-loader/README.md +1 -1
  4. package/bundled-skills/docs/maintainers/repo-growth-seo.md +3 -3
  5. package/bundled-skills/docs/maintainers/security-findings-triage-2026-03-29-refresh.csv +34 -0
  6. package/bundled-skills/docs/maintainers/security-findings-triage-2026-03-29-refresh.md +2 -0
  7. package/bundled-skills/docs/maintainers/skills-update-guide.md +1 -1
  8. package/bundled-skills/docs/sources/sources.md +2 -2
  9. package/bundled-skills/docs/users/bundles.md +1 -1
  10. package/bundled-skills/docs/users/claude-code-skills.md +1 -1
  11. package/bundled-skills/docs/users/gemini-cli-skills.md +1 -1
  12. package/bundled-skills/docs/users/getting-started.md +1 -1
  13. package/bundled-skills/docs/users/kiro-integration.md +1 -1
  14. package/bundled-skills/docs/users/usage.md +4 -4
  15. package/bundled-skills/docs/users/visual-guide.md +4 -4
  16. package/bundled-skills/hugging-face-cli/SKILL.md +192 -195
  17. package/bundled-skills/hugging-face-community-evals/SKILL.md +213 -0
  18. package/bundled-skills/hugging-face-community-evals/examples/.env.example +3 -0
  19. package/bundled-skills/hugging-face-community-evals/examples/USAGE_EXAMPLES.md +101 -0
  20. package/bundled-skills/hugging-face-community-evals/scripts/inspect_eval_uv.py +104 -0
  21. package/bundled-skills/hugging-face-community-evals/scripts/inspect_vllm_uv.py +306 -0
  22. package/bundled-skills/hugging-face-community-evals/scripts/lighteval_vllm_uv.py +297 -0
  23. package/bundled-skills/hugging-face-dataset-viewer/SKILL.md +120 -120
  24. package/bundled-skills/hugging-face-gradio/SKILL.md +304 -0
  25. package/bundled-skills/hugging-face-gradio/examples.md +613 -0
  26. package/bundled-skills/hugging-face-jobs/SKILL.md +25 -18
  27. package/bundled-skills/hugging-face-jobs/index.html +216 -0
  28. package/bundled-skills/hugging-face-jobs/references/hardware_guide.md +336 -0
  29. package/bundled-skills/hugging-face-jobs/references/hub_saving.md +352 -0
  30. package/bundled-skills/hugging-face-jobs/references/token_usage.md +570 -0
  31. package/bundled-skills/hugging-face-jobs/references/troubleshooting.md +475 -0
  32. package/bundled-skills/hugging-face-jobs/scripts/cot-self-instruct.py +718 -0
  33. package/bundled-skills/hugging-face-jobs/scripts/finepdfs-stats.py +546 -0
  34. package/bundled-skills/hugging-face-jobs/scripts/generate-responses.py +587 -0
  35. package/bundled-skills/hugging-face-model-trainer/SKILL.md +11 -12
  36. package/bundled-skills/hugging-face-model-trainer/references/gguf_conversion.md +296 -0
  37. package/bundled-skills/hugging-face-model-trainer/references/hardware_guide.md +283 -0
  38. package/bundled-skills/hugging-face-model-trainer/references/hub_saving.md +364 -0
  39. package/bundled-skills/hugging-face-model-trainer/references/local_training_macos.md +231 -0
  40. package/bundled-skills/hugging-face-model-trainer/references/reliability_principles.md +371 -0
  41. package/bundled-skills/hugging-face-model-trainer/references/trackio_guide.md +189 -0
  42. package/bundled-skills/hugging-face-model-trainer/references/training_methods.md +150 -0
  43. package/bundled-skills/hugging-face-model-trainer/references/training_patterns.md +203 -0
  44. package/bundled-skills/hugging-face-model-trainer/references/troubleshooting.md +282 -0
  45. package/bundled-skills/hugging-face-model-trainer/references/unsloth.md +313 -0
  46. package/bundled-skills/hugging-face-model-trainer/scripts/convert_to_gguf.py +424 -0
  47. package/bundled-skills/hugging-face-model-trainer/scripts/dataset_inspector.py +417 -0
  48. package/bundled-skills/hugging-face-model-trainer/scripts/estimate_cost.py +150 -0
  49. package/bundled-skills/hugging-face-model-trainer/scripts/train_dpo_example.py +106 -0
  50. package/bundled-skills/hugging-face-model-trainer/scripts/train_grpo_example.py +89 -0
  51. package/bundled-skills/hugging-face-model-trainer/scripts/train_sft_example.py +122 -0
  52. package/bundled-skills/hugging-face-model-trainer/scripts/unsloth_sft_example.py +512 -0
  53. package/bundled-skills/hugging-face-paper-publisher/SKILL.md +11 -4
  54. package/bundled-skills/hugging-face-paper-publisher/examples/example_usage.md +326 -0
  55. package/bundled-skills/hugging-face-paper-publisher/references/quick_reference.md +216 -0
  56. package/bundled-skills/hugging-face-paper-publisher/scripts/paper_manager.py +606 -0
  57. package/bundled-skills/hugging-face-paper-publisher/templates/arxiv.md +299 -0
  58. package/bundled-skills/hugging-face-paper-publisher/templates/ml-report.md +358 -0
  59. package/bundled-skills/hugging-face-paper-publisher/templates/modern.md +319 -0
  60. package/bundled-skills/hugging-face-paper-publisher/templates/standard.md +201 -0
  61. package/bundled-skills/hugging-face-papers/SKILL.md +241 -0
  62. package/bundled-skills/hugging-face-trackio/.claude-plugin/plugin.json +19 -0
  63. package/bundled-skills/hugging-face-trackio/SKILL.md +117 -0
  64. package/bundled-skills/hugging-face-trackio/references/alerts.md +196 -0
  65. package/bundled-skills/hugging-face-trackio/references/logging_metrics.md +206 -0
  66. package/bundled-skills/hugging-face-trackio/references/retrieving_metrics.md +251 -0
  67. package/bundled-skills/hugging-face-vision-trainer/SKILL.md +595 -0
  68. package/bundled-skills/hugging-face-vision-trainer/references/finetune_sam2_trainer.md +254 -0
  69. package/bundled-skills/hugging-face-vision-trainer/references/hub_saving.md +618 -0
  70. package/bundled-skills/hugging-face-vision-trainer/references/image_classification_training_notebook.md +279 -0
  71. package/bundled-skills/hugging-face-vision-trainer/references/object_detection_training_notebook.md +700 -0
  72. package/bundled-skills/hugging-face-vision-trainer/references/reliability_principles.md +310 -0
  73. package/bundled-skills/hugging-face-vision-trainer/references/timm_trainer.md +91 -0
  74. package/bundled-skills/hugging-face-vision-trainer/scripts/dataset_inspector.py +814 -0
  75. package/bundled-skills/hugging-face-vision-trainer/scripts/estimate_cost.py +217 -0
  76. package/bundled-skills/hugging-face-vision-trainer/scripts/image_classification_training.py +383 -0
  77. package/bundled-skills/hugging-face-vision-trainer/scripts/object_detection_training.py +710 -0
  78. package/bundled-skills/hugging-face-vision-trainer/scripts/sam_segmentation_training.py +382 -0
  79. package/bundled-skills/jq/SKILL.md +273 -0
  80. package/bundled-skills/odoo-edi-connector/SKILL.md +32 -10
  81. package/bundled-skills/odoo-woocommerce-bridge/SKILL.md +9 -5
  82. package/bundled-skills/tmux/SKILL.md +370 -0
  83. package/bundled-skills/transformers-js/SKILL.md +639 -0
  84. package/bundled-skills/transformers-js/references/CACHE.md +339 -0
  85. package/bundled-skills/transformers-js/references/CONFIGURATION.md +390 -0
  86. package/bundled-skills/transformers-js/references/EXAMPLES.md +605 -0
  87. package/bundled-skills/transformers-js/references/MODEL_ARCHITECTURES.md +167 -0
  88. package/bundled-skills/transformers-js/references/PIPELINE_OPTIONS.md +545 -0
  89. package/bundled-skills/transformers-js/references/TEXT_GENERATION.md +315 -0
  90. package/bundled-skills/viboscope/SKILL.md +64 -0
  91. package/package.json +1 -1
@@ -0,0 +1,700 @@
1
+ # Object Detection Training Reference
2
+
3
+ ## Contents
4
+ - Load the CPPE-5 dataset
5
+ - Preprocess the data (augmentation with Albumentations, COCO annotation formatting)
6
+ - Preparing function to compute mAP
7
+ - Training the detection model (TrainingArguments, Trainer setup)
8
+ - Evaluate
9
+ - Inference (loading from Hub, running predictions, visualizing results)
10
+
11
+ ---
12
+
13
+ Object detection is the computer vision task of detecting instances (such as humans, buildings, or cars) in an image. Object detection models receive an image as input and output
14
+ coordinates of the bounding boxes and associated labels of the detected objects. An image can contain multiple objects,
15
+ each with its own bounding box and a label (e.g. it can have a car and a building), and each object can
16
+ be present in different parts of an image (e.g. the image can have several cars).
17
+ This task is commonly used in autonomous driving for detecting things like pedestrians, road signs, and traffic lights.
18
+ Other applications include counting objects in images, image search, and more.
19
+
20
+ In this guide, you will learn how to:
21
+
22
+ 1. Finetune [DETR](https://huggingface.co/docs/transformers/model_doc/detr), a model that combines a convolutional
23
+ backbone with an encoder-decoder Transformer, on the [CPPE-5](https://huggingface.co/datasets/cppe-5)
24
+ dataset.
25
+ 2. Use your finetuned model for inference.
26
+
27
+ To see all architectures and checkpoints compatible with this task, we recommend checking the [task-page](https://huggingface.co/tasks/object-detection)
28
+
29
+ Before you begin, make sure you have all the necessary libraries installed:
30
+
31
+ ```bash
32
+ pip install -q datasets transformers accelerate timm trackio
33
+ pip install -q -U albumentations>=1.4.5 torchmetrics pycocotools
34
+ ```
35
+
36
+ You'll use 🤗 Datasets to load a dataset from the Hugging Face Hub, 🤗 Transformers to train your model,
37
+ and `albumentations` to augment the data.
38
+
39
+ We encourage you to share your model with the community. Log in to your Hugging Face account to upload it to the Hub.
40
+ When prompted, enter your token to log in:
41
+
42
+ ```py
43
+ >>> from huggingface_hub import notebook_login
44
+
45
+ >>> notebook_login()
46
+ ```
47
+
48
+ To get started, we'll define global constants, namely the model name and image size. For this tutorial, we'll use the conditional DETR model due to its faster convergence. Feel free to select any object detection model available in the `transformers` library.
49
+
50
+ ```py
51
+ >>> MODEL_NAME = "microsoft/conditional-detr-resnet-50" # or "facebook/detr-resnet-50"
52
+ >>> IMAGE_SIZE = 480
53
+ ```
54
+
55
+ ## Load the CPPE-5 dataset
56
+
57
+ The [CPPE-5 dataset](https://huggingface.co/datasets/cppe-5) contains images with
58
+ annotations identifying medical personal protective equipment (PPE) in the context of the COVID-19 pandemic.
59
+
60
+ Start by loading the dataset and creating a `validation` split from `train`:
61
+
62
+ ```py
63
+ >>> from datasets import load_dataset
64
+
65
+ >>> cppe5 = load_dataset("cppe-5")
66
+
67
+ >>> if "validation" not in cppe5:
68
+ ... split = cppe5["train"].train_test_split(0.15, seed=1337)
69
+ ... cppe5["train"] = split["train"]
70
+ ... cppe5["validation"] = split["test"]
71
+
72
+ >>> cppe5
73
+ DatasetDict({
74
+ train: Dataset({
75
+ features: ['image_id', 'image', 'width', 'height', 'objects'],
76
+ num_rows: 850
77
+ })
78
+ test: Dataset({
79
+ features: ['image_id', 'image', 'width', 'height', 'objects'],
80
+ num_rows: 29
81
+ })
82
+ validation: Dataset({
83
+ features: ['image_id', 'image', 'width', 'height', 'objects'],
84
+ num_rows: 150
85
+ })
86
+ })
87
+ ```
88
+
89
+ You'll see that this dataset has 1000 images for train and validation sets and a test set with 29 images.
90
+
91
+ To get familiar with the data, explore what the examples look like.
92
+
93
+ ```py
94
+ >>> cppe5["train"][0]
95
+ {
96
+ 'image_id': 366,
97
+ 'image': ,
98
+ 'width': 500,
99
+ 'height': 500,
100
+ 'objects': {
101
+ 'id': [1932, 1933, 1934],
102
+ 'area': [27063, 34200, 32431],
103
+ 'bbox': [[29.0, 11.0, 97.0, 279.0],
104
+ [201.0, 1.0, 120.0, 285.0],
105
+ [382.0, 0.0, 113.0, 287.0]],
106
+ 'category': [0, 0, 0]
107
+ }
108
+ }
109
+ ```
110
+
111
+ The examples in the dataset have the following fields:
112
+
113
+ - `image_id`: the example image id
114
+ - `image`: a `PIL.Image.Image` object containing the image
115
+ - `width`: width of the image
116
+ - `height`: height of the image
117
+ - `objects`: a dictionary containing bounding box metadata for the objects in the image:
118
+ - `id`: the annotation id
119
+ - `area`: the area of the bounding box
120
+ - `bbox`: the object's bounding box (in the [COCO format](https://albumentations.ai/docs/getting_started/bounding_boxes_augmentation/#coco) )
121
+ - `category`: the object's category, with possible values including `Coverall (0)`, `Face_Shield (1)`, `Gloves (2)`, `Goggles (3)` and `Mask (4)`
122
+
123
+ You may notice that the `bbox` field follows the COCO format, which is the format that the DETR model expects.
124
+ However, the grouping of the fields inside `objects` differs from the annotation format DETR requires. You will
125
+ need to apply some preprocessing transformations before using this data for training.
126
+
127
+ To get an even better understanding of the data, visualize an example in the dataset.
128
+
129
+ ```py
130
+ >>> import numpy as np
131
+ >>> import os
132
+ >>> from PIL import Image, ImageDraw
133
+
134
+ >>> image = cppe5["train"][2]["image"]
135
+ >>> annotations = cppe5["train"][2]["objects"]
136
+ >>> draw = ImageDraw.Draw(image)
137
+
138
+ >>> categories = cppe5["train"].features["objects"]["category"].feature.names
139
+
140
+ >>> id2label = {index: x for index, x in enumerate(categories, start=0)}
141
+ >>> label2id = {v: k for k, v in id2label.items()}
142
+
143
+ >>> for i in range(len(annotations["id"])):
144
+ ... box = annotations["bbox"][i]
145
+ ... class_idx = annotations["category"][i]
146
+ ... x, y, w, h = tuple(box)
147
+ ... # Check if coordinates are normalized or not
148
+ ... if max(box) > 1.0:
149
+ ... # Coordinates are un-normalized, no need to re-scale them
150
+ ... x1, y1 = int(x), int(y)
151
+ ... x2, y2 = int(x + w), int(y + h)
152
+ ... else:
153
+ ... # Coordinates are normalized, re-scale them
154
+ ... x1 = int(x * width)
155
+ ... y1 = int(y * height)
156
+ ... x2 = int((x + w) * width)
157
+ ... y2 = int((y + h) * height)
158
+ ... draw.rectangle((x, y, x + w, y + h), outline="red", width=1)
159
+ ... draw.text((x, y), id2label[class_idx], fill="white")
160
+
161
+ >>> image
162
+ ```
163
+
164
+
165
+
166
+ To visualize the bounding boxes with associated labels, you can get the labels from the dataset's metadata, specifically
167
+ the `category` field.
168
+ You'll also want to create dictionaries that map a label id to a label class (`id2label`) and the other way around (`label2id`).
169
+ You can use them later when setting up the model. Including these maps will make your model reusable by others if you share
170
+ it on the Hugging Face Hub. Please note that, the part of above code that draws the bounding boxes assume that it is in `COCO` format `(x_min, y_min, width, height)`. It has to be adjusted to work for other formats like `(x_min, y_min, x_max, y_max)`.
171
+
172
+ As a final step of getting familiar with the data, explore it for potential issues. One common problem with datasets for
173
+ object detection is bounding boxes that "stretch" beyond the edge of the image. Such "runaway" bounding boxes can raise
174
+ errors during training and should be addressed. There are a few examples with this issue in this dataset.
175
+ To keep things simple in this guide, we will set `clip=True` for `BboxParams` in transformations below.
176
+
177
+ ## Preprocess the data
178
+
179
+ To finetune a model, you must preprocess the data you plan to use to match precisely the approach used for the pre-trained model.
180
+ [AutoImageProcessor](/docs/transformers/v5.1.0/en/model_doc/auto#transformers.AutoImageProcessor) takes care of processing image data to create `pixel_values`, `pixel_mask`, and
181
+ `labels` that a DETR model can train with. The image processor has some attributes that you won't have to worry about:
182
+
183
+ - `image_mean = [0.485, 0.456, 0.406 ]`
184
+ - `image_std = [0.229, 0.224, 0.225]`
185
+
186
+ These are the mean and standard deviation used to normalize images during the model pre-training. These values are crucial
187
+ to replicate when doing inference or finetuning a pre-trained image model.
188
+
189
+ Instantiate the image processor from the same checkpoint as the model you want to finetune.
190
+
191
+ ```py
192
+ >>> from transformers import AutoImageProcessor
193
+
194
+ >>> MAX_SIZE = IMAGE_SIZE
195
+
196
+ >>> image_processor = AutoImageProcessor.from_pretrained(
197
+ ... MODEL_NAME,
198
+ ... do_resize=True,
199
+ ... size={"max_height": MAX_SIZE, "max_width": MAX_SIZE},
200
+ ... do_pad=True,
201
+ ... pad_size={"height": MAX_SIZE, "width": MAX_SIZE},
202
+ ... )
203
+ ```
204
+
205
+ Before passing the images to the `image_processor`, apply two preprocessing transformations to the dataset:
206
+
207
+ - Augmenting images
208
+ - Reformatting annotations to meet DETR expectations
209
+
210
+ First, to make sure the model does not overfit on the training data, you can apply image augmentation with any data augmentation library. Here we use [Albumentations](https://albumentations.ai/docs/).
211
+ This library ensures that transformations affect the image and update the bounding boxes accordingly.
212
+ The 🤗 Datasets library documentation has a detailed [guide on how to augment images for object detection](https://huggingface.co/docs/datasets/object_detection),
213
+ and it uses the exact same dataset as an example. Apply some geometric and color transformations to the image. For additional augmentation options, explore the [Albumentations Demo Space](https://huggingface.co/spaces/qubvel-hf/albumentations-demo).
214
+
215
+ ```py
216
+ >>> import albumentations as A
217
+
218
+ >>> train_augment_and_transform = A.Compose(
219
+ ... [
220
+ ... A.Perspective(p=0.1),
221
+ ... A.HorizontalFlip(p=0.5),
222
+ ... A.RandomBrightnessContrast(p=0.5),
223
+ ... A.HueSaturationValue(p=0.1),
224
+ ... ],
225
+ ... bbox_params=A.BboxParams(format="coco", label_fields=["category"], clip=True, min_area=25),
226
+ ... )
227
+
228
+ >>> validation_transform = A.Compose(
229
+ ... [A.NoOp()],
230
+ ... bbox_params=A.BboxParams(format="coco", label_fields=["category"], clip=True),
231
+ ... )
232
+ ```
233
+
234
+ The `image_processor` expects the annotations to be in the following format: `{'image_id': int, 'annotations': list[Dict]}`,
235
+ where each dictionary is a COCO object annotation. Let's add a function to reformat annotations for a single example:
236
+
237
+ ```py
238
+ >>> def format_image_annotations_as_coco(image_id, categories, areas, bboxes):
239
+ ... """Format one set of image annotations to the COCO format
240
+
241
+ ... Args:
242
+ ... image_id (str): image id. e.g. "0001"
243
+ ... categories (list[int]): list of categories/class labels corresponding to provided bounding boxes
244
+ ... areas (list[float]): list of corresponding areas to provided bounding boxes
245
+ ... bboxes (list[tuple[float]]): list of bounding boxes provided in COCO format
246
+ ... ([center_x, center_y, width, height] in absolute coordinates)
247
+
248
+ ... Returns:
249
+ ... dict: {
250
+ ... "image_id": image id,
251
+ ... "annotations": list of formatted annotations
252
+ ... }
253
+ ... """
254
+ ... annotations = []
255
+ ... for category, area, bbox in zip(categories, areas, bboxes):
256
+ ... formatted_annotation = {
257
+ ... "image_id": image_id,
258
+ ... "category_id": category,
259
+ ... "iscrowd": 0,
260
+ ... "area": area,
261
+ ... "bbox": list(bbox),
262
+ ... }
263
+ ... annotations.append(formatted_annotation)
264
+
265
+ ... return {
266
+ ... "image_id": image_id,
267
+ ... "annotations": annotations,
268
+ ... }
269
+
270
+ ```
271
+
272
+ Now you can combine the image and annotation transformations to use on a batch of examples:
273
+
274
+ ```py
275
+ >>> def augment_and_transform_batch(examples, transform, image_processor, return_pixel_mask=False):
276
+ ... """Apply augmentations and format annotations in COCO format for object detection task"""
277
+
278
+ ... images = []
279
+ ... annotations = []
280
+ ... for image_id, image, objects in zip(examples["image_id"], examples["image"], examples["objects"]):
281
+ ... image = np.array(image.convert("RGB"))
282
+
283
+ ... # apply augmentations
284
+ ... output = transform(image=image, bboxes=objects["bbox"], category=objects["category"])
285
+ ... images.append(output["image"])
286
+
287
+ ... # format annotations in COCO format
288
+ ... formatted_annotations = format_image_annotations_as_coco(
289
+ ... image_id, output["category"], objects["area"], output["bboxes"]
290
+ ... )
291
+ ... annotations.append(formatted_annotations)
292
+
293
+ ... # Apply the image processor transformations: resizing, rescaling, normalization
294
+ ... result = image_processor(images=images, annotations=annotations, return_tensors="pt")
295
+
296
+ ... if not return_pixel_mask:
297
+ ... result.pop("pixel_mask", None)
298
+
299
+ ... return result
300
+ ```
301
+
302
+ Apply this preprocessing function to the entire dataset using 🤗 Datasets [with_transform](https://huggingface.co/docs/datasets/v4.5.0/en/package_reference/main_classes#datasets.Dataset.with_transform) method. This method applies
303
+ transformations on the fly when you load an element of the dataset.
304
+
305
+ At this point, you can check what an example from the dataset looks like after the transformations. You should see a tensor
306
+ with `pixel_values`, a tensor with `pixel_mask`, and `labels`.
307
+
308
+ ```py
309
+ >>> from functools import partial
310
+
311
+ >>> # Make transform functions for batch and apply for dataset splits
312
+ >>> train_transform_batch = partial(
313
+ ... augment_and_transform_batch, transform=train_augment_and_transform, image_processor=image_processor
314
+ ... )
315
+ >>> validation_transform_batch = partial(
316
+ ... augment_and_transform_batch, transform=validation_transform, image_processor=image_processor
317
+ ... )
318
+
319
+ >>> cppe5["train"] = cppe5["train"].with_transform(train_transform_batch)
320
+ >>> cppe5["validation"] = cppe5["validation"].with_transform(validation_transform_batch)
321
+ >>> cppe5["test"] = cppe5["test"].with_transform(validation_transform_batch)
322
+
323
+ >>> cppe5["train"][15]
324
+ {'pixel_values': tensor([[[ 1.9235, 1.9407, 1.9749, ..., -0.7822, -0.7479, -0.6965],
325
+ [ 1.9578, 1.9749, 1.9920, ..., -0.7993, -0.7650, -0.7308],
326
+ [ 2.0092, 2.0092, 2.0263, ..., -0.8507, -0.8164, -0.7822],
327
+ ...,
328
+ [ 0.0741, 0.0741, 0.0741, ..., 0.0741, 0.0741, 0.0741],
329
+ [ 0.0741, 0.0741, 0.0741, ..., 0.0741, 0.0741, 0.0741],
330
+ [ 0.0741, 0.0741, 0.0741, ..., 0.0741, 0.0741, 0.0741]],
331
+
332
+ [[ 1.6232, 1.6408, 1.6583, ..., 0.8704, 1.0105, 1.1331],
333
+ [ 1.6408, 1.6583, 1.6758, ..., 0.8529, 0.9930, 1.0980],
334
+ [ 1.6933, 1.6933, 1.7108, ..., 0.8179, 0.9580, 1.0630],
335
+ ...,
336
+ [ 0.2052, 0.2052, 0.2052, ..., 0.2052, 0.2052, 0.2052],
337
+ [ 0.2052, 0.2052, 0.2052, ..., 0.2052, 0.2052, 0.2052],
338
+ [ 0.2052, 0.2052, 0.2052, ..., 0.2052, 0.2052, 0.2052]],
339
+
340
+ [[ 1.8905, 1.9080, 1.9428, ..., -0.1487, -0.0964, -0.0615],
341
+ [ 1.9254, 1.9428, 1.9603, ..., -0.1661, -0.1138, -0.0790],
342
+ [ 1.9777, 1.9777, 1.9951, ..., -0.2010, -0.1138, -0.0790],
343
+ ...,
344
+ [ 0.4265, 0.4265, 0.4265, ..., 0.4265, 0.4265, 0.4265],
345
+ [ 0.4265, 0.4265, 0.4265, ..., 0.4265, 0.4265, 0.4265],
346
+ [ 0.4265, 0.4265, 0.4265, ..., 0.4265, 0.4265, 0.4265]]]),
347
+ 'labels': {'image_id': tensor([688]), 'class_labels': tensor([3, 4, 2, 0, 0]), 'boxes': tensor([[0.4700, 0.1933, 0.1467, 0.0767],
348
+ [0.4858, 0.2600, 0.1150, 0.1000],
349
+ [0.4042, 0.4517, 0.1217, 0.1300],
350
+ [0.4242, 0.3217, 0.3617, 0.5567],
351
+ [0.6617, 0.4033, 0.5400, 0.4533]]), 'area': tensor([ 4048., 4140., 5694., 72478., 88128.]), 'iscrowd': tensor([0, 0, 0, 0, 0]), 'orig_size': tensor([480, 480])}}
352
+ ```
353
+
354
+ You have successfully augmented the individual images and prepared their annotations. However, preprocessing isn't
355
+ complete yet. In the final step, create a custom `collate_fn` to batch images together.
356
+ Pad images (which are now `pixel_values`) to the largest image in a batch, and create a corresponding `pixel_mask`
357
+ to indicate which pixels are real (1) and which are padding (0).
358
+
359
+ ```py
360
+ >>> import torch
361
+
362
+ >>> def collate_fn(batch):
363
+ ... data = {}
364
+ ... data["pixel_values"] = torch.stack([x["pixel_values"] for x in batch])
365
+ ... data["labels"] = [x["labels"] for x in batch]
366
+ ... if "pixel_mask" in batch[0]:
367
+ ... data["pixel_mask"] = torch.stack([x["pixel_mask"] for x in batch])
368
+ ... return data
369
+
370
+ ```
371
+
372
+ ## Preparing function to compute mAP
373
+
374
+ Object detection models are commonly evaluated with a set of COCO-style metrics. We are going to use `torchmetrics` to compute `mAP` (mean average precision) and `mAR` (mean average recall) metrics and will wrap it to `compute_metrics` function in order to use in [Trainer](/docs/transformers/v5.1.0/en/main_classes/trainer#transformers.Trainer) for evaluation.
375
+
376
+ Intermediate format of boxes used for training is `YOLO` (normalized) but we will compute metrics for boxes in `Pascal VOC` (absolute) format in order to correctly handle box areas. Let's define a function that converts bounding boxes to `Pascal VOC` format:
377
+
378
+ ```py
379
+ >>> from transformers.image_transforms import center_to_corners_format
380
+
381
+ >>> def convert_bbox_yolo_to_pascal(boxes, image_size):
382
+ ... """
383
+ ... Convert bounding boxes from YOLO format (x_center, y_center, width, height) in range [0, 1]
384
+ ... to Pascal VOC format (x_min, y_min, x_max, y_max) in absolute coordinates.
385
+
386
+ ... Args:
387
+ ... boxes (torch.Tensor): Bounding boxes in YOLO format
388
+ ... image_size (tuple[int, int]): Image size in format (height, width)
389
+
390
+ ... Returns:
391
+ ... torch.Tensor: Bounding boxes in Pascal VOC format (x_min, y_min, x_max, y_max)
392
+ ... """
393
+ ... # convert center to corners format
394
+ ... boxes = center_to_corners_format(boxes)
395
+
396
+ ... # convert to absolute coordinates
397
+ ... height, width = image_size
398
+ ... boxes = boxes * torch.tensor([[width, height, width, height]])
399
+
400
+ ... return boxes
401
+ ```
402
+
403
+ Then, in `compute_metrics` function we collect `predicted` and `target` bounding boxes, scores and labels from evaluation loop results and pass it to the scoring function.
404
+
405
+ ```py
406
+ >>> import numpy as np
407
+ >>> from dataclasses import dataclass
408
+ >>> from torchmetrics.detection.mean_ap import MeanAveragePrecision
409
+
410
+ >>> @dataclass
411
+ >>> class ModelOutput:
412
+ ... logits: torch.Tensor
413
+ ... pred_boxes: torch.Tensor
414
+
415
+ >>> @torch.no_grad()
416
+ >>> def compute_metrics(evaluation_results, image_processor, threshold=0.0, id2label=None):
417
+ ... """
418
+ ... Compute mean average mAP, mAR and their variants for the object detection task.
419
+
420
+ ... Args:
421
+ ... evaluation_results (EvalPrediction): Predictions and targets from evaluation.
422
+ ... threshold (float, optional): Threshold to filter predicted boxes by confidence. Defaults to 0.0.
423
+ ... id2label (Optional[dict], optional): Mapping from class id to class name. Defaults to None.
424
+
425
+ ... Returns:
426
+ ... Mapping[str, float]: Metrics in a form of dictionary {: }
427
+ ... """
428
+
429
+ ... predictions, targets = evaluation_results.predictions, evaluation_results.label_ids
430
+
431
+ ... # For metric computation we need to provide:
432
+ ... # - targets in a form of list of dictionaries with keys "boxes", "labels"
433
+ ... # - predictions in a form of list of dictionaries with keys "boxes", "scores", "labels"
434
+
435
+ ... image_sizes = []
436
+ ... post_processed_targets = []
437
+ ... post_processed_predictions = []
438
+
439
+ ... # Collect targets in the required format for metric computation
440
+ ... for batch in targets:
441
+ ... # collect image sizes, we will need them for predictions post processing
442
+ ... batch_image_sizes = torch.tensor(np.array([x["orig_size"] for x in batch]))
443
+ ... image_sizes.append(batch_image_sizes)
444
+ ... # collect targets in the required format for metric computation
445
+ ... # boxes were converted to YOLO format needed for model training
446
+ ... # here we will convert them to Pascal VOC format (x_min, y_min, x_max, y_max)
447
+ ... for image_target in batch:
448
+ ... boxes = torch.tensor(image_target["boxes"])
449
+ ... boxes = convert_bbox_yolo_to_pascal(boxes, image_target["orig_size"])
450
+ ... labels = torch.tensor(image_target["class_labels"])
451
+ ... post_processed_targets.append({"boxes": boxes, "labels": labels})
452
+
453
+ ... # Collect predictions in the required format for metric computation,
454
+ ... # model produce boxes in YOLO format, then image_processor convert them to Pascal VOC format
455
+ ... for batch, target_sizes in zip(predictions, image_sizes):
456
+ ... batch_logits, batch_boxes = batch[1], batch[2]
457
+ ... output = ModelOutput(logits=torch.tensor(batch_logits), pred_boxes=torch.tensor(batch_boxes))
458
+ ... post_processed_output = image_processor.post_process_object_detection(
459
+ ... output, threshold=threshold, target_sizes=target_sizes
460
+ ... )
461
+ ... post_processed_predictions.extend(post_processed_output)
462
+
463
+ ... # Compute metrics
464
+ ... metric = MeanAveragePrecision(box_format="xyxy", class_metrics=True)
465
+ ... metric.update(post_processed_predictions, post_processed_targets)
466
+ ... metrics = metric.compute()
467
+
468
+ ... # Replace list of per class metrics with separate metric for each class
469
+ ... classes = metrics.pop("classes")
470
+ ... map_per_class = metrics.pop("map_per_class")
471
+ ... mar_100_per_class = metrics.pop("mar_100_per_class")
472
+ ... for class_id, class_map, class_mar in zip(classes, map_per_class, mar_100_per_class):
473
+ ... class_name = id2label[class_id.item()] if id2label is not None else class_id.item()
474
+ ... metrics[f"map_{class_name}"] = class_map
475
+ ... metrics[f"mar_100_{class_name}"] = class_mar
476
+
477
+ ... metrics = {k: round(v.item(), 4) for k, v in metrics.items()}
478
+
479
+ ... return metrics
480
+
481
+ >>> eval_compute_metrics_fn = partial(
482
+ ... compute_metrics, image_processor=image_processor, id2label=id2label, threshold=0.0
483
+ ... )
484
+ ```
485
+
486
+ ## Training the detection model
487
+
488
+ You have done most of the heavy lifting in the previous sections, so now you are ready to train your model!
489
+ The images in this dataset are still quite large, even after resizing. This means that finetuning this model will
490
+ require at least one GPU.
491
+
492
+ Training involves the following steps:
493
+
494
+ 1. Load the model with [AutoModelForObjectDetection](/docs/transformers/v5.1.0/en/model_doc/auto#transformers.AutoModelForObjectDetection) using the same checkpoint as in the preprocessing.
495
+ 2. Define your training hyperparameters in [TrainingArguments](/docs/transformers/v5.1.0/en/main_classes/trainer#transformers.TrainingArguments).
496
+ 3. Pass the training arguments to [Trainer](/docs/transformers/v5.1.0/en/main_classes/trainer#transformers.Trainer) along with the model, dataset, image processor, and data collator.
497
+ 4. Call [train()](/docs/transformers/v5.1.0/en/main_classes/trainer#transformers.Trainer.train) to finetune your model.
498
+
499
+ When loading the model from the same checkpoint that you used for the preprocessing, remember to pass the `label2id`
500
+ and `id2label` maps that you created earlier from the dataset's metadata. Additionally, we specify `ignore_mismatched_sizes=True` to replace the existing classification head with a new one.
501
+
502
+ ```py
503
+ >>> from transformers import AutoModelForObjectDetection
504
+
505
+ >>> model = AutoModelForObjectDetection.from_pretrained(
506
+ ... MODEL_NAME,
507
+ ... id2label=id2label,
508
+ ... label2id=label2id,
509
+ ... ignore_mismatched_sizes=True,
510
+ ... )
511
+ ```
512
+
513
+ In the [TrainingArguments](/docs/transformers/v5.1.0/en/main_classes/trainer#transformers.TrainingArguments) use `output_dir` to specify where to save your model, then configure hyperparameters as you see fit. For `num_train_epochs=30` training will take about 35 minutes in Google Colab T4 GPU, increase the number of epoch to get better results.
514
+
515
+ Important notes:
516
+
517
+ - Set `remove_unused_columns` to `False`.
518
+ - Set `eval_do_concat_batches=False` to get proper evaluation results. Images have different number of target boxes, if batches are concatenated we will not be able to determine which boxes belongs to particular image.
519
+
520
+ If you wish to share your model by pushing to the Hub, set `push_to_hub` to `True` (you must be signed in to Hugging
521
+ Face to upload your model).
522
+
523
+ ```py
524
+ >>> from transformers import TrainingArguments
525
+
526
+ >>> training_args = TrainingArguments(
527
+ ... output_dir="detr_finetuned_cppe5",
528
+ ... num_train_epochs=30,
529
+ ... fp16=False,
530
+ ... per_device_train_batch_size=8,
531
+ ... dataloader_num_workers=4,
532
+ ... learning_rate=5e-5,
533
+ ... lr_scheduler_type="cosine",
534
+ ... weight_decay=1e-4,
535
+ ... max_grad_norm=0.01,
536
+ ... metric_for_best_model="eval_map",
537
+ ... greater_is_better=True,
538
+ ... load_best_model_at_end=True,
539
+ ... eval_strategy="epoch",
540
+ ... save_strategy="epoch",
541
+ ... save_total_limit=2,
542
+ ... remove_unused_columns=False,
543
+ ... report_to="trackio",
544
+ ... run_name="cppe",
545
+ ... eval_do_concat_batches=False,
546
+ ... push_to_hub=True,
547
+ ... )
548
+ ```
549
+
550
+ Finally, bring everything together, and call [train()](/docs/transformers/v5.1.0/en/main_classes/trainer#transformers.Trainer.train):
551
+
552
+ ```py
553
+ >>> from transformers import Trainer
554
+
555
+ >>> trainer = Trainer(
556
+ ... model=model,
557
+ ... args=training_args,
558
+ ... train_dataset=cppe5["train"],
559
+ ... eval_dataset=cppe5["validation"],
560
+ ... processing_class=image_processor,
561
+ ... data_collator=collate_fn,
562
+ ... compute_metrics=eval_compute_metrics_fn,
563
+ ... )
564
+
565
+ >>> trainer.train()
566
+ ```
567
+
568
+ Training runs for 30 epochs (~26 minutes on a T4 GPU for CPPE-5). Final epoch 30 results:
569
+
570
+ | Metric | Value |
571
+ |--------|-------|
572
+ | Training Loss | 0.994 |
573
+ | Validation Loss | 1.346 |
574
+ | mAP | 0.277 |
575
+ | mAP@50 | 0.555 |
576
+ | mAP@75 | 0.253 |
577
+ | mAR@100 | 0.443 |
578
+
579
+ Per-class mAP at epoch 30: Coverall 0.530, Face Shield 0.276, Gloves 0.175, Goggles 0.157, Mask 0.249.
580
+
581
+ Key observations:
582
+ - mAP improves rapidly in early epochs (0.009 at epoch 1 → 0.18 by epoch 10), then gradually converges
583
+ - Large objects are detected better (mAP_large=0.524) than small objects (mAP_small=0.148)
584
+ - Class imbalance visible: Coverall highest mAP (0.530), Goggles lowest (0.157)
585
+
586
+ <!-- Full per-epoch training metrics table omitted for brevity. -->
587
+
588
+
589
+ If you have set `push_to_hub` to `True` in the `training_args`, the training checkpoints are pushed to the
590
+ Hugging Face Hub. Upon training completion, push the final model to the Hub as well by calling the [push_to_hub()](/docs/transformers/v5.1.0/en/main_classes/trainer#transformers.Trainer.push_to_hub) method.
591
+
592
+ ```py
593
+ >>> trainer.push_to_hub()
594
+ ```
595
+
596
+ ## Evaluate
597
+
598
+ ```py
599
+ >>> from pprint import pprint
600
+
601
+ >>> metrics = trainer.evaluate(eval_dataset=cppe5["test"], metric_key_prefix="test")
602
+ >>> pprint(metrics)
603
+ {'epoch': 30.0,
604
+ 'test_loss': 1.0877351760864258,
605
+ 'test_map': 0.4116,
606
+ 'test_map_50': 0.741,
607
+ 'test_map_75': 0.3663,
608
+ 'test_map_Coverall': 0.5937,
609
+ 'test_map_Face_Shield': 0.5863,
610
+ 'test_map_Gloves': 0.3416,
611
+ 'test_map_Goggles': 0.1468,
612
+ 'test_map_Mask': 0.3894,
613
+ 'test_map_large': 0.5637,
614
+ 'test_map_medium': 0.3257,
615
+ 'test_map_small': 0.3589,
616
+ 'test_mar_1': 0.323,
617
+ 'test_mar_10': 0.5237,
618
+ 'test_mar_100': 0.5587,
619
+ 'test_mar_100_Coverall': 0.6756,
620
+ 'test_mar_100_Face_Shield': 0.7294,
621
+ 'test_mar_100_Gloves': 0.4721,
622
+ 'test_mar_100_Goggles': 0.4125,
623
+ 'test_mar_100_Mask': 0.5038,
624
+ 'test_mar_large': 0.7283,
625
+ 'test_mar_medium': 0.4901,
626
+ 'test_mar_small': 0.4469,
627
+ 'test_runtime': 1.6526,
628
+ 'test_samples_per_second': 17.548,
629
+ 'test_steps_per_second': 2.42}
630
+ ```
631
+
632
+ These results can be further improved by adjusting the hyperparameters in [TrainingArguments](/docs/transformers/v5.1.0/en/main_classes/trainer#transformers.TrainingArguments). Give it a go!
633
+
634
+ ## Inference
635
+
636
+ Now that you have finetuned a model, evaluated it, and uploaded it to the Hugging Face Hub, you can use it for inference.
637
+
638
+ ```py
639
+ >>> import torch
640
+ >>> import requests
641
+
642
+ >>> from PIL import Image, ImageDraw
643
+ >>> from transformers import AutoImageProcessor, AutoModelForObjectDetection
644
+
645
+ >>> url = "https://images.pexels.com/photos/8413299/pexels-photo-8413299.jpeg?auto=compress&cs=tinysrgb&w=630&h=375&dpr=2"
646
+ >>> image = Image.open(requests.get(url, stream=True).raw)
647
+ ```
648
+
649
+ Load model and image processor from the Hugging Face Hub (skip to use already trained in this session):
650
+
651
+ ```py
652
+ >>> from accelerate import Accelerator
653
+
654
+ >>> device = Accelerator().device
655
+ >>> model_repo = "qubvel-hf/detr_finetuned_cppe5"
656
+
657
+ >>> image_processor = AutoImageProcessor.from_pretrained(model_repo)
658
+ >>> model = AutoModelForObjectDetection.from_pretrained(model_repo)
659
+ >>> model = model.to(device)
660
+ ```
661
+
662
+ And detect bounding boxes:
663
+
664
+ ```py
665
+
666
+ >>> with torch.no_grad():
667
+ ... inputs = image_processor(images=[image], return_tensors="pt")
668
+ ... outputs = model(**inputs.to(device))
669
+ ... target_sizes = torch.tensor([[image.size[1], image.size[0]]])
670
+ ... results = image_processor.post_process_object_detection(outputs, threshold=0.3, target_sizes=target_sizes)[0]
671
+
672
+ >>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
673
+ ... box = [round(i, 2) for i in box.tolist()]
674
+ ... print(
675
+ ... f"Detected {model.config.id2label[label.item()]} with confidence "
676
+ ... f"{round(score.item(), 3)} at location {box}"
677
+ ... )
678
+ Detected Gloves with confidence 0.683 at location [244.58, 124.33, 300.35, 185.13]
679
+ Detected Mask with confidence 0.517 at location [143.73, 64.58, 219.57, 125.89]
680
+ Detected Gloves with confidence 0.425 at location [179.15, 155.57, 262.4, 226.35]
681
+ Detected Coverall with confidence 0.407 at location [307.13, -1.18, 477.82, 318.06]
682
+ Detected Coverall with confidence 0.391 at location [68.61, 126.66, 309.03, 318.89]
683
+ ```
684
+
685
+ Let's plot the result:
686
+
687
+ ```py
688
+ >>> draw = ImageDraw.Draw(image)
689
+
690
+ >>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
691
+ ... box = [round(i, 2) for i in box.tolist()]
692
+ ... x, y, x2, y2 = tuple(box)
693
+ ... draw.rectangle((x, y, x2, y2), outline="red", width=1)
694
+ ... draw.text((x, y), model.config.id2label[label.item()], fill="white")
695
+
696
+ >>> image
697
+ ```
698
+
699
+
700
+