inference-models 0.18.3__py3-none-any.whl
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.
- inference_models/__init__.py +36 -0
- inference_models/configuration.py +72 -0
- inference_models/constants.py +2 -0
- inference_models/entities.py +5 -0
- inference_models/errors.py +137 -0
- inference_models/logger.py +52 -0
- inference_models/model_pipelines/__init__.py +0 -0
- inference_models/model_pipelines/auto_loaders/__init__.py +0 -0
- inference_models/model_pipelines/auto_loaders/core.py +120 -0
- inference_models/model_pipelines/auto_loaders/pipelines_registry.py +36 -0
- inference_models/model_pipelines/face_and_gaze_detection/__init__.py +0 -0
- inference_models/model_pipelines/face_and_gaze_detection/mediapipe_l2cs.py +200 -0
- inference_models/models/__init__.py +0 -0
- inference_models/models/auto_loaders/__init__.py +0 -0
- inference_models/models/auto_loaders/access_manager.py +168 -0
- inference_models/models/auto_loaders/auto_negotiation.py +1329 -0
- inference_models/models/auto_loaders/auto_resolution_cache.py +129 -0
- inference_models/models/auto_loaders/constants.py +7 -0
- inference_models/models/auto_loaders/core.py +1341 -0
- inference_models/models/auto_loaders/dependency_models.py +52 -0
- inference_models/models/auto_loaders/entities.py +57 -0
- inference_models/models/auto_loaders/models_registry.py +497 -0
- inference_models/models/auto_loaders/presentation_utils.py +333 -0
- inference_models/models/auto_loaders/ranking.py +413 -0
- inference_models/models/auto_loaders/utils.py +31 -0
- inference_models/models/base/__init__.py +0 -0
- inference_models/models/base/classification.py +123 -0
- inference_models/models/base/depth_estimation.py +62 -0
- inference_models/models/base/documents_parsing.py +111 -0
- inference_models/models/base/embeddings.py +66 -0
- inference_models/models/base/instance_segmentation.py +87 -0
- inference_models/models/base/keypoints_detection.py +93 -0
- inference_models/models/base/object_detection.py +143 -0
- inference_models/models/base/semantic_segmentation.py +74 -0
- inference_models/models/base/types.py +5 -0
- inference_models/models/clip/__init__.py +0 -0
- inference_models/models/clip/clip_onnx.py +148 -0
- inference_models/models/clip/clip_pytorch.py +104 -0
- inference_models/models/clip/preprocessing.py +162 -0
- inference_models/models/common/__init__.py +0 -0
- inference_models/models/common/cuda.py +30 -0
- inference_models/models/common/model_packages.py +25 -0
- inference_models/models/common/onnx.py +379 -0
- inference_models/models/common/roboflow/__init__.py +0 -0
- inference_models/models/common/roboflow/model_packages.py +361 -0
- inference_models/models/common/roboflow/post_processing.py +436 -0
- inference_models/models/common/roboflow/pre_processing.py +1332 -0
- inference_models/models/common/torch.py +20 -0
- inference_models/models/common/trt.py +266 -0
- inference_models/models/deep_lab_v3_plus/__init__.py +0 -0
- inference_models/models/deep_lab_v3_plus/deep_lab_v3_plus_segmentation_onnx.py +282 -0
- inference_models/models/deep_lab_v3_plus/deep_lab_v3_plus_segmentation_torch.py +264 -0
- inference_models/models/deep_lab_v3_plus/deep_lab_v3_plus_segmentation_trt.py +313 -0
- inference_models/models/depth_anything_v2/__init__.py +0 -0
- inference_models/models/depth_anything_v2/depth_anything_v2_hf.py +77 -0
- inference_models/models/dinov3/__init__.py +0 -0
- inference_models/models/dinov3/dinov3_classification_onnx.py +348 -0
- inference_models/models/dinov3/dinov3_classification_torch.py +323 -0
- inference_models/models/doctr/__init__.py +0 -0
- inference_models/models/doctr/doctr_torch.py +304 -0
- inference_models/models/easy_ocr/__init__.py +0 -0
- inference_models/models/easy_ocr/easy_ocr_torch.py +222 -0
- inference_models/models/florence2/__init__.py +0 -0
- inference_models/models/florence2/florence2_hf.py +897 -0
- inference_models/models/grounding_dino/__init__.py +0 -0
- inference_models/models/grounding_dino/grounding_dino_torch.py +227 -0
- inference_models/models/l2cs/__init__.py +0 -0
- inference_models/models/l2cs/l2cs_onnx.py +216 -0
- inference_models/models/mediapipe_face_detection/__init__.py +0 -0
- inference_models/models/mediapipe_face_detection/face_detection.py +203 -0
- inference_models/models/moondream2/__init__.py +0 -0
- inference_models/models/moondream2/moondream2_hf.py +281 -0
- inference_models/models/owlv2/__init__.py +0 -0
- inference_models/models/owlv2/cache.py +182 -0
- inference_models/models/owlv2/entities.py +112 -0
- inference_models/models/owlv2/owlv2_hf.py +695 -0
- inference_models/models/owlv2/reference_dataset.py +291 -0
- inference_models/models/paligemma/__init__.py +0 -0
- inference_models/models/paligemma/paligemma_hf.py +209 -0
- inference_models/models/perception_encoder/__init__.py +0 -0
- inference_models/models/perception_encoder/perception_encoder_pytorch.py +197 -0
- inference_models/models/perception_encoder/vision_encoder/__init__.py +0 -0
- inference_models/models/perception_encoder/vision_encoder/config.py +160 -0
- inference_models/models/perception_encoder/vision_encoder/pe.py +742 -0
- inference_models/models/perception_encoder/vision_encoder/rope.py +344 -0
- inference_models/models/perception_encoder/vision_encoder/tokenizer.py +342 -0
- inference_models/models/perception_encoder/vision_encoder/transforms.py +33 -0
- inference_models/models/qwen25vl/__init__.py +1 -0
- inference_models/models/qwen25vl/qwen25vl_hf.py +285 -0
- inference_models/models/resnet/__init__.py +0 -0
- inference_models/models/resnet/resnet_classification_onnx.py +330 -0
- inference_models/models/resnet/resnet_classification_torch.py +305 -0
- inference_models/models/resnet/resnet_classification_trt.py +369 -0
- inference_models/models/rfdetr/__init__.py +0 -0
- inference_models/models/rfdetr/backbone_builder.py +101 -0
- inference_models/models/rfdetr/class_remapping.py +41 -0
- inference_models/models/rfdetr/common.py +115 -0
- inference_models/models/rfdetr/default_labels.py +108 -0
- inference_models/models/rfdetr/dinov2_with_windowed_attn.py +1330 -0
- inference_models/models/rfdetr/misc.py +26 -0
- inference_models/models/rfdetr/ms_deform_attn.py +180 -0
- inference_models/models/rfdetr/ms_deform_attn_func.py +60 -0
- inference_models/models/rfdetr/position_encoding.py +166 -0
- inference_models/models/rfdetr/post_processor.py +83 -0
- inference_models/models/rfdetr/projector.py +373 -0
- inference_models/models/rfdetr/rfdetr_backbone_pytorch.py +394 -0
- inference_models/models/rfdetr/rfdetr_base_pytorch.py +807 -0
- inference_models/models/rfdetr/rfdetr_instance_segmentation_onnx.py +206 -0
- inference_models/models/rfdetr/rfdetr_instance_segmentation_pytorch.py +373 -0
- inference_models/models/rfdetr/rfdetr_instance_segmentation_trt.py +227 -0
- inference_models/models/rfdetr/rfdetr_object_detection_onnx.py +244 -0
- inference_models/models/rfdetr/rfdetr_object_detection_pytorch.py +470 -0
- inference_models/models/rfdetr/rfdetr_object_detection_trt.py +270 -0
- inference_models/models/rfdetr/segmentation_head.py +273 -0
- inference_models/models/rfdetr/transformer.py +767 -0
- inference_models/models/roboflow_instant/__init__.py +0 -0
- inference_models/models/roboflow_instant/roboflow_instant_hf.py +141 -0
- inference_models/models/sam/__init__.py +0 -0
- inference_models/models/sam/cache.py +147 -0
- inference_models/models/sam/entities.py +25 -0
- inference_models/models/sam/sam_torch.py +675 -0
- inference_models/models/sam2/__init__.py +0 -0
- inference_models/models/sam2/cache.py +162 -0
- inference_models/models/sam2/entities.py +43 -0
- inference_models/models/sam2/sam2_torch.py +905 -0
- inference_models/models/sam2_rt/__init__.py +0 -0
- inference_models/models/sam2_rt/sam2_pytorch.py +119 -0
- inference_models/models/smolvlm/__init__.py +0 -0
- inference_models/models/smolvlm/smolvlm_hf.py +245 -0
- inference_models/models/trocr/__init__.py +0 -0
- inference_models/models/trocr/trocr_hf.py +53 -0
- inference_models/models/vit/__init__.py +0 -0
- inference_models/models/vit/vit_classification_huggingface.py +319 -0
- inference_models/models/vit/vit_classification_onnx.py +326 -0
- inference_models/models/vit/vit_classification_trt.py +365 -0
- inference_models/models/yolact/__init__.py +1 -0
- inference_models/models/yolact/yolact_instance_segmentation_onnx.py +336 -0
- inference_models/models/yolact/yolact_instance_segmentation_trt.py +361 -0
- inference_models/models/yolo_world/__init__.py +1 -0
- inference_models/models/yolonas/__init__.py +0 -0
- inference_models/models/yolonas/nms.py +44 -0
- inference_models/models/yolonas/yolonas_object_detection_onnx.py +204 -0
- inference_models/models/yolonas/yolonas_object_detection_trt.py +230 -0
- inference_models/models/yolov10/__init__.py +0 -0
- inference_models/models/yolov10/yolov10_object_detection_onnx.py +187 -0
- inference_models/models/yolov10/yolov10_object_detection_trt.py +215 -0
- inference_models/models/yolov11/__init__.py +0 -0
- inference_models/models/yolov11/yolov11_onnx.py +28 -0
- inference_models/models/yolov11/yolov11_torch_script.py +25 -0
- inference_models/models/yolov11/yolov11_trt.py +21 -0
- inference_models/models/yolov12/__init__.py +0 -0
- inference_models/models/yolov12/yolov12_onnx.py +7 -0
- inference_models/models/yolov12/yolov12_torch_script.py +7 -0
- inference_models/models/yolov12/yolov12_trt.py +7 -0
- inference_models/models/yolov5/__init__.py +0 -0
- inference_models/models/yolov5/nms.py +99 -0
- inference_models/models/yolov5/yolov5_instance_segmentation_onnx.py +225 -0
- inference_models/models/yolov5/yolov5_instance_segmentation_trt.py +255 -0
- inference_models/models/yolov5/yolov5_object_detection_onnx.py +192 -0
- inference_models/models/yolov5/yolov5_object_detection_trt.py +218 -0
- inference_models/models/yolov7/__init__.py +0 -0
- inference_models/models/yolov7/yolov7_instance_segmentation_onnx.py +226 -0
- inference_models/models/yolov7/yolov7_instance_segmentation_trt.py +253 -0
- inference_models/models/yolov8/__init__.py +0 -0
- inference_models/models/yolov8/yolov8_classification_onnx.py +181 -0
- inference_models/models/yolov8/yolov8_instance_segmentation_onnx.py +239 -0
- inference_models/models/yolov8/yolov8_instance_segmentation_torch_script.py +201 -0
- inference_models/models/yolov8/yolov8_instance_segmentation_trt.py +268 -0
- inference_models/models/yolov8/yolov8_key_points_detection_onnx.py +263 -0
- inference_models/models/yolov8/yolov8_key_points_detection_torch_script.py +218 -0
- inference_models/models/yolov8/yolov8_key_points_detection_trt.py +287 -0
- inference_models/models/yolov8/yolov8_object_detection_onnx.py +213 -0
- inference_models/models/yolov8/yolov8_object_detection_torch_script.py +166 -0
- inference_models/models/yolov8/yolov8_object_detection_trt.py +231 -0
- inference_models/models/yolov9/__init__.py +0 -0
- inference_models/models/yolov9/yolov9_onnx.py +7 -0
- inference_models/models/yolov9/yolov9_torch_script.py +7 -0
- inference_models/models/yolov9/yolov9_trt.py +7 -0
- inference_models/runtime_introspection/__init__.py +0 -0
- inference_models/runtime_introspection/core.py +410 -0
- inference_models/utils/__init__.py +0 -0
- inference_models/utils/download.py +608 -0
- inference_models/utils/environment.py +28 -0
- inference_models/utils/file_system.py +51 -0
- inference_models/utils/hashing.py +7 -0
- inference_models/utils/imports.py +48 -0
- inference_models/utils/onnx_introspection.py +17 -0
- inference_models/weights_providers/__init__.py +0 -0
- inference_models/weights_providers/core.py +20 -0
- inference_models/weights_providers/entities.py +159 -0
- inference_models/weights_providers/roboflow.py +601 -0
- inference_models-0.18.3.dist-info/METADATA +466 -0
- inference_models-0.18.3.dist-info/RECORD +195 -0
- inference_models-0.18.3.dist-info/WHEEL +5 -0
- inference_models-0.18.3.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
from threading import Lock
|
|
2
|
+
from typing import List, Optional, Tuple, Union
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
import torch
|
|
6
|
+
|
|
7
|
+
from inference_models import Detections, ObjectDetectionModel
|
|
8
|
+
from inference_models.configuration import DEFAULT_DEVICE
|
|
9
|
+
from inference_models.entities import ColorFormat
|
|
10
|
+
from inference_models.errors import (
|
|
11
|
+
EnvironmentConfigurationError,
|
|
12
|
+
MissingDependencyError,
|
|
13
|
+
)
|
|
14
|
+
from inference_models.models.common.model_packages import get_model_package_contents
|
|
15
|
+
from inference_models.models.common.onnx import (
|
|
16
|
+
run_session_with_batch_size_limit,
|
|
17
|
+
set_execution_provider_defaults,
|
|
18
|
+
)
|
|
19
|
+
from inference_models.models.common.roboflow.model_packages import (
|
|
20
|
+
InferenceConfig,
|
|
21
|
+
PreProcessingMetadata,
|
|
22
|
+
ResizeMode,
|
|
23
|
+
parse_class_names_file,
|
|
24
|
+
parse_inference_config,
|
|
25
|
+
)
|
|
26
|
+
from inference_models.models.common.roboflow.post_processing import rescale_detections
|
|
27
|
+
from inference_models.models.common.roboflow.pre_processing import (
|
|
28
|
+
pre_process_network_input,
|
|
29
|
+
)
|
|
30
|
+
from inference_models.models.yolov5.nms import run_nms_yolov5
|
|
31
|
+
from inference_models.utils.onnx_introspection import (
|
|
32
|
+
get_selected_onnx_execution_providers,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
try:
|
|
36
|
+
import onnxruntime
|
|
37
|
+
except ImportError as import_error:
|
|
38
|
+
raise MissingDependencyError(
|
|
39
|
+
message=f"Could not import YOLOv5 model with ONNX backend - this error means that some additional dependencies "
|
|
40
|
+
f"are not installed in the environment. If you run the `inference-models` library directly in your Python "
|
|
41
|
+
f"program, make sure the following extras of the package are installed: \n"
|
|
42
|
+
f"\t* `onnx-cpu` - when you wish to use library with CPU support only\n"
|
|
43
|
+
f"\t* `onnx-cu12` - for running on GPU with Cuda 12 installed\n"
|
|
44
|
+
f"\t* `onnx-cu118` - for running on GPU with Cuda 11.8 installed\n"
|
|
45
|
+
f"\t* `onnx-jp6-cu126` - for running on Jetson with Jetpack 6\n"
|
|
46
|
+
f"If you see this error using Roboflow infrastructure, make sure the service you use does support the model. "
|
|
47
|
+
f"You can also contact Roboflow to get support.",
|
|
48
|
+
help_url="https://todo",
|
|
49
|
+
) from import_error
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class YOLOv5ForObjectDetectionOnnx(
|
|
53
|
+
ObjectDetectionModel[torch.Tensor, PreProcessingMetadata, torch.Tensor]
|
|
54
|
+
):
|
|
55
|
+
|
|
56
|
+
@classmethod
|
|
57
|
+
def from_pretrained(
|
|
58
|
+
cls,
|
|
59
|
+
model_name_or_path: str,
|
|
60
|
+
onnx_execution_providers: Optional[List[Union[str, tuple]]] = None,
|
|
61
|
+
default_onnx_trt_options: bool = True,
|
|
62
|
+
device: torch.device = DEFAULT_DEVICE,
|
|
63
|
+
**kwargs,
|
|
64
|
+
) -> "YOLOv5ForObjectDetectionOnnx":
|
|
65
|
+
if onnx_execution_providers is None:
|
|
66
|
+
onnx_execution_providers = get_selected_onnx_execution_providers()
|
|
67
|
+
if not onnx_execution_providers:
|
|
68
|
+
raise EnvironmentConfigurationError(
|
|
69
|
+
message=f"Could not initialize model - selected backend is ONNX which requires execution provider to "
|
|
70
|
+
f"be specified - explicitly in `from_pretrained(...)` method or via env variable "
|
|
71
|
+
f"`ONNXRUNTIME_EXECUTION_PROVIDERS`. If you run model locally - adjust your setup, otherwise "
|
|
72
|
+
f"contact the platform support.",
|
|
73
|
+
help_url="https://todo",
|
|
74
|
+
)
|
|
75
|
+
onnx_execution_providers = set_execution_provider_defaults(
|
|
76
|
+
providers=onnx_execution_providers,
|
|
77
|
+
model_package_path=model_name_or_path,
|
|
78
|
+
device=device,
|
|
79
|
+
default_onnx_trt_options=default_onnx_trt_options,
|
|
80
|
+
)
|
|
81
|
+
model_package_content = get_model_package_contents(
|
|
82
|
+
model_package_dir=model_name_or_path,
|
|
83
|
+
elements=[
|
|
84
|
+
"class_names.txt",
|
|
85
|
+
"inference_config.json",
|
|
86
|
+
"weights.onnx",
|
|
87
|
+
],
|
|
88
|
+
)
|
|
89
|
+
class_names = parse_class_names_file(
|
|
90
|
+
class_names_path=model_package_content["class_names.txt"]
|
|
91
|
+
)
|
|
92
|
+
inference_config = parse_inference_config(
|
|
93
|
+
config_path=model_package_content["inference_config.json"],
|
|
94
|
+
allowed_resize_modes={
|
|
95
|
+
ResizeMode.STRETCH_TO,
|
|
96
|
+
ResizeMode.LETTERBOX,
|
|
97
|
+
ResizeMode.CENTER_CROP,
|
|
98
|
+
ResizeMode.LETTERBOX_REFLECT_EDGES,
|
|
99
|
+
},
|
|
100
|
+
)
|
|
101
|
+
session = onnxruntime.InferenceSession(
|
|
102
|
+
path_or_bytes=model_package_content["weights.onnx"],
|
|
103
|
+
providers=onnx_execution_providers,
|
|
104
|
+
)
|
|
105
|
+
input_batch_size = session.get_inputs()[0].shape[0]
|
|
106
|
+
if isinstance(input_batch_size, str):
|
|
107
|
+
input_batch_size = None
|
|
108
|
+
input_name = session.get_inputs()[0].name
|
|
109
|
+
return cls(
|
|
110
|
+
session=session,
|
|
111
|
+
input_name=input_name,
|
|
112
|
+
class_names=class_names,
|
|
113
|
+
inference_config=inference_config,
|
|
114
|
+
device=device,
|
|
115
|
+
input_batch_size=input_batch_size,
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
def __init__(
|
|
119
|
+
self,
|
|
120
|
+
session: onnxruntime.InferenceSession,
|
|
121
|
+
input_name: str,
|
|
122
|
+
inference_config: InferenceConfig,
|
|
123
|
+
class_names: List[str],
|
|
124
|
+
device: torch.device,
|
|
125
|
+
input_batch_size: Optional[int],
|
|
126
|
+
):
|
|
127
|
+
self._session = session
|
|
128
|
+
self._input_name = input_name
|
|
129
|
+
self._inference_config = inference_config
|
|
130
|
+
self._class_names = class_names
|
|
131
|
+
self._device = device
|
|
132
|
+
self._input_batch_size = input_batch_size
|
|
133
|
+
self._session_thread_lock = Lock()
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def class_names(self) -> List[str]:
|
|
137
|
+
return self._class_names
|
|
138
|
+
|
|
139
|
+
def pre_process(
|
|
140
|
+
self,
|
|
141
|
+
images: Union[torch.Tensor, List[torch.Tensor], np.ndarray, List[np.ndarray]],
|
|
142
|
+
input_color_format: Optional[ColorFormat] = None,
|
|
143
|
+
**kwargs,
|
|
144
|
+
) -> Tuple[torch.Tensor, List[PreProcessingMetadata]]:
|
|
145
|
+
return pre_process_network_input(
|
|
146
|
+
images=images,
|
|
147
|
+
image_pre_processing=self._inference_config.image_pre_processing,
|
|
148
|
+
network_input=self._inference_config.network_input,
|
|
149
|
+
target_device=self._device,
|
|
150
|
+
input_color_format=input_color_format,
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
def forward(self, pre_processed_images: torch.Tensor, **kwargs) -> torch.Tensor:
|
|
154
|
+
with self._session_thread_lock:
|
|
155
|
+
return run_session_with_batch_size_limit(
|
|
156
|
+
session=self._session,
|
|
157
|
+
inputs={self._input_name: pre_processed_images},
|
|
158
|
+
min_batch_size=self._input_batch_size,
|
|
159
|
+
max_batch_size=self._input_batch_size,
|
|
160
|
+
)[0]
|
|
161
|
+
|
|
162
|
+
def post_process(
|
|
163
|
+
self,
|
|
164
|
+
model_results: torch.Tensor,
|
|
165
|
+
pre_processing_meta: List[PreProcessingMetadata],
|
|
166
|
+
conf_thresh: float = 0.25,
|
|
167
|
+
iou_thresh: float = 0.45,
|
|
168
|
+
max_detections: int = 100,
|
|
169
|
+
class_agnostic: bool = False,
|
|
170
|
+
**kwargs,
|
|
171
|
+
) -> List[Detections]:
|
|
172
|
+
nms_results = run_nms_yolov5(
|
|
173
|
+
output=model_results.permute(0, 2, 1),
|
|
174
|
+
conf_thresh=conf_thresh,
|
|
175
|
+
iou_thresh=iou_thresh,
|
|
176
|
+
max_detections=max_detections,
|
|
177
|
+
class_agnostic=class_agnostic,
|
|
178
|
+
)
|
|
179
|
+
rescaled_results = rescale_detections(
|
|
180
|
+
detections=nms_results,
|
|
181
|
+
images_metadata=pre_processing_meta,
|
|
182
|
+
)
|
|
183
|
+
results = []
|
|
184
|
+
for result in rescaled_results:
|
|
185
|
+
results.append(
|
|
186
|
+
Detections(
|
|
187
|
+
xyxy=result[:, :4].round().int(),
|
|
188
|
+
class_id=result[:, 5].int(),
|
|
189
|
+
confidence=result[:, 4],
|
|
190
|
+
)
|
|
191
|
+
)
|
|
192
|
+
return results
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
from threading import Lock
|
|
2
|
+
from typing import List, Optional, Tuple, Union
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
import torch
|
|
6
|
+
|
|
7
|
+
from inference_models import Detections, ObjectDetectionModel
|
|
8
|
+
from inference_models.configuration import DEFAULT_DEVICE
|
|
9
|
+
from inference_models.entities import ColorFormat
|
|
10
|
+
from inference_models.errors import (
|
|
11
|
+
CorruptedModelPackageError,
|
|
12
|
+
MissingDependencyError,
|
|
13
|
+
ModelRuntimeError,
|
|
14
|
+
)
|
|
15
|
+
from inference_models.models.common.cuda import (
|
|
16
|
+
use_cuda_context,
|
|
17
|
+
use_primary_cuda_context,
|
|
18
|
+
)
|
|
19
|
+
from inference_models.models.common.model_packages import get_model_package_contents
|
|
20
|
+
from inference_models.models.common.roboflow.model_packages import (
|
|
21
|
+
InferenceConfig,
|
|
22
|
+
PreProcessingMetadata,
|
|
23
|
+
ResizeMode,
|
|
24
|
+
TRTConfig,
|
|
25
|
+
parse_class_names_file,
|
|
26
|
+
parse_inference_config,
|
|
27
|
+
parse_trt_config,
|
|
28
|
+
)
|
|
29
|
+
from inference_models.models.common.roboflow.post_processing import rescale_detections
|
|
30
|
+
from inference_models.models.common.roboflow.pre_processing import (
|
|
31
|
+
pre_process_network_input,
|
|
32
|
+
)
|
|
33
|
+
from inference_models.models.common.trt import (
|
|
34
|
+
get_engine_inputs_and_outputs,
|
|
35
|
+
infer_from_trt_engine,
|
|
36
|
+
load_model,
|
|
37
|
+
)
|
|
38
|
+
from inference_models.models.yolov5.nms import run_nms_yolov5
|
|
39
|
+
|
|
40
|
+
try:
|
|
41
|
+
import tensorrt as trt
|
|
42
|
+
except ImportError as import_error:
|
|
43
|
+
raise MissingDependencyError(
|
|
44
|
+
message=f"Could not import YOLOv5 model with TRT backend - this error means that some additional dependencies "
|
|
45
|
+
f"are not installed in the environment. If you run the `inference-models` library directly in your Python "
|
|
46
|
+
f"program, make sure the following extras of the package are installed: `trt10` - installation can only "
|
|
47
|
+
f"succeed for Linux and Windows machines with Cuda 12 installed. Jetson devices, should have TRT 10.x "
|
|
48
|
+
f"installed for all builds with Jetpack 6. "
|
|
49
|
+
f"If you see this error using Roboflow infrastructure, make sure the service you use does support the model. "
|
|
50
|
+
f"You can also contact Roboflow to get support.",
|
|
51
|
+
help_url="https://todo",
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
try:
|
|
55
|
+
import pycuda.driver as cuda
|
|
56
|
+
except ImportError as import_error:
|
|
57
|
+
raise MissingDependencyError(
|
|
58
|
+
message="TODO", help_url="https://todo"
|
|
59
|
+
) from import_error
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class YOLOv5ForObjectDetectionTRT(
|
|
63
|
+
ObjectDetectionModel[torch.Tensor, PreProcessingMetadata, torch.Tensor]
|
|
64
|
+
):
|
|
65
|
+
|
|
66
|
+
@classmethod
|
|
67
|
+
def from_pretrained(
|
|
68
|
+
cls,
|
|
69
|
+
model_name_or_path: str,
|
|
70
|
+
device: torch.device = DEFAULT_DEVICE,
|
|
71
|
+
engine_host_code_allowed: bool = False,
|
|
72
|
+
**kwargs,
|
|
73
|
+
) -> "YOLOv5ForObjectDetectionTRT":
|
|
74
|
+
if device.type != "cuda":
|
|
75
|
+
raise ModelRuntimeError(
|
|
76
|
+
message=f"TRT engine only runs on CUDA device - {device} device detected.",
|
|
77
|
+
help_url="https://todo",
|
|
78
|
+
)
|
|
79
|
+
model_package_content = get_model_package_contents(
|
|
80
|
+
model_package_dir=model_name_or_path,
|
|
81
|
+
elements=[
|
|
82
|
+
"class_names.txt",
|
|
83
|
+
"inference_config.json",
|
|
84
|
+
"trt_config.json",
|
|
85
|
+
"engine.plan",
|
|
86
|
+
],
|
|
87
|
+
)
|
|
88
|
+
class_names = parse_class_names_file(
|
|
89
|
+
class_names_path=model_package_content["class_names.txt"]
|
|
90
|
+
)
|
|
91
|
+
inference_config = parse_inference_config(
|
|
92
|
+
config_path=model_package_content["inference_config.json"],
|
|
93
|
+
allowed_resize_modes={
|
|
94
|
+
ResizeMode.STRETCH_TO,
|
|
95
|
+
ResizeMode.LETTERBOX,
|
|
96
|
+
ResizeMode.CENTER_CROP,
|
|
97
|
+
ResizeMode.LETTERBOX_REFLECT_EDGES,
|
|
98
|
+
},
|
|
99
|
+
)
|
|
100
|
+
trt_config = parse_trt_config(
|
|
101
|
+
config_path=model_package_content["trt_config.json"]
|
|
102
|
+
)
|
|
103
|
+
cuda.init()
|
|
104
|
+
cuda_device = cuda.Device(device.index or 0)
|
|
105
|
+
with use_primary_cuda_context(cuda_device=cuda_device) as cuda_context:
|
|
106
|
+
engine = load_model(
|
|
107
|
+
model_path=model_package_content["engine.plan"],
|
|
108
|
+
engine_host_code_allowed=engine_host_code_allowed,
|
|
109
|
+
)
|
|
110
|
+
execution_context = engine.create_execution_context()
|
|
111
|
+
inputs, outputs = get_engine_inputs_and_outputs(engine=engine)
|
|
112
|
+
if len(inputs) != 1:
|
|
113
|
+
raise CorruptedModelPackageError(
|
|
114
|
+
message=f"Implementation assume single model input, found: {len(inputs)}.",
|
|
115
|
+
help_url="https://todo",
|
|
116
|
+
)
|
|
117
|
+
if len(outputs) != 1:
|
|
118
|
+
raise CorruptedModelPackageError(
|
|
119
|
+
message=f"Implementation assume single model output, found: {len(outputs)}.",
|
|
120
|
+
help_url="https://todo",
|
|
121
|
+
)
|
|
122
|
+
return cls(
|
|
123
|
+
engine=engine,
|
|
124
|
+
input_name=inputs[0],
|
|
125
|
+
output_name=outputs[0],
|
|
126
|
+
class_names=class_names,
|
|
127
|
+
inference_config=inference_config,
|
|
128
|
+
trt_config=trt_config,
|
|
129
|
+
device=device,
|
|
130
|
+
cuda_context=cuda_context,
|
|
131
|
+
execution_context=execution_context,
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
def __init__(
|
|
135
|
+
self,
|
|
136
|
+
engine: trt.ICudaEngine,
|
|
137
|
+
input_name: str,
|
|
138
|
+
output_name: str,
|
|
139
|
+
class_names: List[str],
|
|
140
|
+
inference_config: InferenceConfig,
|
|
141
|
+
trt_config: TRTConfig,
|
|
142
|
+
device: torch.device,
|
|
143
|
+
cuda_context: cuda.Context,
|
|
144
|
+
execution_context: trt.IExecutionContext,
|
|
145
|
+
):
|
|
146
|
+
self._engine = engine
|
|
147
|
+
self._input_name = input_name
|
|
148
|
+
self._output_names = [output_name]
|
|
149
|
+
self._class_names = class_names
|
|
150
|
+
self._inference_config = inference_config
|
|
151
|
+
self._trt_config = trt_config
|
|
152
|
+
self._device = device
|
|
153
|
+
self._cuda_context = cuda_context
|
|
154
|
+
self._execution_context = execution_context
|
|
155
|
+
self._session_thread_lock = Lock()
|
|
156
|
+
|
|
157
|
+
@property
|
|
158
|
+
def class_names(self) -> List[str]:
|
|
159
|
+
return self._class_names
|
|
160
|
+
|
|
161
|
+
def pre_process(
|
|
162
|
+
self,
|
|
163
|
+
images: Union[torch.Tensor, List[torch.Tensor], np.ndarray, List[np.ndarray]],
|
|
164
|
+
input_color_format: Optional[ColorFormat] = None,
|
|
165
|
+
**kwargs,
|
|
166
|
+
) -> Tuple[torch.Tensor, List[PreProcessingMetadata]]:
|
|
167
|
+
return pre_process_network_input(
|
|
168
|
+
images=images,
|
|
169
|
+
image_pre_processing=self._inference_config.image_pre_processing,
|
|
170
|
+
network_input=self._inference_config.network_input,
|
|
171
|
+
target_device=self._device,
|
|
172
|
+
input_color_format=input_color_format,
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
def forward(self, pre_processed_images: torch.Tensor, **kwargs) -> torch.Tensor:
|
|
176
|
+
with self._session_thread_lock:
|
|
177
|
+
with use_cuda_context(context=self._cuda_context):
|
|
178
|
+
return infer_from_trt_engine(
|
|
179
|
+
pre_processed_images=pre_processed_images,
|
|
180
|
+
trt_config=self._trt_config,
|
|
181
|
+
engine=self._engine,
|
|
182
|
+
context=self._execution_context,
|
|
183
|
+
device=self._device,
|
|
184
|
+
input_name=self._input_name,
|
|
185
|
+
outputs=self._output_names,
|
|
186
|
+
)[0]
|
|
187
|
+
|
|
188
|
+
def post_process(
|
|
189
|
+
self,
|
|
190
|
+
model_results: torch.Tensor,
|
|
191
|
+
pre_processing_meta: List[PreProcessingMetadata],
|
|
192
|
+
conf_thresh: float = 0.25,
|
|
193
|
+
iou_thresh: float = 0.45,
|
|
194
|
+
max_detections: int = 100,
|
|
195
|
+
class_agnostic: bool = False,
|
|
196
|
+
**kwargs,
|
|
197
|
+
) -> List[Detections]:
|
|
198
|
+
nms_results = run_nms_yolov5(
|
|
199
|
+
output=model_results.permute(0, 2, 1),
|
|
200
|
+
conf_thresh=conf_thresh,
|
|
201
|
+
iou_thresh=iou_thresh,
|
|
202
|
+
max_detections=max_detections,
|
|
203
|
+
class_agnostic=class_agnostic,
|
|
204
|
+
)
|
|
205
|
+
rescaled_results = rescale_detections(
|
|
206
|
+
detections=nms_results,
|
|
207
|
+
images_metadata=pre_processing_meta,
|
|
208
|
+
)
|
|
209
|
+
results = []
|
|
210
|
+
for result in rescaled_results:
|
|
211
|
+
results.append(
|
|
212
|
+
Detections(
|
|
213
|
+
xyxy=result[:, :4].round().int(),
|
|
214
|
+
class_id=result[:, 5].int(),
|
|
215
|
+
confidence=result[:, 4],
|
|
216
|
+
)
|
|
217
|
+
)
|
|
218
|
+
return results
|
|
File without changes
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
from threading import Lock
|
|
2
|
+
from typing import List, Optional, Tuple, Union
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
import torch
|
|
6
|
+
|
|
7
|
+
from inference_models import InstanceDetections, InstanceSegmentationModel
|
|
8
|
+
from inference_models.configuration import DEFAULT_DEVICE
|
|
9
|
+
from inference_models.entities import ColorFormat
|
|
10
|
+
from inference_models.errors import (
|
|
11
|
+
EnvironmentConfigurationError,
|
|
12
|
+
MissingDependencyError,
|
|
13
|
+
)
|
|
14
|
+
from inference_models.models.common.model_packages import get_model_package_contents
|
|
15
|
+
from inference_models.models.common.onnx import (
|
|
16
|
+
run_session_with_batch_size_limit,
|
|
17
|
+
set_execution_provider_defaults,
|
|
18
|
+
)
|
|
19
|
+
from inference_models.models.common.roboflow.model_packages import (
|
|
20
|
+
InferenceConfig,
|
|
21
|
+
PreProcessingMetadata,
|
|
22
|
+
ResizeMode,
|
|
23
|
+
parse_class_names_file,
|
|
24
|
+
parse_inference_config,
|
|
25
|
+
)
|
|
26
|
+
from inference_models.models.common.roboflow.post_processing import (
|
|
27
|
+
align_instance_segmentation_results,
|
|
28
|
+
crop_masks_to_boxes,
|
|
29
|
+
preprocess_segmentation_masks,
|
|
30
|
+
run_nms_for_instance_segmentation,
|
|
31
|
+
)
|
|
32
|
+
from inference_models.models.common.roboflow.pre_processing import (
|
|
33
|
+
pre_process_network_input,
|
|
34
|
+
)
|
|
35
|
+
from inference_models.utils.onnx_introspection import (
|
|
36
|
+
get_selected_onnx_execution_providers,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
import onnxruntime
|
|
41
|
+
except ImportError as import_error:
|
|
42
|
+
raise MissingDependencyError(
|
|
43
|
+
message=f"Could not import YOLOv7 model with ONNX backend - this error means that some additional dependencies "
|
|
44
|
+
f"are not installed in the environment. If you run the `inference-models` library directly in your Python "
|
|
45
|
+
f"program, make sure the following extras of the package are installed: \n"
|
|
46
|
+
f"\t* `onnx-cpu` - when you wish to use library with CPU support only\n"
|
|
47
|
+
f"\t* `onnx-cu12` - for running on GPU with Cuda 12 installed\n"
|
|
48
|
+
f"\t* `onnx-cu118` - for running on GPU with Cuda 11.8 installed\n"
|
|
49
|
+
f"\t* `onnx-jp6-cu126` - for running on Jetson with Jetpack 6\n"
|
|
50
|
+
f"If you see this error using Roboflow infrastructure, make sure the service you use does support the model. "
|
|
51
|
+
f"You can also contact Roboflow to get support.",
|
|
52
|
+
help_url="https://todo",
|
|
53
|
+
) from import_error
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class YOLOv7ForInstanceSegmentationOnnx(
|
|
57
|
+
InstanceSegmentationModel[
|
|
58
|
+
torch.Tensor, PreProcessingMetadata, Tuple[torch.Tensor, torch.Tensor]
|
|
59
|
+
]
|
|
60
|
+
):
|
|
61
|
+
|
|
62
|
+
@classmethod
|
|
63
|
+
def from_pretrained(
|
|
64
|
+
cls,
|
|
65
|
+
model_name_or_path: str,
|
|
66
|
+
onnx_execution_providers: Optional[List[Union[str, tuple]]] = None,
|
|
67
|
+
default_onnx_trt_options: bool = True,
|
|
68
|
+
device: torch.device = DEFAULT_DEVICE,
|
|
69
|
+
**kwargs,
|
|
70
|
+
) -> "YOLOv7ForInstanceSegmentationOnnx":
|
|
71
|
+
if onnx_execution_providers is None:
|
|
72
|
+
onnx_execution_providers = get_selected_onnx_execution_providers()
|
|
73
|
+
if not onnx_execution_providers:
|
|
74
|
+
raise EnvironmentConfigurationError(
|
|
75
|
+
message=f"Could not initialize model - selected backend is ONNX which requires execution provider to "
|
|
76
|
+
f"be specified - explicitly in `from_pretrained(...)` method or via env variable "
|
|
77
|
+
f"`ONNXRUNTIME_EXECUTION_PROVIDERS`. If you run model locally - adjust your setup, otherwise "
|
|
78
|
+
f"contact the platform support.",
|
|
79
|
+
help_url="https://todo",
|
|
80
|
+
)
|
|
81
|
+
onnx_execution_providers = set_execution_provider_defaults(
|
|
82
|
+
providers=onnx_execution_providers,
|
|
83
|
+
model_package_path=model_name_or_path,
|
|
84
|
+
device=device,
|
|
85
|
+
default_onnx_trt_options=default_onnx_trt_options,
|
|
86
|
+
)
|
|
87
|
+
model_package_content = get_model_package_contents(
|
|
88
|
+
model_package_dir=model_name_or_path,
|
|
89
|
+
elements=[
|
|
90
|
+
"class_names.txt",
|
|
91
|
+
"inference_config.json",
|
|
92
|
+
"weights.onnx",
|
|
93
|
+
],
|
|
94
|
+
)
|
|
95
|
+
class_names = parse_class_names_file(
|
|
96
|
+
class_names_path=model_package_content["class_names.txt"]
|
|
97
|
+
)
|
|
98
|
+
inference_config = parse_inference_config(
|
|
99
|
+
config_path=model_package_content["inference_config.json"],
|
|
100
|
+
allowed_resize_modes={
|
|
101
|
+
ResizeMode.STRETCH_TO,
|
|
102
|
+
ResizeMode.LETTERBOX,
|
|
103
|
+
ResizeMode.CENTER_CROP,
|
|
104
|
+
ResizeMode.LETTERBOX_REFLECT_EDGES,
|
|
105
|
+
},
|
|
106
|
+
)
|
|
107
|
+
session = onnxruntime.InferenceSession(
|
|
108
|
+
path_or_bytes=model_package_content["weights.onnx"],
|
|
109
|
+
providers=onnx_execution_providers,
|
|
110
|
+
)
|
|
111
|
+
input_batch_size = session.get_inputs()[0].shape[0]
|
|
112
|
+
if isinstance(input_batch_size, str):
|
|
113
|
+
input_batch_size = None
|
|
114
|
+
input_name = session.get_inputs()[0].name
|
|
115
|
+
return cls(
|
|
116
|
+
session=session,
|
|
117
|
+
input_name=input_name,
|
|
118
|
+
class_names=class_names,
|
|
119
|
+
inference_config=inference_config,
|
|
120
|
+
device=device,
|
|
121
|
+
input_batch_size=input_batch_size,
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
def __init__(
|
|
125
|
+
self,
|
|
126
|
+
session: onnxruntime.InferenceSession,
|
|
127
|
+
input_name: str,
|
|
128
|
+
inference_config: InferenceConfig,
|
|
129
|
+
class_names: List[str],
|
|
130
|
+
device: torch.device,
|
|
131
|
+
input_batch_size: Optional[int],
|
|
132
|
+
):
|
|
133
|
+
self._session = session
|
|
134
|
+
self._input_name = input_name
|
|
135
|
+
self._inference_config = inference_config
|
|
136
|
+
self._class_names = class_names
|
|
137
|
+
self._device = device
|
|
138
|
+
self._input_batch_size = input_batch_size
|
|
139
|
+
self._session_thread_lock = Lock()
|
|
140
|
+
|
|
141
|
+
@property
|
|
142
|
+
def class_names(self) -> List[str]:
|
|
143
|
+
return self._class_names
|
|
144
|
+
|
|
145
|
+
def pre_process(
|
|
146
|
+
self,
|
|
147
|
+
images: Union[torch.Tensor, List[torch.Tensor], np.ndarray, List[np.ndarray]],
|
|
148
|
+
input_color_format: Optional[ColorFormat] = None,
|
|
149
|
+
**kwargs,
|
|
150
|
+
) -> Tuple[torch.Tensor, List[PreProcessingMetadata]]:
|
|
151
|
+
return pre_process_network_input(
|
|
152
|
+
images=images,
|
|
153
|
+
image_pre_processing=self._inference_config.image_pre_processing,
|
|
154
|
+
network_input=self._inference_config.network_input,
|
|
155
|
+
target_device=self._device,
|
|
156
|
+
input_color_format=input_color_format,
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
def forward(
|
|
160
|
+
self, pre_processed_images: torch.Tensor, **kwargs
|
|
161
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
162
|
+
with self._session_thread_lock:
|
|
163
|
+
raw_outputs = run_session_with_batch_size_limit(
|
|
164
|
+
session=self._session,
|
|
165
|
+
inputs={self._input_name: pre_processed_images},
|
|
166
|
+
min_batch_size=self._input_batch_size,
|
|
167
|
+
max_batch_size=self._input_batch_size,
|
|
168
|
+
)
|
|
169
|
+
instances, protos = raw_outputs[0], raw_outputs[4]
|
|
170
|
+
return instances, protos
|
|
171
|
+
|
|
172
|
+
def post_process(
|
|
173
|
+
self,
|
|
174
|
+
model_results: Tuple[torch.Tensor, torch.Tensor],
|
|
175
|
+
pre_processing_meta: List[PreProcessingMetadata],
|
|
176
|
+
conf_thresh: float = 0.25,
|
|
177
|
+
iou_thresh: float = 0.45,
|
|
178
|
+
max_detections: int = 100,
|
|
179
|
+
class_agnostic: bool = False,
|
|
180
|
+
**kwargs,
|
|
181
|
+
) -> List[InstanceDetections]:
|
|
182
|
+
instances, protos = model_results
|
|
183
|
+
nms_results = run_nms_for_instance_segmentation(
|
|
184
|
+
output=instances.permute(0, 2, 1),
|
|
185
|
+
conf_thresh=conf_thresh,
|
|
186
|
+
iou_thresh=iou_thresh,
|
|
187
|
+
max_detections=max_detections,
|
|
188
|
+
class_agnostic=class_agnostic,
|
|
189
|
+
)
|
|
190
|
+
final_results = []
|
|
191
|
+
for image_bboxes, image_protos, image_meta in zip(
|
|
192
|
+
nms_results, protos, pre_processing_meta
|
|
193
|
+
):
|
|
194
|
+
pre_processed_masks = preprocess_segmentation_masks(
|
|
195
|
+
protos=image_protos,
|
|
196
|
+
masks_in=image_bboxes[:, 6:],
|
|
197
|
+
)
|
|
198
|
+
cropped_masks = crop_masks_to_boxes(
|
|
199
|
+
image_bboxes[:, :4], pre_processed_masks
|
|
200
|
+
)
|
|
201
|
+
padding = (
|
|
202
|
+
image_meta.pad_left,
|
|
203
|
+
image_meta.pad_top,
|
|
204
|
+
image_meta.pad_right,
|
|
205
|
+
image_meta.pad_bottom,
|
|
206
|
+
)
|
|
207
|
+
aligned_boxes, aligned_masks = align_instance_segmentation_results(
|
|
208
|
+
image_bboxes=image_bboxes,
|
|
209
|
+
masks=cropped_masks,
|
|
210
|
+
padding=padding,
|
|
211
|
+
scale_height=image_meta.scale_height,
|
|
212
|
+
scale_width=image_meta.scale_width,
|
|
213
|
+
original_size=image_meta.original_size,
|
|
214
|
+
size_after_pre_processing=image_meta.size_after_pre_processing,
|
|
215
|
+
inference_size=image_meta.inference_size,
|
|
216
|
+
static_crop_offset=image_meta.static_crop_offset,
|
|
217
|
+
)
|
|
218
|
+
final_results.append(
|
|
219
|
+
InstanceDetections(
|
|
220
|
+
xyxy=aligned_boxes[:, :4].round().int(),
|
|
221
|
+
class_id=aligned_boxes[:, 5].int(),
|
|
222
|
+
confidence=aligned_boxes[:, 4],
|
|
223
|
+
mask=aligned_masks,
|
|
224
|
+
)
|
|
225
|
+
)
|
|
226
|
+
return final_results
|