-
Notifications
You must be signed in to change notification settings - Fork 224
Revert "Revert "USE_INFERENCE_EXP_MODELS"" #1657
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
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
2962971
Revert "Revert "USE_INFERENCE_EXP_MODELS""
hansent ce40c3f
Merge branch 'main' into revert-1656-revert-1642-exp-rfdetr-2
hansent d9c64f4
Merge branch 'main' into revert-1656-revert-1642-exp-rfdetr-2
hansent 90a08e0
use new florence weights aliases for use with transformers > 0.53.3
hansent d71ed05
Merge branch 'main' into revert-1656-revert-1642-exp-rfdetr-2
hansent 2885a77
fix syntax error
hansent 5c22472
allow some missing keys in lora adapter for early revision
hansent 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| from threading import Lock | ||
| from time import perf_counter | ||
| from typing import Any, Generic, List, Optional, Tuple, Union | ||
|
|
||
| import numpy as np | ||
| from inference_exp.models.base.object_detection import Detections, ObjectDetectionModel | ||
| from inference_exp.models.base.types import ( | ||
| PreprocessedInputs, | ||
| PreprocessingMetadata, | ||
| RawPrediction, | ||
| ) | ||
|
|
||
| from inference.core.entities.responses.inference import ( | ||
| InferenceResponseImage, | ||
| ObjectDetectionInferenceResponse, | ||
| ObjectDetectionPrediction, | ||
| ) | ||
| from inference.core.env import API_KEY | ||
| from inference.core.logger import logger | ||
| from inference.core.models.base import Model | ||
| from inference.core.utils.image_utils import load_image_rgb | ||
| from inference.models.aliases import resolve_roboflow_model_alias | ||
|
|
||
|
|
||
| class InferenceExpObjectDetectionModelAdapter(Model): | ||
| def __init__(self, model_id: str, api_key: str = None, **kwargs): | ||
| super().__init__() | ||
|
|
||
| self.metrics = {"num_inferences": 0, "avg_inference_time": 0.0} | ||
|
|
||
| self.api_key = api_key if api_key else API_KEY | ||
| model_id = resolve_roboflow_model_alias(model_id=model_id) | ||
|
|
||
| self.task_type = "object-detection" | ||
|
|
||
| # Lazy import to avoid hard dependency if flag disabled | ||
| from inference_exp import AutoModel # type: ignore | ||
|
|
||
| self._exp_model: ObjectDetectionModel = AutoModel.from_pretrained( | ||
| model_id_or_path=model_id, api_key=self.api_key | ||
| ) | ||
| if hasattr(self._exp_model, "optimize_for_inference"): | ||
| self._exp_model.optimize_for_inference() | ||
|
|
||
| self.class_names = list(self._exp_model.class_names) | ||
|
|
||
| def map_inference_kwargs(self, kwargs: dict) -> dict: | ||
| return kwargs | ||
|
|
||
| def preprocess(self, image: Any, **kwargs): | ||
| is_batch = isinstance(image, list) | ||
| images = image if is_batch else [image] | ||
| np_images: List[np.ndarray] = [ | ||
| load_image_rgb( | ||
| v, | ||
| disable_preproc_auto_orient=kwargs.get( | ||
| "disable_preproc_auto_orient", False | ||
| ), | ||
| ) | ||
| for v in images | ||
| ] | ||
| mapped_kwargs = self.map_inference_kwargs(kwargs) | ||
| return self._exp_model.pre_process(np_images, **mapped_kwargs) | ||
|
|
||
| def predict(self, img_in, **kwargs): | ||
| mapped_kwargs = self.map_inference_kwargs(kwargs) | ||
| return self._exp_model.forward(img_in, **mapped_kwargs) | ||
|
|
||
| def postprocess( | ||
| self, | ||
| predictions: Tuple[np.ndarray, ...], | ||
| preprocess_return_metadata: PreprocessingMetadata, | ||
| **kwargs, | ||
| ) -> List[Detections]: | ||
| mapped_kwargs = self.map_inference_kwargs(kwargs) | ||
| detections_list = self._exp_model.post_process( | ||
| predictions, preprocess_return_metadata, **mapped_kwargs | ||
| ) | ||
|
|
||
| responses: List[ObjectDetectionInferenceResponse] = [] | ||
| for preproc_metadata, det in zip(preprocess_return_metadata, detections_list): | ||
| H = preproc_metadata.original_size.height | ||
| W = preproc_metadata.original_size.width | ||
|
|
||
| xyxy = det.xyxy.detach().cpu().numpy() | ||
| confs = det.confidence.detach().cpu().numpy() | ||
| class_ids = det.class_id.detach().cpu().numpy() | ||
|
|
||
| predictions: List[ObjectDetectionPrediction] = [] | ||
|
|
||
| for (x1, y1, x2, y2), conf, class_id in zip(xyxy, confs, class_ids): | ||
| cx = (float(x1) + float(x2)) / 2.0 | ||
| cy = (float(y1) + float(y2)) / 2.0 | ||
| w = float(x2) - float(x1) | ||
| h = float(y2) - float(y1) | ||
| class_id_int = int(class_id) | ||
| class_name = ( | ||
| self.class_names[class_id_int] | ||
| if 0 <= class_id_int < len(self.class_names) | ||
| else str(class_id_int) | ||
| ) | ||
| predictions.append( | ||
| ObjectDetectionPrediction( | ||
| x=cx, | ||
| y=cy, | ||
| width=w, | ||
| height=h, | ||
| confidence=float(conf), | ||
| **{"class": class_name}, | ||
| class_id=class_id_int, | ||
| ) | ||
| ) | ||
|
|
||
| responses.append( | ||
| ObjectDetectionInferenceResponse( | ||
| predictions=predictions, | ||
| image=InferenceResponseImage(width=W, height=H), | ||
| ) | ||
| ) | ||
|
|
||
| return responses | ||
|
|
||
| def clear_cache(self, delete_from_disk: bool = True) -> None: | ||
| """Clears any cache if necessary. TODO: Implement this to delete the cache from the experimental model. | ||
|
|
||
| Args: | ||
| delete_from_disk (bool, optional): Whether to delete cached files from disk. Defaults to True. | ||
| """ | ||
| pass | ||
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,14 @@ | ||
| from inference.core.models.exp_adapter import InferenceExpObjectDetectionModelAdapter | ||
|
|
||
|
|
||
| class RFDetrExperimentalModel(InferenceExpObjectDetectionModelAdapter): | ||
| """Adapter for RF-DETR using inference_exp AutoModel backend. | ||
|
|
||
| This class wraps an inference_exp AutoModel to present the same interface | ||
| as legacy models in the inference server. | ||
| """ | ||
|
|
||
| def map_inference_kwargs(self, kwargs: dict) -> dict: | ||
| return { | ||
| "threshold": kwargs.get("confidence"), | ||
| } |
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,11 @@ | ||
| from inference.core.models.exp_adapter import InferenceExpObjectDetectionModelAdapter | ||
|
|
||
|
|
||
| class Yolo8ODExperimentalModel(InferenceExpObjectDetectionModelAdapter): | ||
| def map_inference_kwargs(self, kwargs: dict) -> dict: | ||
| return { | ||
| "conf_thresh": kwargs.get("confidence"), | ||
| "iou_thresh": kwargs.get("iou_threshold"), | ||
| "max_detections": kwargs.get("max_detections"), | ||
| "class_agnostic": kwargs.get("class_agnostic"), | ||
| } |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The new experimental adapter calls
self._exp_model.pre_process,forward, andpost_processdirectly without any synchronization. Other torch-backed models in this repository protect inference with aLockto avoid concurrent access to shared model state (for exampleYOLOv8ObjectDetection.predictuses_session_lock).AutoModelinstances frominference_expare PyTorch models as well and are unlikely to be thread-safe. When the server runs with multiple workers or handles concurrent requests, unsynchronized access can trigger CUDA/torch runtime errors or corrupt intermediate buffers. The adapter already importsLock, so wrapping the model calls in a mutex seems intended and would prevent these race conditions.Useful? React with 👍 / 👎.