ultralytics-opencv-headless 8.3.246__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 +1578 -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 +313 -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 +1006 -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 +501 -0
  282. ultralytics/utils/loss.py +849 -0
  283. ultralytics/utils/metrics.py +1563 -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.246.dist-info/METADATA +374 -0
  294. ultralytics_opencv_headless-8.3.246.dist-info/RECORD +298 -0
  295. ultralytics_opencv_headless-8.3.246.dist-info/WHEEL +5 -0
  296. ultralytics_opencv_headless-8.3.246.dist-info/entry_points.txt +3 -0
  297. ultralytics_opencv_headless-8.3.246.dist-info/licenses/LICENSE +661 -0
  298. ultralytics_opencv_headless-8.3.246.dist-info/top_level.txt +1 -0
@@ -0,0 +1,728 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+ """
3
+ Benchmark YOLO model formats for speed and accuracy.
4
+
5
+ Usage:
6
+ from ultralytics.utils.benchmarks import ProfileModels, benchmark
7
+ ProfileModels(['yolo11n.yaml', 'yolov8s.yaml']).run()
8
+ benchmark(model='yolo11n.pt', imgsz=160)
9
+
10
+ Format | `format=argument` | Model
11
+ --- | --- | ---
12
+ PyTorch | - | yolo11n.pt
13
+ TorchScript | `torchscript` | yolo11n.torchscript
14
+ ONNX | `onnx` | yolo11n.onnx
15
+ OpenVINO | `openvino` | yolo11n_openvino_model/
16
+ TensorRT | `engine` | yolo11n.engine
17
+ CoreML | `coreml` | yolo11n.mlpackage
18
+ TensorFlow SavedModel | `saved_model` | yolo11n_saved_model/
19
+ TensorFlow GraphDef | `pb` | yolo11n.pb
20
+ TensorFlow Lite | `tflite` | yolo11n.tflite
21
+ TensorFlow Edge TPU | `edgetpu` | yolo11n_edgetpu.tflite
22
+ TensorFlow.js | `tfjs` | yolo11n_web_model/
23
+ PaddlePaddle | `paddle` | yolo11n_paddle_model/
24
+ MNN | `mnn` | yolo11n.mnn
25
+ NCNN | `ncnn` | yolo11n_ncnn_model/
26
+ IMX | `imx` | yolo11n_imx_model/
27
+ RKNN | `rknn` | yolo11n_rknn_model/
28
+ ExecuTorch | `executorch` | yolo11n_executorch_model/
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import glob
34
+ import os
35
+ import platform
36
+ import re
37
+ import shutil
38
+ import time
39
+ from pathlib import Path
40
+
41
+ import numpy as np
42
+ import torch.cuda
43
+
44
+ from ultralytics import YOLO, YOLOWorld
45
+ from ultralytics.cfg import TASK2DATA, TASK2METRIC
46
+ from ultralytics.engine.exporter import export_formats
47
+ from ultralytics.utils import ARM64, ASSETS, ASSETS_URL, IS_JETSON, LINUX, LOGGER, MACOS, TQDM, WEIGHTS_DIR, YAML
48
+ from ultralytics.utils.checks import IS_PYTHON_3_13, check_imgsz, check_requirements, check_yolo, is_rockchip
49
+ from ultralytics.utils.downloads import safe_download
50
+ from ultralytics.utils.files import file_size
51
+ from ultralytics.utils.torch_utils import get_cpu_info, select_device
52
+
53
+
54
+ def benchmark(
55
+ model=WEIGHTS_DIR / "yolo11n.pt",
56
+ data=None,
57
+ imgsz=160,
58
+ half=False,
59
+ int8=False,
60
+ device="cpu",
61
+ verbose=False,
62
+ eps=1e-3,
63
+ format="",
64
+ **kwargs,
65
+ ):
66
+ """Benchmark a YOLO model across different formats for speed and accuracy.
67
+
68
+ Args:
69
+ model (str | Path): Path to the model file or directory.
70
+ data (str | None): Dataset to evaluate on, inherited from TASK2DATA if not passed.
71
+ imgsz (int): Image size for the benchmark.
72
+ half (bool): Use half-precision for the model if True.
73
+ int8 (bool): Use int8-precision for the model if True.
74
+ device (str): Device to run the benchmark on, either 'cpu' or 'cuda'.
75
+ verbose (bool | float): If True or a float, assert benchmarks pass with given metric.
76
+ eps (float): Epsilon value for divide by zero prevention.
77
+ format (str): Export format for benchmarking. If not supplied all formats are benchmarked.
78
+ **kwargs (Any): Additional keyword arguments for exporter.
79
+
80
+ Returns:
81
+ (polars.DataFrame): A Polars DataFrame with benchmark results for each format, including file size, metric, and
82
+ inference time.
83
+
84
+ Examples:
85
+ Benchmark a YOLO model with default settings:
86
+ >>> from ultralytics.utils.benchmarks import benchmark
87
+ >>> benchmark(model="yolo11n.pt", imgsz=640)
88
+ """
89
+ imgsz = check_imgsz(imgsz)
90
+ assert imgsz[0] == imgsz[1] if isinstance(imgsz, list) else True, "benchmark() only supports square imgsz."
91
+
92
+ import polars as pl # scope for faster 'import ultralytics'
93
+
94
+ pl.Config.set_tbl_cols(-1) # Show all columns
95
+ pl.Config.set_tbl_rows(-1) # Show all rows
96
+ pl.Config.set_tbl_width_chars(-1) # No width limit
97
+ pl.Config.set_tbl_hide_column_data_types(True) # Hide data types
98
+ pl.Config.set_tbl_hide_dataframe_shape(True) # Hide shape info
99
+ pl.Config.set_tbl_formatting("ASCII_BORDERS_ONLY_CONDENSED")
100
+
101
+ device = select_device(device, verbose=False)
102
+ if isinstance(model, (str, Path)):
103
+ model = YOLO(model)
104
+ is_end2end = getattr(model.model.model[-1], "end2end", False)
105
+ data = data or TASK2DATA[model.task] # task to dataset, i.e. coco8.yaml for task=detect
106
+ key = TASK2METRIC[model.task] # task to metric, i.e. metrics/mAP50-95(B) for task=detect
107
+
108
+ y = []
109
+ t0 = time.time()
110
+
111
+ format_arg = format.lower()
112
+ if format_arg:
113
+ formats = frozenset(export_formats()["Argument"])
114
+ assert format in formats, f"Expected format to be one of {formats}, but got '{format_arg}'."
115
+ for name, format, suffix, cpu, gpu, _ in zip(*export_formats().values()):
116
+ emoji, filename = "❌", None # export defaults
117
+ try:
118
+ if format_arg and format_arg != format:
119
+ continue
120
+
121
+ # Checks
122
+ if format == "pb":
123
+ assert model.task != "obb", "TensorFlow GraphDef not supported for OBB task"
124
+ elif format == "edgetpu":
125
+ assert LINUX and not ARM64, "Edge TPU export only supported on non-aarch64 Linux"
126
+ elif format in {"coreml", "tfjs"}:
127
+ assert MACOS or (LINUX and not ARM64), (
128
+ "CoreML and TF.js export only supported on macOS and non-aarch64 Linux"
129
+ )
130
+ if format == "coreml":
131
+ assert not IS_PYTHON_3_13, "CoreML not supported on Python 3.13"
132
+ if format in {"saved_model", "pb", "tflite", "edgetpu", "tfjs"}:
133
+ assert not isinstance(model, YOLOWorld), "YOLOWorldv2 TensorFlow exports not supported by onnx2tf yet"
134
+ # assert not IS_PYTHON_MINIMUM_3_12, "TFLite exports not supported on Python>=3.12 yet"
135
+ if format == "paddle":
136
+ assert not isinstance(model, YOLOWorld), "YOLOWorldv2 Paddle exports not supported yet"
137
+ assert model.task != "obb", "Paddle OBB bug https://github.com/PaddlePaddle/Paddle/issues/72024"
138
+ assert not is_end2end, "End-to-end models not supported by PaddlePaddle yet"
139
+ assert (LINUX and not IS_JETSON) or MACOS, "Windows and Jetson Paddle exports not supported yet"
140
+ if format == "mnn":
141
+ assert not isinstance(model, YOLOWorld), "YOLOWorldv2 MNN exports not supported yet"
142
+ if format == "ncnn":
143
+ assert not isinstance(model, YOLOWorld), "YOLOWorldv2 NCNN exports not supported yet"
144
+ if format == "imx":
145
+ assert not is_end2end
146
+ assert not isinstance(model, YOLOWorld), "YOLOWorldv2 IMX exports not supported"
147
+ assert model.task in {"detect", "classify", "pose"}, (
148
+ "IMX export is only supported for detection, classification and pose estimation tasks"
149
+ )
150
+ assert "C2f" in model.__str__(), "IMX only supported for YOLOv8n and YOLO11n"
151
+ if format == "rknn":
152
+ assert not isinstance(model, YOLOWorld), "YOLOWorldv2 RKNN exports not supported yet"
153
+ assert not is_end2end, "End-to-end models not supported by RKNN yet"
154
+ assert LINUX, "RKNN only supported on Linux"
155
+ assert not is_rockchip(), "RKNN Inference only supported on Rockchip devices"
156
+ if format == "executorch":
157
+ assert not isinstance(model, YOLOWorld), "YOLOWorldv2 ExecuTorch exports not supported yet"
158
+ assert not is_end2end, "End-to-end models not supported by ExecuTorch yet"
159
+ if "cpu" in device.type:
160
+ assert cpu, "inference not supported on CPU"
161
+ if "cuda" in device.type:
162
+ assert gpu, "inference not supported on GPU"
163
+
164
+ # Export
165
+ if format == "-":
166
+ filename = model.pt_path or model.ckpt_path or model.model_name
167
+ exported_model = model # PyTorch format
168
+ else:
169
+ filename = model.export(
170
+ imgsz=imgsz, format=format, half=half, int8=int8, data=data, device=device, verbose=False, **kwargs
171
+ )
172
+ exported_model = YOLO(filename, task=model.task)
173
+ assert suffix in str(filename), "export failed"
174
+ emoji = "❎" # indicates export succeeded
175
+
176
+ # Predict
177
+ assert model.task != "pose" or format != "pb", "GraphDef Pose inference is not supported"
178
+ assert model.task != "pose" or format != "executorch", "ExecuTorch Pose inference is not supported"
179
+ assert format not in {"edgetpu", "tfjs"}, "inference not supported"
180
+ assert format != "coreml" or platform.system() == "Darwin", "inference only supported on macOS>=10.13"
181
+ if format == "ncnn":
182
+ assert not is_end2end, "End-to-end torch.topk operation is not supported for NCNN prediction yet"
183
+ exported_model.predict(ASSETS / "bus.jpg", imgsz=imgsz, device=device, half=half, verbose=False)
184
+
185
+ # Validate
186
+ results = exported_model.val(
187
+ data=data,
188
+ batch=1,
189
+ imgsz=imgsz,
190
+ plots=False,
191
+ device=device,
192
+ half=half,
193
+ int8=int8,
194
+ verbose=False,
195
+ conf=0.001, # all the pre-set benchmark mAP values are based on conf=0.001
196
+ )
197
+ metric, speed = results.results_dict[key], results.speed["inference"]
198
+ fps = round(1000 / (speed + eps), 2) # frames per second
199
+ y.append([name, "✅", round(file_size(filename), 1), round(metric, 4), round(speed, 2), fps])
200
+ except Exception as e:
201
+ if verbose:
202
+ assert type(e) is AssertionError, f"Benchmark failure for {name}: {e}"
203
+ LOGGER.error(f"Benchmark failure for {name}: {e}")
204
+ y.append([name, emoji, round(file_size(filename), 1), None, None, None]) # mAP, t_inference
205
+
206
+ # Print results
207
+ check_yolo(device=device) # print system info
208
+ df = pl.DataFrame(y, schema=["Format", "Status❔", "Size (MB)", key, "Inference time (ms/im)", "FPS"], orient="row")
209
+ df = df.with_row_index(" ", offset=1) # add index info
210
+ df_display = df.with_columns(pl.all().cast(pl.String).fill_null("-"))
211
+
212
+ name = model.model_name
213
+ dt = time.time() - t0
214
+ legend = "Benchmarks legend: - ✅ Success - ❎ Export passed but validation failed - ❌️ Export failed"
215
+ s = f"\nBenchmarks complete for {name} on {data} at imgsz={imgsz} ({dt:.2f}s)\n{legend}\n{df_display}\n"
216
+ LOGGER.info(s)
217
+ with open("benchmarks.log", "a", errors="ignore", encoding="utf-8") as f:
218
+ f.write(s)
219
+
220
+ if verbose and isinstance(verbose, float):
221
+ metrics = df[key].to_numpy() # values to compare to floor
222
+ floor = verbose # minimum metric floor to pass, i.e. = 0.29 mAP for YOLOv5n
223
+ assert all(x > floor for x in metrics if not np.isnan(x)), f"Benchmark failure: metric(s) < floor {floor}"
224
+
225
+ return df_display
226
+
227
+
228
+ class RF100Benchmark:
229
+ """Benchmark YOLO model performance across various formats for speed and accuracy.
230
+
231
+ This class provides functionality to benchmark YOLO models on the RF100 dataset collection.
232
+
233
+ Attributes:
234
+ ds_names (list[str]): Names of datasets used for benchmarking.
235
+ ds_cfg_list (list[Path]): List of paths to dataset configuration files.
236
+ rf (Roboflow): Roboflow instance for accessing datasets.
237
+ val_metrics (list[str]): Metrics used for validation.
238
+
239
+ Methods:
240
+ set_key: Set Roboflow API key for accessing datasets.
241
+ parse_dataset: Parse dataset links and download datasets.
242
+ fix_yaml: Fix train and validation paths in YAML files.
243
+ evaluate: Evaluate model performance on validation results.
244
+ """
245
+
246
+ def __init__(self):
247
+ """Initialize the RF100Benchmark class for benchmarking YOLO model performance across various formats."""
248
+ self.ds_names = []
249
+ self.ds_cfg_list = []
250
+ self.rf = None
251
+ self.val_metrics = ["class", "images", "targets", "precision", "recall", "map50", "map95"]
252
+
253
+ def set_key(self, api_key: str):
254
+ """Set Roboflow API key for processing.
255
+
256
+ Args:
257
+ api_key (str): The API key.
258
+
259
+ Examples:
260
+ Set the Roboflow API key for accessing datasets:
261
+ >>> benchmark = RF100Benchmark()
262
+ >>> benchmark.set_key("your_roboflow_api_key")
263
+ """
264
+ check_requirements("roboflow")
265
+ from roboflow import Roboflow
266
+
267
+ self.rf = Roboflow(api_key=api_key)
268
+
269
+ def parse_dataset(self, ds_link_txt: str = "datasets_links.txt"):
270
+ """Parse dataset links and download datasets.
271
+
272
+ Args:
273
+ ds_link_txt (str): Path to the file containing dataset links.
274
+
275
+ Returns:
276
+ ds_names (list[str]): List of dataset names.
277
+ ds_cfg_list (list[Path]): List of paths to dataset configuration files.
278
+
279
+ Examples:
280
+ >>> benchmark = RF100Benchmark()
281
+ >>> benchmark.set_key("api_key")
282
+ >>> benchmark.parse_dataset("datasets_links.txt")
283
+ """
284
+ (shutil.rmtree("rf-100"), os.mkdir("rf-100")) if os.path.exists("rf-100") else os.mkdir("rf-100")
285
+ os.chdir("rf-100")
286
+ os.mkdir("ultralytics-benchmarks")
287
+ safe_download(f"{ASSETS_URL}/datasets_links.txt")
288
+
289
+ with open(ds_link_txt, encoding="utf-8") as file:
290
+ for line in file:
291
+ try:
292
+ _, _url, workspace, project, version = re.split("/+", line.strip())
293
+ self.ds_names.append(project)
294
+ proj_version = f"{project}-{version}"
295
+ if not Path(proj_version).exists():
296
+ self.rf.workspace(workspace).project(project).version(version).download("yolov8")
297
+ else:
298
+ LOGGER.info("Dataset already downloaded.")
299
+ self.ds_cfg_list.append(Path.cwd() / proj_version / "data.yaml")
300
+ except Exception:
301
+ continue
302
+
303
+ return self.ds_names, self.ds_cfg_list
304
+
305
+ @staticmethod
306
+ def fix_yaml(path: Path):
307
+ """Fix the train and validation paths in a given YAML file."""
308
+ yaml_data = YAML.load(path)
309
+ yaml_data["train"] = "train/images"
310
+ yaml_data["val"] = "valid/images"
311
+ YAML.dump(yaml_data, path)
312
+
313
+ def evaluate(self, yaml_path: str, val_log_file: str, eval_log_file: str, list_ind: int):
314
+ """Evaluate model performance on validation results.
315
+
316
+ Args:
317
+ yaml_path (str): Path to the YAML configuration file.
318
+ val_log_file (str): Path to the validation log file.
319
+ eval_log_file (str): Path to the evaluation log file.
320
+ list_ind (int): Index of the current dataset in the list.
321
+
322
+ Returns:
323
+ (float): The mean average precision (mAP) value for the evaluated model.
324
+
325
+ Examples:
326
+ Evaluate a model on a specific dataset
327
+ >>> benchmark = RF100Benchmark()
328
+ >>> benchmark.evaluate("path/to/data.yaml", "path/to/val_log.txt", "path/to/eval_log.txt", 0)
329
+ """
330
+ skip_symbols = ["🚀", "⚠️", "💡", "❌"]
331
+ class_names = YAML.load(yaml_path)["names"]
332
+ with open(val_log_file, encoding="utf-8") as f:
333
+ lines = f.readlines()
334
+ eval_lines = []
335
+ for line in lines:
336
+ if any(symbol in line for symbol in skip_symbols):
337
+ continue
338
+ entries = line.split(" ")
339
+ entries = list(filter(lambda val: val != "", entries))
340
+ entries = [e.strip("\n") for e in entries]
341
+ eval_lines.extend(
342
+ {
343
+ "class": entries[0],
344
+ "images": entries[1],
345
+ "targets": entries[2],
346
+ "precision": entries[3],
347
+ "recall": entries[4],
348
+ "map50": entries[5],
349
+ "map95": entries[6],
350
+ }
351
+ for e in entries
352
+ if e in class_names or (e == "all" and "(AP)" not in entries and "(AR)" not in entries)
353
+ )
354
+ map_val = 0.0
355
+ if len(eval_lines) > 1:
356
+ LOGGER.info("Multiple dicts found")
357
+ for lst in eval_lines:
358
+ if lst["class"] == "all":
359
+ map_val = lst["map50"]
360
+ else:
361
+ LOGGER.info("Single dict found")
362
+ map_val = next(res["map50"] for res in eval_lines)
363
+
364
+ with open(eval_log_file, "a", encoding="utf-8") as f:
365
+ f.write(f"{self.ds_names[list_ind]}: {map_val}\n")
366
+
367
+ return float(map_val)
368
+
369
+
370
+ class ProfileModels:
371
+ """ProfileModels class for profiling different models on ONNX and TensorRT.
372
+
373
+ This class profiles the performance of different models, returning results such as model speed and FLOPs.
374
+
375
+ Attributes:
376
+ paths (list[str]): Paths of the models to profile.
377
+ num_timed_runs (int): Number of timed runs for the profiling.
378
+ num_warmup_runs (int): Number of warmup runs before profiling.
379
+ min_time (float): Minimum number of seconds to profile for.
380
+ imgsz (int): Image size used in the models.
381
+ half (bool): Flag to indicate whether to use FP16 half-precision for TensorRT profiling.
382
+ trt (bool): Flag to indicate whether to profile using TensorRT.
383
+ device (torch.device): Device used for profiling.
384
+
385
+ Methods:
386
+ run: Profile YOLO models for speed and accuracy across various formats.
387
+ get_files: Get all relevant model files.
388
+ get_onnx_model_info: Extract metadata from an ONNX model.
389
+ iterative_sigma_clipping: Apply sigma clipping to remove outliers.
390
+ profile_tensorrt_model: Profile a TensorRT model.
391
+ profile_onnx_model: Profile an ONNX model.
392
+ generate_table_row: Generate a table row with model metrics.
393
+ generate_results_dict: Generate a dictionary of profiling results.
394
+ print_table: Print a formatted table of results.
395
+
396
+ Examples:
397
+ Profile models and print results
398
+ >>> from ultralytics.utils.benchmarks import ProfileModels
399
+ >>> profiler = ProfileModels(["yolo11n.yaml", "yolov8s.yaml"], imgsz=640)
400
+ >>> profiler.run()
401
+ """
402
+
403
+ def __init__(
404
+ self,
405
+ paths: list[str],
406
+ num_timed_runs: int = 100,
407
+ num_warmup_runs: int = 10,
408
+ min_time: float = 60,
409
+ imgsz: int = 640,
410
+ half: bool = True,
411
+ trt: bool = True,
412
+ device: torch.device | str | None = None,
413
+ ):
414
+ """Initialize the ProfileModels class for profiling models.
415
+
416
+ Args:
417
+ paths (list[str]): List of paths of the models to be profiled.
418
+ num_timed_runs (int): Number of timed runs for the profiling.
419
+ num_warmup_runs (int): Number of warmup runs before the actual profiling starts.
420
+ min_time (float): Minimum time in seconds for profiling a model.
421
+ imgsz (int): Size of the image used during profiling.
422
+ half (bool): Flag to indicate whether to use FP16 half-precision for TensorRT profiling.
423
+ trt (bool): Flag to indicate whether to profile using TensorRT.
424
+ device (torch.device | str | None): Device used for profiling. If None, it is determined automatically.
425
+
426
+ Notes:
427
+ FP16 'half' argument option removed for ONNX as slower on CPU than FP32.
428
+ """
429
+ self.paths = paths
430
+ self.num_timed_runs = num_timed_runs
431
+ self.num_warmup_runs = num_warmup_runs
432
+ self.min_time = min_time
433
+ self.imgsz = imgsz
434
+ self.half = half
435
+ self.trt = trt # run TensorRT profiling
436
+ self.device = device if isinstance(device, torch.device) else select_device(device)
437
+
438
+ def run(self):
439
+ """Profile YOLO models for speed and accuracy across various formats including ONNX and TensorRT.
440
+
441
+ Returns:
442
+ (list[dict]): List of dictionaries containing profiling results for each model.
443
+
444
+ Examples:
445
+ Profile models and print results
446
+ >>> from ultralytics.utils.benchmarks import ProfileModels
447
+ >>> profiler = ProfileModels(["yolo11n.yaml", "yolov8s.yaml"])
448
+ >>> results = profiler.run()
449
+ """
450
+ files = self.get_files()
451
+
452
+ if not files:
453
+ LOGGER.warning("No matching *.pt or *.onnx files found.")
454
+ return []
455
+
456
+ table_rows = []
457
+ output = []
458
+ for file in files:
459
+ engine_file = file.with_suffix(".engine")
460
+ if file.suffix in {".pt", ".yaml", ".yml"}:
461
+ model = YOLO(str(file))
462
+ model.fuse() # to report correct params and GFLOPs in model.info()
463
+ model_info = model.info()
464
+ if self.trt and self.device.type != "cpu" and not engine_file.is_file():
465
+ engine_file = model.export(
466
+ format="engine",
467
+ half=self.half,
468
+ imgsz=self.imgsz,
469
+ device=self.device,
470
+ verbose=False,
471
+ )
472
+ onnx_file = model.export(
473
+ format="onnx",
474
+ imgsz=self.imgsz,
475
+ device=self.device,
476
+ verbose=False,
477
+ )
478
+ elif file.suffix == ".onnx":
479
+ model_info = self.get_onnx_model_info(file)
480
+ onnx_file = file
481
+ else:
482
+ continue
483
+
484
+ t_engine = self.profile_tensorrt_model(str(engine_file))
485
+ t_onnx = self.profile_onnx_model(str(onnx_file))
486
+ table_rows.append(self.generate_table_row(file.stem, t_onnx, t_engine, model_info))
487
+ output.append(self.generate_results_dict(file.stem, t_onnx, t_engine, model_info))
488
+
489
+ self.print_table(table_rows)
490
+ return output
491
+
492
+ def get_files(self):
493
+ """Return a list of paths for all relevant model files given by the user.
494
+
495
+ Returns:
496
+ (list[Path]): List of Path objects for the model files.
497
+ """
498
+ files = []
499
+ for path in self.paths:
500
+ path = Path(path)
501
+ if path.is_dir():
502
+ extensions = ["*.pt", "*.onnx", "*.yaml"]
503
+ files.extend([file for ext in extensions for file in glob.glob(str(path / ext))])
504
+ elif path.suffix in {".pt", ".yaml", ".yml"}: # add non-existing
505
+ files.append(str(path))
506
+ else:
507
+ files.extend(glob.glob(str(path)))
508
+
509
+ LOGGER.info(f"Profiling: {sorted(files)}")
510
+ return [Path(file) for file in sorted(files)]
511
+
512
+ @staticmethod
513
+ def get_onnx_model_info(onnx_file: str):
514
+ """Extract metadata from an ONNX model file including parameters, GFLOPs, and input shape."""
515
+ return 0.0, 0.0, 0.0, 0.0 # return (num_layers, num_params, num_gradients, num_flops)
516
+
517
+ @staticmethod
518
+ def iterative_sigma_clipping(data: np.ndarray, sigma: float = 2, max_iters: int = 3):
519
+ """Apply iterative sigma clipping to data to remove outliers.
520
+
521
+ Args:
522
+ data (np.ndarray): Input data array.
523
+ sigma (float): Number of standard deviations to use for clipping.
524
+ max_iters (int): Maximum number of iterations for the clipping process.
525
+
526
+ Returns:
527
+ (np.ndarray): Clipped data array with outliers removed.
528
+ """
529
+ data = np.array(data)
530
+ for _ in range(max_iters):
531
+ mean, std = np.mean(data), np.std(data)
532
+ clipped_data = data[(data > mean - sigma * std) & (data < mean + sigma * std)]
533
+ if len(clipped_data) == len(data):
534
+ break
535
+ data = clipped_data
536
+ return data
537
+
538
+ def profile_tensorrt_model(self, engine_file: str, eps: float = 1e-3):
539
+ """Profile YOLO model performance with TensorRT, measuring average run time and standard deviation.
540
+
541
+ Args:
542
+ engine_file (str): Path to the TensorRT engine file.
543
+ eps (float): Small epsilon value to prevent division by zero.
544
+
545
+ Returns:
546
+ mean_time (float): Mean inference time in milliseconds.
547
+ std_time (float): Standard deviation of inference time in milliseconds.
548
+ """
549
+ if not self.trt or not Path(engine_file).is_file():
550
+ return 0.0, 0.0
551
+
552
+ # Model and input
553
+ model = YOLO(engine_file)
554
+ input_data = np.zeros((self.imgsz, self.imgsz, 3), dtype=np.uint8) # use uint8 for Classify
555
+
556
+ # Warmup runs
557
+ elapsed = 0.0
558
+ for _ in range(3):
559
+ start_time = time.time()
560
+ for _ in range(self.num_warmup_runs):
561
+ model(input_data, imgsz=self.imgsz, verbose=False)
562
+ elapsed = time.time() - start_time
563
+
564
+ # Compute number of runs as higher of min_time or num_timed_runs
565
+ num_runs = max(round(self.min_time / (elapsed + eps) * self.num_warmup_runs), self.num_timed_runs * 50)
566
+
567
+ # Timed runs
568
+ run_times = []
569
+ for _ in TQDM(range(num_runs), desc=engine_file):
570
+ results = model(input_data, imgsz=self.imgsz, verbose=False)
571
+ run_times.append(results[0].speed["inference"]) # Convert to milliseconds
572
+
573
+ run_times = self.iterative_sigma_clipping(np.array(run_times), sigma=2, max_iters=3) # sigma clipping
574
+ return np.mean(run_times), np.std(run_times)
575
+
576
+ @staticmethod
577
+ def check_dynamic(tensor_shape):
578
+ """Check whether the tensor shape in the ONNX model is dynamic."""
579
+ return not all(isinstance(dim, int) and dim >= 0 for dim in tensor_shape)
580
+
581
+ def profile_onnx_model(self, onnx_file: str, eps: float = 1e-3):
582
+ """Profile an ONNX model, measuring average inference time and standard deviation across multiple runs.
583
+
584
+ Args:
585
+ onnx_file (str): Path to the ONNX model file.
586
+ eps (float): Small epsilon value to prevent division by zero.
587
+
588
+ Returns:
589
+ mean_time (float): Mean inference time in milliseconds.
590
+ std_time (float): Standard deviation of inference time in milliseconds.
591
+ """
592
+ check_requirements([("onnxruntime", "onnxruntime-gpu")]) # either package meets requirements
593
+ import onnxruntime as ort
594
+
595
+ # Session with either 'TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider'
596
+ sess_options = ort.SessionOptions()
597
+ sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
598
+ sess_options.intra_op_num_threads = 8 # Limit the number of threads
599
+ sess = ort.InferenceSession(onnx_file, sess_options, providers=["CPUExecutionProvider"])
600
+
601
+ input_data_dict = {}
602
+ for input_tensor in sess.get_inputs():
603
+ input_type = input_tensor.type
604
+ if self.check_dynamic(input_tensor.shape):
605
+ if len(input_tensor.shape) != 4 and self.check_dynamic(input_tensor.shape[1:]):
606
+ raise ValueError(f"Unsupported dynamic shape {input_tensor.shape} of {input_tensor.name}")
607
+ input_shape = (
608
+ (1, 3, self.imgsz, self.imgsz) if len(input_tensor.shape) == 4 else (1, *input_tensor.shape[1:])
609
+ )
610
+ else:
611
+ input_shape = input_tensor.shape
612
+
613
+ # Mapping ONNX datatype to numpy datatype
614
+ if "float16" in input_type:
615
+ input_dtype = np.float16
616
+ elif "float" in input_type:
617
+ input_dtype = np.float32
618
+ elif "double" in input_type:
619
+ input_dtype = np.float64
620
+ elif "int64" in input_type:
621
+ input_dtype = np.int64
622
+ elif "int32" in input_type:
623
+ input_dtype = np.int32
624
+ else:
625
+ raise ValueError(f"Unsupported ONNX datatype {input_type}")
626
+
627
+ input_data = np.random.rand(*input_shape).astype(input_dtype)
628
+ input_name = input_tensor.name
629
+ input_data_dict[input_name] = input_data
630
+
631
+ output_name = sess.get_outputs()[0].name
632
+
633
+ # Warmup runs
634
+ elapsed = 0.0
635
+ for _ in range(3):
636
+ start_time = time.time()
637
+ for _ in range(self.num_warmup_runs):
638
+ sess.run([output_name], input_data_dict)
639
+ elapsed = time.time() - start_time
640
+
641
+ # Compute number of runs as higher of min_time or num_timed_runs
642
+ num_runs = max(round(self.min_time / (elapsed + eps) * self.num_warmup_runs), self.num_timed_runs)
643
+
644
+ # Timed runs
645
+ run_times = []
646
+ for _ in TQDM(range(num_runs), desc=onnx_file):
647
+ start_time = time.time()
648
+ sess.run([output_name], input_data_dict)
649
+ run_times.append((time.time() - start_time) * 1000) # Convert to milliseconds
650
+
651
+ run_times = self.iterative_sigma_clipping(np.array(run_times), sigma=2, max_iters=5) # sigma clipping
652
+ return np.mean(run_times), np.std(run_times)
653
+
654
+ def generate_table_row(
655
+ self,
656
+ model_name: str,
657
+ t_onnx: tuple[float, float],
658
+ t_engine: tuple[float, float],
659
+ model_info: tuple[float, float, float, float],
660
+ ):
661
+ """Generate a table row string with model performance metrics.
662
+
663
+ Args:
664
+ model_name (str): Name of the model.
665
+ t_onnx (tuple): ONNX model inference time statistics (mean, std).
666
+ t_engine (tuple): TensorRT engine inference time statistics (mean, std).
667
+ model_info (tuple): Model information (layers, params, gradients, flops).
668
+
669
+ Returns:
670
+ (str): Formatted table row string with model metrics.
671
+ """
672
+ _layers, params, _gradients, flops = model_info
673
+ return (
674
+ f"| {model_name:18s} | {self.imgsz} | - | {t_onnx[0]:.1f}±{t_onnx[1]:.1f} ms | {t_engine[0]:.1f}±"
675
+ f"{t_engine[1]:.1f} ms | {params / 1e6:.1f} | {flops:.1f} |"
676
+ )
677
+
678
+ @staticmethod
679
+ def generate_results_dict(
680
+ model_name: str,
681
+ t_onnx: tuple[float, float],
682
+ t_engine: tuple[float, float],
683
+ model_info: tuple[float, float, float, float],
684
+ ):
685
+ """Generate a dictionary of profiling results.
686
+
687
+ Args:
688
+ model_name (str): Name of the model.
689
+ t_onnx (tuple): ONNX model inference time statistics (mean, std).
690
+ t_engine (tuple): TensorRT engine inference time statistics (mean, std).
691
+ model_info (tuple): Model information (layers, params, gradients, flops).
692
+
693
+ Returns:
694
+ (dict): Dictionary containing profiling results.
695
+ """
696
+ _layers, params, _gradients, flops = model_info
697
+ return {
698
+ "model/name": model_name,
699
+ "model/parameters": params,
700
+ "model/GFLOPs": round(flops, 3),
701
+ "model/speed_ONNX(ms)": round(t_onnx[0], 3),
702
+ "model/speed_TensorRT(ms)": round(t_engine[0], 3),
703
+ }
704
+
705
+ @staticmethod
706
+ def print_table(table_rows: list[str]):
707
+ """Print a formatted table of model profiling results.
708
+
709
+ Args:
710
+ table_rows (list[str]): List of formatted table row strings.
711
+ """
712
+ gpu = torch.cuda.get_device_name(0) if torch.cuda.is_available() else "GPU"
713
+ headers = [
714
+ "Model",
715
+ "size<br><sup>(pixels)",
716
+ "mAP<sup>val<br>50-95",
717
+ f"Speed<br><sup>CPU ({get_cpu_info()}) ONNX<br>(ms)",
718
+ f"Speed<br><sup>{gpu} TensorRT<br>(ms)",
719
+ "params<br><sup>(M)",
720
+ "FLOPs<br><sup>(B)",
721
+ ]
722
+ header = "|" + "|".join(f" {h} " for h in headers) + "|"
723
+ separator = "|" + "|".join("-" * (len(h) + 2) for h in headers) + "|"
724
+
725
+ LOGGER.info(f"\n\n{header}")
726
+ LOGGER.info(separator)
727
+ for row in table_rows:
728
+ LOGGER.info(row)