-
Notifications
You must be signed in to change notification settings - Fork 34
Implement ObjectDetection support #205
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
benjamintli
wants to merge
4
commits into
huggingface:main
Choose a base branch
from
benjamintli:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| # Copyright 2026 The HuggingFace Team. All rights reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from transformers import AutoModelForObjectDetection | ||
|
|
||
| from ..integrations import ObjectDetectionExportableModule | ||
| from ..task_registry import register_task | ||
|
|
||
|
|
||
| # NOTE: It’s important to map the registered task name to the pipeline name in https://github.com/huggingface/transformers/blob/main/utils/update_metadata.py. | ||
| # This will streamline using inferred task names and make exporting models to Hugging Face pipelines easier. | ||
| @register_task("object-detection") | ||
| def load_object_detection_model(model_name_or_path: str, **kwargs) -> ObjectDetectionExportableModule: | ||
| """ | ||
| Loads a vision model for object detection and registers it under the task | ||
| 'object-detection' using Hugging Face's `AutoModelForImageClassification`. | ||
|
|
||
| Args: | ||
| model_name_or_path (str): | ||
| Model ID on huggingface.co or path on disk to the model repository to export. For example: | ||
| `model_name_or_path="google/vit-base-patch16-224"` or `mode_name_or_path="/path/to/model_folder` | ||
| **kwargs: | ||
| Additional configuration options for the model. | ||
|
|
||
| Returns: | ||
| ObjectDetectionExportableModule: | ||
| An instance of `ObjectDetectionExportableModule` for exporting and lowering to ExecuTorch. | ||
| """ | ||
|
|
||
| image_size = kwargs.pop("image_size", None) | ||
| if image_size is None: | ||
| raise ValueError("image_size is a required argument for object-detection task") | ||
| num_channels = kwargs.pop("num_channels", None) | ||
| eager_model = AutoModelForObjectDetection.from_pretrained(model_name_or_path, **kwargs).eval() | ||
| return ObjectDetectionExportableModule(eager_model, image_size, num_channels) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -46,6 +46,7 @@ dev = [ | |
| "tiktoken", | ||
| "black~=23.1", | ||
| "ruff==0.4.4", | ||
| "timm", | ||
| ] | ||
|
|
||
| [project.urls] | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| # coding=utf-8 | ||
| # Copyright 2026 The HuggingFace Team. All rights reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import os | ||
| import subprocess | ||
| import tempfile | ||
| import unittest | ||
|
|
||
| import pytest | ||
| import torch | ||
| from executorch.extension.pybindings.portable_lib import ExecuTorchModule | ||
| from transformers import AutoConfig, AutoModelForObjectDetection | ||
| from transformers.testing_utils import slow | ||
|
|
||
| from optimum.executorch import ExecuTorchModelForObjectDetection | ||
|
|
||
| from ..utils import check_close_recursively | ||
|
|
||
|
|
||
| class ExecuTorchModelIntegrationTest(unittest.TestCase): | ||
| def __init__(self, *args, **kwargs): | ||
| super().__init__(*args, **kwargs) | ||
|
|
||
| @slow | ||
| @pytest.mark.run_slow | ||
| def test_detr_export_to_executorch(self): | ||
| model_id = "facebook/detr-resnet-50" # note: requires timm | ||
| task = "object-detection" | ||
| recipe = "xnnpack" | ||
| with tempfile.TemporaryDirectory() as tempdir: | ||
| subprocess.run( | ||
| f"optimum-cli export executorch --model {model_id} --task {task} --recipe {recipe} --image_size {640} --output_dir {tempdir}/executorch", | ||
| shell=True, | ||
| check=True, | ||
| ) | ||
| self.assertTrue(os.path.exists(f"{tempdir}/executorch/model.pte")) | ||
|
|
||
| def _helper_detr_object_detection(self, recipe: str, image_size: int): | ||
| model_id = "facebook/detr-resnet-50" # note: requires timm | ||
|
|
||
| config = AutoConfig.from_pretrained(model_id) | ||
| batch_size = 1 | ||
| num_channels = config.num_channels | ||
| height = image_size | ||
| width = image_size | ||
| pixel_values = torch.rand(batch_size, num_channels, height, width) | ||
|
|
||
| # Test fetching and lowering the model to ExecuTorch | ||
| et_model = ExecuTorchModelForObjectDetection.from_pretrained( | ||
| model_id=model_id, recipe=recipe, image_size=image_size | ||
| ) | ||
| self.assertIsInstance(et_model, ExecuTorchModelForObjectDetection) | ||
| self.assertIsInstance(et_model.model, ExecuTorchModule) | ||
| self.assertIsInstance(et_model.id2label, dict) | ||
| self.assertEqual(et_model.image_size, image_size) | ||
| self.assertEqual(et_model.num_channels, num_channels) | ||
|
|
||
| eager_model = AutoModelForObjectDetection.from_pretrained(model_id).eval().to("cpu") | ||
| with torch.no_grad(): | ||
| eager_output = eager_model(pixel_values) | ||
| et_logits, et_pred_boxes = et_model.forward(pixel_values) | ||
|
|
||
| # Compare with eager outputs | ||
| self.assertTrue(check_close_recursively(eager_output.logits, et_logits)) | ||
| self.assertTrue(check_close_recursively(eager_output.pred_boxes, et_pred_boxes)) | ||
|
|
||
| @slow | ||
| @pytest.mark.run_slow | ||
| def test_detr_object_detection(self): | ||
| self._helper_detr_object_detection(recipe="xnnpack", image_size=640) | ||
|
|
||
| @slow | ||
| @pytest.mark.run_slow | ||
| @pytest.mark.portable | ||
| def test_detr_object_detection_portable(self): | ||
| self._helper_detr_object_detection(recipe="portable", image_size=640) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.