ultralytics-opencv-headless 8.3.242__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.
Files changed (298) hide show
  1. tests/__init__.py +23 -0
  2. tests/conftest.py +59 -0
  3. tests/test_cli.py +131 -0
  4. tests/test_cuda.py +216 -0
  5. tests/test_engine.py +157 -0
  6. tests/test_exports.py +309 -0
  7. tests/test_integrations.py +151 -0
  8. tests/test_python.py +777 -0
  9. tests/test_solutions.py +371 -0
  10. ultralytics/__init__.py +48 -0
  11. ultralytics/assets/bus.jpg +0 -0
  12. ultralytics/assets/zidane.jpg +0 -0
  13. ultralytics/cfg/__init__.py +1026 -0
  14. ultralytics/cfg/datasets/Argoverse.yaml +78 -0
  15. ultralytics/cfg/datasets/DOTAv1.5.yaml +37 -0
  16. ultralytics/cfg/datasets/DOTAv1.yaml +36 -0
  17. ultralytics/cfg/datasets/GlobalWheat2020.yaml +68 -0
  18. ultralytics/cfg/datasets/HomeObjects-3K.yaml +32 -0
  19. ultralytics/cfg/datasets/ImageNet.yaml +2025 -0
  20. ultralytics/cfg/datasets/Objects365.yaml +447 -0
  21. ultralytics/cfg/datasets/SKU-110K.yaml +58 -0
  22. ultralytics/cfg/datasets/VOC.yaml +102 -0
  23. ultralytics/cfg/datasets/VisDrone.yaml +87 -0
  24. ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
  25. ultralytics/cfg/datasets/brain-tumor.yaml +22 -0
  26. ultralytics/cfg/datasets/carparts-seg.yaml +44 -0
  27. ultralytics/cfg/datasets/coco-pose.yaml +64 -0
  28. ultralytics/cfg/datasets/coco.yaml +118 -0
  29. ultralytics/cfg/datasets/coco128-seg.yaml +101 -0
  30. ultralytics/cfg/datasets/coco128.yaml +101 -0
  31. ultralytics/cfg/datasets/coco8-grayscale.yaml +103 -0
  32. ultralytics/cfg/datasets/coco8-multispectral.yaml +104 -0
  33. ultralytics/cfg/datasets/coco8-pose.yaml +47 -0
  34. ultralytics/cfg/datasets/coco8-seg.yaml +101 -0
  35. ultralytics/cfg/datasets/coco8.yaml +101 -0
  36. ultralytics/cfg/datasets/construction-ppe.yaml +32 -0
  37. ultralytics/cfg/datasets/crack-seg.yaml +22 -0
  38. ultralytics/cfg/datasets/dog-pose.yaml +52 -0
  39. ultralytics/cfg/datasets/dota8-multispectral.yaml +38 -0
  40. ultralytics/cfg/datasets/dota8.yaml +35 -0
  41. ultralytics/cfg/datasets/hand-keypoints.yaml +50 -0
  42. ultralytics/cfg/datasets/kitti.yaml +27 -0
  43. ultralytics/cfg/datasets/lvis.yaml +1240 -0
  44. ultralytics/cfg/datasets/medical-pills.yaml +21 -0
  45. ultralytics/cfg/datasets/open-images-v7.yaml +663 -0
  46. ultralytics/cfg/datasets/package-seg.yaml +22 -0
  47. ultralytics/cfg/datasets/signature.yaml +21 -0
  48. ultralytics/cfg/datasets/tiger-pose.yaml +41 -0
  49. ultralytics/cfg/datasets/xView.yaml +155 -0
  50. ultralytics/cfg/default.yaml +130 -0
  51. ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +17 -0
  52. ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
  53. ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
  54. ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
  55. ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
  56. ultralytics/cfg/models/11/yolo11.yaml +50 -0
  57. ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
  58. ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
  59. ultralytics/cfg/models/12/yolo12-cls.yaml +32 -0
  60. ultralytics/cfg/models/12/yolo12-obb.yaml +48 -0
  61. ultralytics/cfg/models/12/yolo12-pose.yaml +49 -0
  62. ultralytics/cfg/models/12/yolo12-seg.yaml +48 -0
  63. ultralytics/cfg/models/12/yolo12.yaml +48 -0
  64. ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +53 -0
  65. ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +45 -0
  66. ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +45 -0
  67. ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +57 -0
  68. ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
  69. ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
  70. ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
  71. ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
  72. ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
  73. ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
  74. ultralytics/cfg/models/v3/yolov3-spp.yaml +49 -0
  75. ultralytics/cfg/models/v3/yolov3-tiny.yaml +40 -0
  76. ultralytics/cfg/models/v3/yolov3.yaml +49 -0
  77. ultralytics/cfg/models/v5/yolov5-p6.yaml +62 -0
  78. ultralytics/cfg/models/v5/yolov5.yaml +51 -0
  79. ultralytics/cfg/models/v6/yolov6.yaml +56 -0
  80. ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +48 -0
  81. ultralytics/cfg/models/v8/yoloe-v8.yaml +48 -0
  82. ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +28 -0
  83. ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +28 -0
  84. ultralytics/cfg/models/v8/yolov8-cls.yaml +32 -0
  85. ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +58 -0
  86. ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +60 -0
  87. ultralytics/cfg/models/v8/yolov8-ghost.yaml +50 -0
  88. ultralytics/cfg/models/v8/yolov8-obb.yaml +49 -0
  89. ultralytics/cfg/models/v8/yolov8-p2.yaml +57 -0
  90. ultralytics/cfg/models/v8/yolov8-p6.yaml +59 -0
  91. ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +60 -0
  92. ultralytics/cfg/models/v8/yolov8-pose.yaml +50 -0
  93. ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +49 -0
  94. ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +59 -0
  95. ultralytics/cfg/models/v8/yolov8-seg.yaml +49 -0
  96. ultralytics/cfg/models/v8/yolov8-world.yaml +51 -0
  97. ultralytics/cfg/models/v8/yolov8-worldv2.yaml +49 -0
  98. ultralytics/cfg/models/v8/yolov8.yaml +49 -0
  99. ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
  100. ultralytics/cfg/models/v9/yolov9c.yaml +41 -0
  101. ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
  102. ultralytics/cfg/models/v9/yolov9e.yaml +64 -0
  103. ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
  104. ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
  105. ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
  106. ultralytics/cfg/trackers/botsort.yaml +21 -0
  107. ultralytics/cfg/trackers/bytetrack.yaml +12 -0
  108. ultralytics/data/__init__.py +26 -0
  109. ultralytics/data/annotator.py +66 -0
  110. ultralytics/data/augment.py +2801 -0
  111. ultralytics/data/base.py +435 -0
  112. ultralytics/data/build.py +437 -0
  113. ultralytics/data/converter.py +855 -0
  114. ultralytics/data/dataset.py +834 -0
  115. ultralytics/data/loaders.py +704 -0
  116. ultralytics/data/scripts/download_weights.sh +18 -0
  117. ultralytics/data/scripts/get_coco.sh +61 -0
  118. ultralytics/data/scripts/get_coco128.sh +18 -0
  119. ultralytics/data/scripts/get_imagenet.sh +52 -0
  120. ultralytics/data/split.py +138 -0
  121. ultralytics/data/split_dota.py +344 -0
  122. ultralytics/data/utils.py +798 -0
  123. ultralytics/engine/__init__.py +1 -0
  124. ultralytics/engine/exporter.py +1574 -0
  125. ultralytics/engine/model.py +1124 -0
  126. ultralytics/engine/predictor.py +508 -0
  127. ultralytics/engine/results.py +1522 -0
  128. ultralytics/engine/trainer.py +974 -0
  129. ultralytics/engine/tuner.py +448 -0
  130. ultralytics/engine/validator.py +384 -0
  131. ultralytics/hub/__init__.py +166 -0
  132. ultralytics/hub/auth.py +151 -0
  133. ultralytics/hub/google/__init__.py +174 -0
  134. ultralytics/hub/session.py +422 -0
  135. ultralytics/hub/utils.py +162 -0
  136. ultralytics/models/__init__.py +9 -0
  137. ultralytics/models/fastsam/__init__.py +7 -0
  138. ultralytics/models/fastsam/model.py +79 -0
  139. ultralytics/models/fastsam/predict.py +169 -0
  140. ultralytics/models/fastsam/utils.py +23 -0
  141. ultralytics/models/fastsam/val.py +38 -0
  142. ultralytics/models/nas/__init__.py +7 -0
  143. ultralytics/models/nas/model.py +98 -0
  144. ultralytics/models/nas/predict.py +56 -0
  145. ultralytics/models/nas/val.py +38 -0
  146. ultralytics/models/rtdetr/__init__.py +7 -0
  147. ultralytics/models/rtdetr/model.py +63 -0
  148. ultralytics/models/rtdetr/predict.py +88 -0
  149. ultralytics/models/rtdetr/train.py +89 -0
  150. ultralytics/models/rtdetr/val.py +216 -0
  151. ultralytics/models/sam/__init__.py +25 -0
  152. ultralytics/models/sam/amg.py +275 -0
  153. ultralytics/models/sam/build.py +365 -0
  154. ultralytics/models/sam/build_sam3.py +377 -0
  155. ultralytics/models/sam/model.py +169 -0
  156. ultralytics/models/sam/modules/__init__.py +1 -0
  157. ultralytics/models/sam/modules/blocks.py +1067 -0
  158. ultralytics/models/sam/modules/decoders.py +495 -0
  159. ultralytics/models/sam/modules/encoders.py +794 -0
  160. ultralytics/models/sam/modules/memory_attention.py +298 -0
  161. ultralytics/models/sam/modules/sam.py +1160 -0
  162. ultralytics/models/sam/modules/tiny_encoder.py +979 -0
  163. ultralytics/models/sam/modules/transformer.py +344 -0
  164. ultralytics/models/sam/modules/utils.py +512 -0
  165. ultralytics/models/sam/predict.py +3940 -0
  166. ultralytics/models/sam/sam3/__init__.py +3 -0
  167. ultralytics/models/sam/sam3/decoder.py +546 -0
  168. ultralytics/models/sam/sam3/encoder.py +529 -0
  169. ultralytics/models/sam/sam3/geometry_encoders.py +415 -0
  170. ultralytics/models/sam/sam3/maskformer_segmentation.py +286 -0
  171. ultralytics/models/sam/sam3/model_misc.py +199 -0
  172. ultralytics/models/sam/sam3/necks.py +129 -0
  173. ultralytics/models/sam/sam3/sam3_image.py +339 -0
  174. ultralytics/models/sam/sam3/text_encoder_ve.py +307 -0
  175. ultralytics/models/sam/sam3/vitdet.py +547 -0
  176. ultralytics/models/sam/sam3/vl_combiner.py +160 -0
  177. ultralytics/models/utils/__init__.py +1 -0
  178. ultralytics/models/utils/loss.py +466 -0
  179. ultralytics/models/utils/ops.py +315 -0
  180. ultralytics/models/yolo/__init__.py +7 -0
  181. ultralytics/models/yolo/classify/__init__.py +7 -0
  182. ultralytics/models/yolo/classify/predict.py +90 -0
  183. ultralytics/models/yolo/classify/train.py +202 -0
  184. ultralytics/models/yolo/classify/val.py +216 -0
  185. ultralytics/models/yolo/detect/__init__.py +7 -0
  186. ultralytics/models/yolo/detect/predict.py +122 -0
  187. ultralytics/models/yolo/detect/train.py +227 -0
  188. ultralytics/models/yolo/detect/val.py +507 -0
  189. ultralytics/models/yolo/model.py +430 -0
  190. ultralytics/models/yolo/obb/__init__.py +7 -0
  191. ultralytics/models/yolo/obb/predict.py +56 -0
  192. ultralytics/models/yolo/obb/train.py +79 -0
  193. ultralytics/models/yolo/obb/val.py +302 -0
  194. ultralytics/models/yolo/pose/__init__.py +7 -0
  195. ultralytics/models/yolo/pose/predict.py +65 -0
  196. ultralytics/models/yolo/pose/train.py +110 -0
  197. ultralytics/models/yolo/pose/val.py +248 -0
  198. ultralytics/models/yolo/segment/__init__.py +7 -0
  199. ultralytics/models/yolo/segment/predict.py +109 -0
  200. ultralytics/models/yolo/segment/train.py +69 -0
  201. ultralytics/models/yolo/segment/val.py +307 -0
  202. ultralytics/models/yolo/world/__init__.py +5 -0
  203. ultralytics/models/yolo/world/train.py +173 -0
  204. ultralytics/models/yolo/world/train_world.py +178 -0
  205. ultralytics/models/yolo/yoloe/__init__.py +22 -0
  206. ultralytics/models/yolo/yoloe/predict.py +162 -0
  207. ultralytics/models/yolo/yoloe/train.py +287 -0
  208. ultralytics/models/yolo/yoloe/train_seg.py +122 -0
  209. ultralytics/models/yolo/yoloe/val.py +206 -0
  210. ultralytics/nn/__init__.py +27 -0
  211. ultralytics/nn/autobackend.py +958 -0
  212. ultralytics/nn/modules/__init__.py +182 -0
  213. ultralytics/nn/modules/activation.py +54 -0
  214. ultralytics/nn/modules/block.py +1947 -0
  215. ultralytics/nn/modules/conv.py +669 -0
  216. ultralytics/nn/modules/head.py +1183 -0
  217. ultralytics/nn/modules/transformer.py +793 -0
  218. ultralytics/nn/modules/utils.py +159 -0
  219. ultralytics/nn/tasks.py +1768 -0
  220. ultralytics/nn/text_model.py +356 -0
  221. ultralytics/py.typed +1 -0
  222. ultralytics/solutions/__init__.py +41 -0
  223. ultralytics/solutions/ai_gym.py +108 -0
  224. ultralytics/solutions/analytics.py +264 -0
  225. ultralytics/solutions/config.py +107 -0
  226. ultralytics/solutions/distance_calculation.py +123 -0
  227. ultralytics/solutions/heatmap.py +125 -0
  228. ultralytics/solutions/instance_segmentation.py +86 -0
  229. ultralytics/solutions/object_blurrer.py +89 -0
  230. ultralytics/solutions/object_counter.py +190 -0
  231. ultralytics/solutions/object_cropper.py +87 -0
  232. ultralytics/solutions/parking_management.py +280 -0
  233. ultralytics/solutions/queue_management.py +93 -0
  234. ultralytics/solutions/region_counter.py +133 -0
  235. ultralytics/solutions/security_alarm.py +151 -0
  236. ultralytics/solutions/similarity_search.py +219 -0
  237. ultralytics/solutions/solutions.py +828 -0
  238. ultralytics/solutions/speed_estimation.py +114 -0
  239. ultralytics/solutions/streamlit_inference.py +260 -0
  240. ultralytics/solutions/templates/similarity-search.html +156 -0
  241. ultralytics/solutions/trackzone.py +88 -0
  242. ultralytics/solutions/vision_eye.py +67 -0
  243. ultralytics/trackers/__init__.py +7 -0
  244. ultralytics/trackers/basetrack.py +115 -0
  245. ultralytics/trackers/bot_sort.py +257 -0
  246. ultralytics/trackers/byte_tracker.py +469 -0
  247. ultralytics/trackers/track.py +116 -0
  248. ultralytics/trackers/utils/__init__.py +1 -0
  249. ultralytics/trackers/utils/gmc.py +339 -0
  250. ultralytics/trackers/utils/kalman_filter.py +482 -0
  251. ultralytics/trackers/utils/matching.py +154 -0
  252. ultralytics/utils/__init__.py +1450 -0
  253. ultralytics/utils/autobatch.py +118 -0
  254. ultralytics/utils/autodevice.py +205 -0
  255. ultralytics/utils/benchmarks.py +728 -0
  256. ultralytics/utils/callbacks/__init__.py +5 -0
  257. ultralytics/utils/callbacks/base.py +233 -0
  258. ultralytics/utils/callbacks/clearml.py +146 -0
  259. ultralytics/utils/callbacks/comet.py +625 -0
  260. ultralytics/utils/callbacks/dvc.py +197 -0
  261. ultralytics/utils/callbacks/hub.py +110 -0
  262. ultralytics/utils/callbacks/mlflow.py +134 -0
  263. ultralytics/utils/callbacks/neptune.py +126 -0
  264. ultralytics/utils/callbacks/platform.py +73 -0
  265. ultralytics/utils/callbacks/raytune.py +42 -0
  266. ultralytics/utils/callbacks/tensorboard.py +123 -0
  267. ultralytics/utils/callbacks/wb.py +188 -0
  268. ultralytics/utils/checks.py +998 -0
  269. ultralytics/utils/cpu.py +85 -0
  270. ultralytics/utils/dist.py +123 -0
  271. ultralytics/utils/downloads.py +529 -0
  272. ultralytics/utils/errors.py +35 -0
  273. ultralytics/utils/events.py +113 -0
  274. ultralytics/utils/export/__init__.py +7 -0
  275. ultralytics/utils/export/engine.py +237 -0
  276. ultralytics/utils/export/imx.py +315 -0
  277. ultralytics/utils/export/tensorflow.py +231 -0
  278. ultralytics/utils/files.py +219 -0
  279. ultralytics/utils/git.py +137 -0
  280. ultralytics/utils/instance.py +484 -0
  281. ultralytics/utils/logger.py +444 -0
  282. ultralytics/utils/loss.py +849 -0
  283. ultralytics/utils/metrics.py +1560 -0
  284. ultralytics/utils/nms.py +337 -0
  285. ultralytics/utils/ops.py +664 -0
  286. ultralytics/utils/patches.py +201 -0
  287. ultralytics/utils/plotting.py +1045 -0
  288. ultralytics/utils/tal.py +403 -0
  289. ultralytics/utils/torch_utils.py +984 -0
  290. ultralytics/utils/tqdm.py +440 -0
  291. ultralytics/utils/triton.py +112 -0
  292. ultralytics/utils/tuner.py +160 -0
  293. ultralytics_opencv_headless-8.3.242.dist-info/METADATA +374 -0
  294. ultralytics_opencv_headless-8.3.242.dist-info/RECORD +298 -0
  295. ultralytics_opencv_headless-8.3.242.dist-info/WHEEL +5 -0
  296. ultralytics_opencv_headless-8.3.242.dist-info/entry_points.txt +3 -0
  297. ultralytics_opencv_headless-8.3.242.dist-info/licenses/LICENSE +661 -0
  298. ultralytics_opencv_headless-8.3.242.dist-info/top_level.txt +1 -0
@@ -0,0 +1,237 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+
8
+ import torch
9
+
10
+ from ultralytics.utils import IS_JETSON, LOGGER
11
+ from ultralytics.utils.torch_utils import TORCH_2_4
12
+
13
+
14
+ def torch2onnx(
15
+ torch_model: torch.nn.Module,
16
+ im: torch.Tensor,
17
+ onnx_file: str,
18
+ opset: int = 14,
19
+ input_names: list[str] = ["images"],
20
+ output_names: list[str] = ["output0"],
21
+ dynamic: bool | dict = False,
22
+ ) -> None:
23
+ """Export a PyTorch model to ONNX format.
24
+
25
+ Args:
26
+ torch_model (torch.nn.Module): The PyTorch model to export.
27
+ im (torch.Tensor): Example input tensor for the model.
28
+ onnx_file (str): Path to save the exported ONNX file.
29
+ opset (int): ONNX opset version to use for export.
30
+ input_names (list[str]): List of input tensor names.
31
+ output_names (list[str]): List of output tensor names.
32
+ dynamic (bool | dict, optional): Whether to enable dynamic axes.
33
+
34
+ Notes:
35
+ Setting `do_constant_folding=True` may cause issues with DNN inference for torch>=1.12.
36
+ """
37
+ kwargs = {"dynamo": False} if TORCH_2_4 else {}
38
+ torch.onnx.export(
39
+ torch_model,
40
+ im,
41
+ onnx_file,
42
+ verbose=False,
43
+ opset_version=opset,
44
+ do_constant_folding=True, # WARNING: DNN inference with torch>=1.12 may require do_constant_folding=False
45
+ input_names=input_names,
46
+ output_names=output_names,
47
+ dynamic_axes=dynamic or None,
48
+ **kwargs,
49
+ )
50
+
51
+
52
+ def onnx2engine(
53
+ onnx_file: str,
54
+ engine_file: str | None = None,
55
+ workspace: int | None = None,
56
+ half: bool = False,
57
+ int8: bool = False,
58
+ dynamic: bool = False,
59
+ shape: tuple[int, int, int, int] = (1, 3, 640, 640),
60
+ dla: int | None = None,
61
+ dataset=None,
62
+ metadata: dict | None = None,
63
+ verbose: bool = False,
64
+ prefix: str = "",
65
+ ) -> None:
66
+ """Export a YOLO model to TensorRT engine format.
67
+
68
+ Args:
69
+ onnx_file (str): Path to the ONNX file to be converted.
70
+ engine_file (str, optional): Path to save the generated TensorRT engine file.
71
+ workspace (int, optional): Workspace size in GB for TensorRT.
72
+ half (bool, optional): Enable FP16 precision.
73
+ int8 (bool, optional): Enable INT8 precision.
74
+ dynamic (bool, optional): Enable dynamic input shapes.
75
+ shape (tuple[int, int, int, int], optional): Input shape (batch, channels, height, width).
76
+ dla (int, optional): DLA core to use (Jetson devices only).
77
+ dataset (ultralytics.data.build.InfiniteDataLoader, optional): Dataset for INT8 calibration.
78
+ metadata (dict, optional): Metadata to include in the engine file.
79
+ verbose (bool, optional): Enable verbose logging.
80
+ prefix (str, optional): Prefix for log messages.
81
+
82
+ Raises:
83
+ ValueError: If DLA is enabled on non-Jetson devices or required precision is not set.
84
+ RuntimeError: If the ONNX file cannot be parsed.
85
+
86
+ Notes:
87
+ TensorRT version compatibility is handled for workspace size and engine building.
88
+ INT8 calibration requires a dataset and generates a calibration cache.
89
+ Metadata is serialized and written to the engine file if provided.
90
+ """
91
+ import tensorrt as trt
92
+
93
+ engine_file = engine_file or Path(onnx_file).with_suffix(".engine")
94
+
95
+ logger = trt.Logger(trt.Logger.INFO)
96
+ if verbose:
97
+ logger.min_severity = trt.Logger.Severity.VERBOSE
98
+
99
+ # Engine builder
100
+ builder = trt.Builder(logger)
101
+ config = builder.create_builder_config()
102
+ workspace_bytes = int((workspace or 0) * (1 << 30))
103
+ is_trt10 = int(trt.__version__.split(".", 1)[0]) >= 10 # is TensorRT >= 10
104
+ if is_trt10 and workspace_bytes > 0:
105
+ config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace_bytes)
106
+ elif workspace_bytes > 0: # TensorRT versions 7, 8
107
+ config.max_workspace_size = workspace_bytes
108
+ flag = 1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
109
+ network = builder.create_network(flag)
110
+ half = builder.platform_has_fast_fp16 and half
111
+ int8 = builder.platform_has_fast_int8 and int8
112
+
113
+ # Optionally switch to DLA if enabled
114
+ if dla is not None:
115
+ if not IS_JETSON:
116
+ raise ValueError("DLA is only available on NVIDIA Jetson devices")
117
+ LOGGER.info(f"{prefix} enabling DLA on core {dla}...")
118
+ if not half and not int8:
119
+ raise ValueError(
120
+ "DLA requires either 'half=True' (FP16) or 'int8=True' (INT8) to be enabled. Please enable one of them and try again."
121
+ )
122
+ config.default_device_type = trt.DeviceType.DLA
123
+ config.DLA_core = int(dla)
124
+ config.set_flag(trt.BuilderFlag.GPU_FALLBACK)
125
+
126
+ # Read ONNX file
127
+ parser = trt.OnnxParser(network, logger)
128
+ if not parser.parse_from_file(onnx_file):
129
+ raise RuntimeError(f"failed to load ONNX file: {onnx_file}")
130
+
131
+ # Network inputs
132
+ inputs = [network.get_input(i) for i in range(network.num_inputs)]
133
+ outputs = [network.get_output(i) for i in range(network.num_outputs)]
134
+ for inp in inputs:
135
+ LOGGER.info(f'{prefix} input "{inp.name}" with shape{inp.shape} {inp.dtype}')
136
+ for out in outputs:
137
+ LOGGER.info(f'{prefix} output "{out.name}" with shape{out.shape} {out.dtype}')
138
+
139
+ if dynamic:
140
+ profile = builder.create_optimization_profile()
141
+ min_shape = (1, shape[1], 32, 32) # minimum input shape
142
+ max_shape = (*shape[:2], *(int(max(2, workspace or 2) * d) for d in shape[2:])) # max input shape
143
+ for inp in inputs:
144
+ profile.set_shape(inp.name, min=min_shape, opt=shape, max=max_shape)
145
+ config.add_optimization_profile(profile)
146
+ if int8:
147
+ config.set_calibration_profile(profile)
148
+
149
+ LOGGER.info(f"{prefix} building {'INT8' if int8 else 'FP' + ('16' if half else '32')} engine as {engine_file}")
150
+ if int8:
151
+ config.set_flag(trt.BuilderFlag.INT8)
152
+ config.profiling_verbosity = trt.ProfilingVerbosity.DETAILED
153
+
154
+ class EngineCalibrator(trt.IInt8Calibrator):
155
+ """Custom INT8 calibrator for TensorRT engine optimization.
156
+
157
+ This calibrator provides the necessary interface for TensorRT to perform INT8 quantization calibration using
158
+ a dataset. It handles batch generation, caching, and calibration algorithm selection.
159
+
160
+ Attributes:
161
+ dataset: Dataset for calibration.
162
+ data_iter: Iterator over the calibration dataset.
163
+ algo (trt.CalibrationAlgoType): Calibration algorithm type.
164
+ batch (int): Batch size for calibration.
165
+ cache (Path): Path to save the calibration cache.
166
+
167
+ Methods:
168
+ get_algorithm: Get the calibration algorithm to use.
169
+ get_batch_size: Get the batch size to use for calibration.
170
+ get_batch: Get the next batch to use for calibration.
171
+ read_calibration_cache: Use existing cache instead of calibrating again.
172
+ write_calibration_cache: Write calibration cache to disk.
173
+ """
174
+
175
+ def __init__(
176
+ self,
177
+ dataset, # ultralytics.data.build.InfiniteDataLoader
178
+ cache: str = "",
179
+ ) -> None:
180
+ """Initialize the INT8 calibrator with dataset and cache path."""
181
+ trt.IInt8Calibrator.__init__(self)
182
+ self.dataset = dataset
183
+ self.data_iter = iter(dataset)
184
+ self.algo = (
185
+ trt.CalibrationAlgoType.ENTROPY_CALIBRATION_2 # DLA quantization needs ENTROPY_CALIBRATION_2
186
+ if dla is not None
187
+ else trt.CalibrationAlgoType.MINMAX_CALIBRATION
188
+ )
189
+ self.batch = dataset.batch_size
190
+ self.cache = Path(cache)
191
+
192
+ def get_algorithm(self) -> trt.CalibrationAlgoType:
193
+ """Get the calibration algorithm to use."""
194
+ return self.algo
195
+
196
+ def get_batch_size(self) -> int:
197
+ """Get the batch size to use for calibration."""
198
+ return self.batch or 1
199
+
200
+ def get_batch(self, names) -> list[int] | None:
201
+ """Get the next batch to use for calibration, as a list of device memory pointers."""
202
+ try:
203
+ im0s = next(self.data_iter)["img"] / 255.0
204
+ im0s = im0s.to("cuda") if im0s.device.type == "cpu" else im0s
205
+ return [int(im0s.data_ptr())]
206
+ except StopIteration:
207
+ # Return None to signal to TensorRT there is no calibration data remaining
208
+ return None
209
+
210
+ def read_calibration_cache(self) -> bytes | None:
211
+ """Use existing cache instead of calibrating again, otherwise, implicitly return None."""
212
+ if self.cache.exists() and self.cache.suffix == ".cache":
213
+ return self.cache.read_bytes()
214
+
215
+ def write_calibration_cache(self, cache: bytes) -> None:
216
+ """Write calibration cache to disk."""
217
+ _ = self.cache.write_bytes(cache)
218
+
219
+ # Load dataset w/ builder (for batching) and calibrate
220
+ config.int8_calibrator = EngineCalibrator(
221
+ dataset=dataset,
222
+ cache=str(Path(onnx_file).with_suffix(".cache")),
223
+ )
224
+
225
+ elif half:
226
+ config.set_flag(trt.BuilderFlag.FP16)
227
+
228
+ # Write file
229
+ build = builder.build_serialized_network if is_trt10 else builder.build_engine
230
+ with build(network, config) as engine, open(engine_file, "wb") as t:
231
+ # Metadata
232
+ if metadata is not None:
233
+ meta = json.dumps(metadata)
234
+ t.write(len(meta).to_bytes(4, byteorder="little", signed=True))
235
+ t.write(meta.encode())
236
+ # Model
237
+ t.write(engine if is_trt10 else engine.serialize())
@@ -0,0 +1,315 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ from __future__ import annotations
4
+
5
+ import subprocess
6
+ import types
7
+ from pathlib import Path
8
+
9
+ import numpy as np
10
+ import torch
11
+
12
+ from ultralytics.nn.modules import Detect, Pose, Segment
13
+ from ultralytics.utils import LOGGER
14
+ from ultralytics.utils.patches import onnx_export_patch
15
+ from ultralytics.utils.tal import make_anchors
16
+ from ultralytics.utils.torch_utils import copy_attr
17
+
18
+ # Configuration for Model Compression Toolkit (MCT) quantization
19
+ MCT_CONFIG = {
20
+ "YOLO11": {
21
+ "detect": {
22
+ "layer_names": ["sub", "mul_2", "add_14", "cat_21"],
23
+ "weights_memory": 2585350.2439,
24
+ "n_layers": 238,
25
+ },
26
+ "pose": {
27
+ "layer_names": ["sub", "mul_2", "add_14", "cat_22", "cat_23", "mul_4", "add_15"],
28
+ "weights_memory": 2437771.67,
29
+ "n_layers": 257,
30
+ },
31
+ "classify": {"layer_names": [], "weights_memory": np.inf, "n_layers": 112},
32
+ "segment": {"layer_names": ["sub", "mul_2", "add_14", "cat_22"], "weights_memory": 2466604.8, "n_layers": 265},
33
+ },
34
+ "YOLOv8": {
35
+ "detect": {"layer_names": ["sub", "mul", "add_6", "cat_17"], "weights_memory": 2550540.8, "n_layers": 168},
36
+ "pose": {
37
+ "layer_names": ["add_7", "mul_2", "cat_19", "mul", "sub", "add_6", "cat_18"],
38
+ "weights_memory": 2482451.85,
39
+ "n_layers": 187,
40
+ },
41
+ "classify": {"layer_names": [], "weights_memory": np.inf, "n_layers": 73},
42
+ "segment": {"layer_names": ["sub", "mul", "add_6", "cat_18"], "weights_memory": 2580060.0, "n_layers": 195},
43
+ },
44
+ }
45
+
46
+
47
+ class FXModel(torch.nn.Module):
48
+ """A custom model class for torch.fx compatibility.
49
+
50
+ This class extends `torch.nn.Module` and is designed to ensure compatibility with torch.fx for tracing and graph
51
+ manipulation. It copies attributes from an existing model and explicitly sets the model attribute to ensure proper
52
+ copying.
53
+
54
+ Attributes:
55
+ model (nn.Module): The original model's layers.
56
+ """
57
+
58
+ def __init__(self, model, imgsz=(640, 640)):
59
+ """Initialize the FXModel.
60
+
61
+ Args:
62
+ model (nn.Module): The original model to wrap for torch.fx compatibility.
63
+ imgsz (tuple[int, int]): The input image size (height, width). Default is (640, 640).
64
+ """
65
+ super().__init__()
66
+ copy_attr(self, model)
67
+ # Explicitly set `model` since `copy_attr` somehow does not copy it.
68
+ self.model = model.model
69
+ self.imgsz = imgsz
70
+
71
+ def forward(self, x):
72
+ """Forward pass through the model.
73
+
74
+ This method performs the forward pass through the model, handling the dependencies between layers and saving
75
+ intermediate outputs.
76
+
77
+ Args:
78
+ x (torch.Tensor): The input tensor to the model.
79
+
80
+ Returns:
81
+ (torch.Tensor): The output tensor from the model.
82
+ """
83
+ y = [] # outputs
84
+ for m in self.model:
85
+ if m.f != -1: # if not from previous layer
86
+ # from earlier layers
87
+ x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f]
88
+ if isinstance(m, Detect):
89
+ m._inference = types.MethodType(_inference, m) # bind method to Detect
90
+ m.anchors, m.strides = (
91
+ x.transpose(0, 1)
92
+ for x in make_anchors(
93
+ torch.cat([s / m.stride.unsqueeze(-1) for s in self.imgsz], dim=1), m.stride, 0.5
94
+ )
95
+ )
96
+ if type(m) is Pose:
97
+ m.forward = types.MethodType(pose_forward, m) # bind method to Detect
98
+ if type(m) is Segment:
99
+ m.forward = types.MethodType(segment_forward, m) # bind method to Detect
100
+ x = m(x) # run
101
+ y.append(x) # save output
102
+ return x
103
+
104
+
105
+ def _inference(self, x: list[torch.Tensor]) -> tuple[torch.Tensor]:
106
+ """Decode boxes and cls scores for imx object detection."""
107
+ x_cat = torch.cat([xi.view(x[0].shape[0], self.no, -1) for xi in x], 2)
108
+ box, cls = x_cat.split((self.reg_max * 4, self.nc), 1)
109
+ dbox = self.decode_bboxes(self.dfl(box), self.anchors.unsqueeze(0)) * self.strides
110
+ return dbox.transpose(1, 2), cls.sigmoid().permute(0, 2, 1)
111
+
112
+
113
+ def pose_forward(self, x: list[torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
114
+ """Forward pass for imx pose estimation, including keypoint decoding."""
115
+ bs = x[0].shape[0] # batch size
116
+ kpt = torch.cat([self.cv4[i](x[i]).view(bs, self.nk, -1) for i in range(self.nl)], -1) # (bs, 17*3, h*w)
117
+ x = Detect.forward(self, x)
118
+ pred_kpt = self.kpts_decode(bs, kpt)
119
+ return *x, pred_kpt.permute(0, 2, 1)
120
+
121
+
122
+ def segment_forward(self, x: list[torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
123
+ """Forward pass for imx segmentation."""
124
+ p = self.proto(x[0]) # mask protos
125
+ bs = p.shape[0] # batch size
126
+ mc = torch.cat([self.cv4[i](x[i]).view(bs, self.nm, -1) for i in range(self.nl)], 2) # mask coefficients
127
+ x = Detect.forward(self, x)
128
+ return *x, mc.transpose(1, 2), p
129
+
130
+
131
+ class NMSWrapper(torch.nn.Module):
132
+ """Wrap PyTorch Module with multiclass_nms layer from edge-mdt-cl."""
133
+
134
+ def __init__(
135
+ self,
136
+ model: torch.nn.Module,
137
+ score_threshold: float = 0.001,
138
+ iou_threshold: float = 0.7,
139
+ max_detections: int = 300,
140
+ task: str = "detect",
141
+ ):
142
+ """Initialize NMSWrapper with PyTorch Module and NMS parameters.
143
+
144
+ Args:
145
+ model (torch.nn.Module): Model instance.
146
+ score_threshold (float): Score threshold for non-maximum suppression.
147
+ iou_threshold (float): Intersection over union threshold for non-maximum suppression.
148
+ max_detections (int): The number of detections to return.
149
+ task (str): Task type, either 'detect' or 'pose'.
150
+ """
151
+ super().__init__()
152
+ self.model = model
153
+ self.score_threshold = score_threshold
154
+ self.iou_threshold = iou_threshold
155
+ self.max_detections = max_detections
156
+ self.task = task
157
+
158
+ def forward(self, images):
159
+ """Forward pass with model inference and NMS post-processing."""
160
+ from edgemdt_cl.pytorch.nms.nms_with_indices import multiclass_nms_with_indices
161
+
162
+ # model inference
163
+ outputs = self.model(images)
164
+ boxes, scores = outputs[0], outputs[1]
165
+ nms_outputs = multiclass_nms_with_indices(
166
+ boxes=boxes,
167
+ scores=scores,
168
+ score_threshold=self.score_threshold,
169
+ iou_threshold=self.iou_threshold,
170
+ max_detections=self.max_detections,
171
+ )
172
+ if self.task == "pose":
173
+ kpts = outputs[2] # (bs, max_detections, kpts 17*3)
174
+ out_kpts = torch.gather(kpts, 1, nms_outputs.indices.unsqueeze(-1).expand(-1, -1, kpts.size(-1)))
175
+ return nms_outputs.boxes, nms_outputs.scores, nms_outputs.labels, out_kpts
176
+ if self.task == "segment":
177
+ mc, proto = outputs[2], outputs[3]
178
+ out_mc = torch.gather(mc, 1, nms_outputs.indices.unsqueeze(-1).expand(-1, -1, mc.size(-1)))
179
+ return nms_outputs.boxes, nms_outputs.scores, nms_outputs.labels, out_mc, proto
180
+ return nms_outputs.boxes, nms_outputs.scores, nms_outputs.labels, nms_outputs.n_valid
181
+
182
+
183
+ def torch2imx(
184
+ model: torch.nn.Module,
185
+ file: Path | str,
186
+ conf: float,
187
+ iou: float,
188
+ max_det: int,
189
+ metadata: dict | None = None,
190
+ gptq: bool = False,
191
+ dataset=None,
192
+ prefix: str = "",
193
+ ):
194
+ """Export YOLO model to IMX format for deployment on Sony IMX500 devices.
195
+
196
+ This function quantizes a YOLO model using Model Compression Toolkit (MCT) and exports it to IMX format compatible
197
+ with Sony IMX500 edge devices. It supports both YOLOv8n and YOLO11n models for detection and pose estimation tasks.
198
+
199
+ Args:
200
+ model (torch.nn.Module): The YOLO model to export. Must be YOLOv8n or YOLO11n.
201
+ file (Path | str): Output file path for the exported model.
202
+ conf (float): Confidence threshold for NMS post-processing.
203
+ iou (float): IoU threshold for NMS post-processing.
204
+ max_det (int): Maximum number of detections to return.
205
+ metadata (dict | None, optional): Metadata to embed in the ONNX model. Defaults to None.
206
+ gptq (bool, optional): Whether to use Gradient-Based Post Training Quantization. If False, uses standard Post
207
+ Training Quantization. Defaults to False.
208
+ dataset (optional): Representative dataset for quantization calibration. Defaults to None.
209
+ prefix (str, optional): Logging prefix string. Defaults to "".
210
+
211
+ Returns:
212
+ f (Path): Path to the exported IMX model directory
213
+
214
+ Raises:
215
+ ValueError: If the model is not a supported YOLOv8n or YOLO11n variant.
216
+
217
+ Examples:
218
+ >>> from ultralytics import YOLO
219
+ >>> model = YOLO("yolo11n.pt")
220
+ >>> path, _ = export_imx(model, "model.imx", conf=0.25, iou=0.45, max_det=300)
221
+
222
+ Notes:
223
+ - Requires model_compression_toolkit, onnx, edgemdt_tpc, and edge-mdt-cl packages
224
+ - Only supports YOLOv8n and YOLO11n models (detection and pose tasks)
225
+ - Output includes quantized ONNX model, IMX binary, and labels.txt file
226
+ """
227
+ import model_compression_toolkit as mct
228
+ import onnx
229
+ from edgemdt_tpc import get_target_platform_capabilities
230
+
231
+ LOGGER.info(f"\n{prefix} starting export with model_compression_toolkit {mct.__version__}...")
232
+
233
+ def representative_dataset_gen(dataloader=dataset):
234
+ for batch in dataloader:
235
+ img = batch["img"]
236
+ img = img / 255.0
237
+ yield [img]
238
+
239
+ # NOTE: need tpc_version to be "4.0" for IMX500 Pose estimation models
240
+ tpc = get_target_platform_capabilities(tpc_version="4.0", device_type="imx500")
241
+
242
+ bit_cfg = mct.core.BitWidthConfig()
243
+ mct_config = MCT_CONFIG["YOLO11" if "C2PSA" in model.__str__() else "YOLOv8"][model.task]
244
+
245
+ # Check if the model has the expected number of layers
246
+ if len(list(model.modules())) != mct_config["n_layers"]:
247
+ raise ValueError("IMX export only supported for YOLOv8n and YOLO11n models.")
248
+
249
+ for layer_name in mct_config["layer_names"]:
250
+ bit_cfg.set_manual_activation_bit_width([mct.core.common.network_editors.NodeNameFilter(layer_name)], 16)
251
+
252
+ config = mct.core.CoreConfig(
253
+ mixed_precision_config=mct.core.MixedPrecisionQuantizationConfig(num_of_images=10),
254
+ quantization_config=mct.core.QuantizationConfig(concat_threshold_update=True),
255
+ bit_width_config=bit_cfg,
256
+ )
257
+
258
+ resource_utilization = mct.core.ResourceUtilization(weights_memory=mct_config["weights_memory"])
259
+
260
+ quant_model = (
261
+ mct.gptq.pytorch_gradient_post_training_quantization( # Perform Gradient-Based Post Training Quantization
262
+ model=model,
263
+ representative_data_gen=representative_dataset_gen,
264
+ target_resource_utilization=resource_utilization,
265
+ gptq_config=mct.gptq.get_pytorch_gptq_config(
266
+ n_epochs=1000, use_hessian_based_weights=False, use_hessian_sample_attention=False
267
+ ),
268
+ core_config=config,
269
+ target_platform_capabilities=tpc,
270
+ )[0]
271
+ if gptq
272
+ else mct.ptq.pytorch_post_training_quantization( # Perform post training quantization
273
+ in_module=model,
274
+ representative_data_gen=representative_dataset_gen,
275
+ target_resource_utilization=resource_utilization,
276
+ core_config=config,
277
+ target_platform_capabilities=tpc,
278
+ )[0]
279
+ )
280
+
281
+ if model.task != "classify":
282
+ quant_model = NMSWrapper(
283
+ model=quant_model,
284
+ score_threshold=conf or 0.001,
285
+ iou_threshold=iou,
286
+ max_detections=max_det,
287
+ task=model.task,
288
+ )
289
+
290
+ f = Path(str(file).replace(file.suffix, "_imx_model"))
291
+ f.mkdir(exist_ok=True)
292
+ onnx_model = f / Path(str(file.name).replace(file.suffix, "_imx.onnx")) # js dir
293
+
294
+ with onnx_export_patch():
295
+ mct.exporter.pytorch_export_model(
296
+ model=quant_model, save_model_path=onnx_model, repr_dataset=representative_dataset_gen
297
+ )
298
+
299
+ model_onnx = onnx.load(onnx_model) # load onnx model
300
+ for k, v in metadata.items():
301
+ meta = model_onnx.metadata_props.add()
302
+ meta.key, meta.value = k, str(v)
303
+
304
+ onnx.save(model_onnx, onnx_model)
305
+
306
+ subprocess.run(
307
+ ["imxconv-pt", "-i", str(onnx_model), "-o", str(f), "--no-input-persistency", "--overwrite-output"],
308
+ check=True,
309
+ )
310
+
311
+ # Needed for imx models.
312
+ with open(f / "labels.txt", "w", encoding="utf-8") as file:
313
+ file.writelines([f"{name}\n" for _, name in model.names.items()])
314
+
315
+ return f