Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

#13643 Fix deprecation warning for `pkg_resources` dependency by changing to `packaging`

Merged
Ghost merged 1 commits into Ultralytics:master from ultralytics:fix-pkg-resource-dep
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
  1. # Ultralytics ๐Ÿš€ AGPL-3.0 License - https://ultralytics.com/license
  2. """
  3. Run YOLOv5 benchmarks on all supported export formats.
  4. Format | `export.py --include` | Model
  5. --- | --- | ---
  6. PyTorch | - | yolov5s.pt
  7. TorchScript | `torchscript` | yolov5s.torchscript
  8. ONNX | `onnx` | yolov5s.onnx
  9. OpenVINO | `openvino` | yolov5s_openvino_model/
  10. TensorRT | `engine` | yolov5s.engine
  11. CoreML | `coreml` | yolov5s.mlpackage
  12. TensorFlow SavedModel | `saved_model` | yolov5s_saved_model/
  13. TensorFlow GraphDef | `pb` | yolov5s.pb
  14. TensorFlow Lite | `tflite` | yolov5s.tflite
  15. TensorFlow Edge TPU | `edgetpu` | yolov5s_edgetpu.tflite
  16. TensorFlow.js | `tfjs` | yolov5s_web_model/
  17. Requirements:
  18. $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU
  19. $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU
  20. $ pip install -U nvidia-tensorrt --index-url https://pypi.ngc.nvidia.com # TensorRT
  21. Usage:
  22. $ python benchmarks.py --weights yolov5s.pt --img 640
  23. """
  24. import argparse
  25. import platform
  26. import sys
  27. import time
  28. from pathlib import Path
  29. import pandas as pd
  30. FILE = Path(__file__).resolve()
  31. ROOT = FILE.parents[0] # YOLOv5 root directory
  32. if str(ROOT) not in sys.path:
  33. sys.path.append(str(ROOT)) # add ROOT to PATH
  34. # ROOT = ROOT.relative_to(Path.cwd()) # relative
  35. import export
  36. from models.experimental import attempt_load
  37. from models.yolo import SegmentationModel
  38. from segment.val import run as val_seg
  39. from utils import notebook_init
  40. from utils.general import LOGGER, check_yaml, file_size, print_args
  41. from utils.torch_utils import select_device
  42. from val import run as val_det
  43. def run(
  44. weights=ROOT / "yolov5s.pt", # weights path
  45. imgsz=640, # inference size (pixels)
  46. batch_size=1, # batch size
  47. data=ROOT / "data/coco128.yaml", # dataset.yaml path
  48. device="", # cuda device, i.e. 0 or 0,1,2,3 or cpu
  49. half=False, # use FP16 half-precision inference
  50. test=False, # test exports only
  51. pt_only=False, # test PyTorch only
  52. hard_fail=False, # throw error on benchmark failure
  53. ):
  54. """
  55. Run YOLOv5 benchmarks on multiple export formats and log results for model performance evaluation.
  56. Args:
  57. weights (Path | str): Path to the model weights file (default: ROOT / "yolov5s.pt").
  58. imgsz (int): Inference size in pixels (default: 640).
  59. batch_size (int): Batch size for inference (default: 1).
  60. data (Path | str): Path to the dataset.yaml file (default: ROOT / "data/coco128.yaml").
  61. device (str): CUDA device, e.g., '0' or '0,1,2,3' or 'cpu' (default: "").
  62. half (bool): Use FP16 half-precision inference (default: False).
  63. test (bool): Test export formats only (default: False).
  64. pt_only (bool): Test PyTorch format only (default: False).
  65. hard_fail (bool): Throw an error on benchmark failure if True (default: False).
  66. Returns:
  67. None. Logs information about the benchmark results, including the format, size, mAP50-95, and inference time.
  68. Notes:
  69. Supported export formats and models include PyTorch, TorchScript, ONNX, OpenVINO, TensorRT, CoreML,
  70. TensorFlow SavedModel, TensorFlow GraphDef, TensorFlow Lite, and TensorFlow Edge TPU. Edge TPU and TF.js
  71. are unsupported.
  72. Example:
  73. ```python
  74. $ python benchmarks.py --weights yolov5s.pt --img 640
  75. ```
  76. Usage:
  77. Install required packages:
  78. $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU support
  79. $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU support
  80. $ pip install -U nvidia-tensorrt --index-url https://pypi.ngc.nvidia.com # TensorRT
  81. Run benchmarks:
  82. $ python benchmarks.py --weights yolov5s.pt --img 640
  83. """
  84. y, t = [], time.time()
  85. device = select_device(device)
  86. model_type = type(attempt_load(weights, fuse=False)) # DetectionModel, SegmentationModel, etc.
  87. for i, (name, f, suffix, cpu, gpu) in export.export_formats().iterrows(): # index, (name, file, suffix, CPU, GPU)
  88. try:
  89. assert i not in (9, 10), "inference not supported" # Edge TPU and TF.js are unsupported
  90. assert i != 5 or platform.system() == "Darwin", "inference only supported on macOS>=10.13" # CoreML
  91. if "cpu" in device.type:
  92. assert cpu, "inference not supported on CPU"
  93. if "cuda" in device.type:
  94. assert gpu, "inference not supported on GPU"
  95. # Export
  96. if f == "-":
  97. w = weights # PyTorch format
  98. else:
  99. w = export.run(
  100. weights=weights, imgsz=[imgsz], include=[f], batch_size=batch_size, device=device, half=half
  101. )[-1] # all others
  102. assert suffix in str(w), "export failed"
  103. # Validate
  104. if model_type == SegmentationModel:
  105. result = val_seg(data, w, batch_size, imgsz, plots=False, device=device, task="speed", half=half)
  106. metric = result[0][7] # (box(p, r, map50, map), mask(p, r, map50, map), *loss(box, obj, cls))
  107. else: # DetectionModel:
  108. result = val_det(data, w, batch_size, imgsz, plots=False, device=device, task="speed", half=half)
  109. metric = result[0][3] # (p, r, map50, map, *loss(box, obj, cls))
  110. speed = result[2][1] # times (preprocess, inference, postprocess)
  111. y.append([name, round(file_size(w), 1), round(metric, 4), round(speed, 2)]) # MB, mAP, t_inference
  112. except Exception as e:
  113. if hard_fail:
  114. assert type(e) is AssertionError, f"Benchmark --hard-fail for {name}: {e}"
  115. LOGGER.warning(f"WARNING โš ๏ธ Benchmark failure for {name}: {e}")
  116. y.append([name, None, None, None]) # mAP, t_inference
  117. if pt_only and i == 0:
  118. break # break after PyTorch
  119. # Print results
  120. LOGGER.info("\n")
  121. parse_opt()
  122. notebook_init() # print system info
  123. c = ["Format", "Size (MB)", "mAP50-95", "Inference time (ms)"] if map else ["Format", "Export", "", ""]
  124. py = pd.DataFrame(y, columns=c)
  125. LOGGER.info(f"\nBenchmarks complete ({time.time() - t:.2f}s)")
  126. LOGGER.info(str(py if map else py.iloc[:, :2]))
  127. if hard_fail and isinstance(hard_fail, str):
  128. metrics = py["mAP50-95"].array # values to compare to floor
  129. floor = eval(hard_fail) # minimum metric floor to pass, i.e. = 0.29 mAP for YOLOv5n
  130. assert all(x > floor for x in metrics if pd.notna(x)), f"HARD FAIL: mAP50-95 < floor {floor}"
  131. return py
  132. def test(
  133. weights=ROOT / "yolov5s.pt", # weights path
  134. imgsz=640, # inference size (pixels)
  135. batch_size=1, # batch size
  136. data=ROOT / "data/coco128.yaml", # dataset.yaml path
  137. device="", # cuda device, i.e. 0 or 0,1,2,3 or cpu
  138. half=False, # use FP16 half-precision inference
  139. test=False, # test exports only
  140. pt_only=False, # test PyTorch only
  141. hard_fail=False, # throw error on benchmark failure
  142. ):
  143. """
  144. Run YOLOv5 export tests for all supported formats and log the results, including export statuses.
  145. Args:
  146. weights (Path | str): Path to the model weights file (.pt format). Default is 'ROOT / "yolov5s.pt"'.
  147. imgsz (int): Inference image size (in pixels). Default is 640.
  148. batch_size (int): Batch size for testing. Default is 1.
  149. data (Path | str): Path to the dataset configuration file (.yaml format). Default is 'ROOT / "data/coco128.yaml"'.
  150. device (str): Device for running the tests, can be 'cpu' or a specific CUDA device ('0', '0,1,2,3', etc.). Default is an empty string.
  151. half (bool): Use FP16 half-precision for inference if True. Default is False.
  152. test (bool): Test export formats only without running inference. Default is False.
  153. pt_only (bool): Test only the PyTorch model if True. Default is False.
  154. hard_fail (bool): Raise error on export or test failure if True. Default is False.
  155. Returns:
  156. pd.DataFrame: DataFrame containing the results of the export tests, including format names and export statuses.
  157. Examples:
  158. ```python
  159. $ python benchmarks.py --weights yolov5s.pt --img 640
  160. ```
  161. Notes:
  162. Supported export formats and models include PyTorch, TorchScript, ONNX, OpenVINO, TensorRT, CoreML, TensorFlow
  163. SavedModel, TensorFlow GraphDef, TensorFlow Lite, and TensorFlow Edge TPU. Edge TPU and TF.js are unsupported.
  164. Usage:
  165. Install required packages:
  166. $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU support
  167. $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU support
  168. $ pip install -U nvidia-tensorrt --index-url https://pypi.ngc.nvidia.com # TensorRT
  169. Run export tests:
  170. $ python benchmarks.py --weights yolov5s.pt --img 640
  171. """
  172. y, t = [], time.time()
  173. device = select_device(device)
  174. for i, (name, f, suffix, gpu) in export.export_formats().iterrows(): # index, (name, file, suffix, gpu-capable)
  175. try:
  176. w = (
  177. weights
  178. if f == "-"
  179. else export.run(weights=weights, imgsz=[imgsz], include=[f], device=device, half=half)[-1]
  180. ) # weights
  181. assert suffix in str(w), "export failed"
  182. y.append([name, True])
  183. except Exception:
  184. y.append([name, False]) # mAP, t_inference
  185. # Print results
  186. LOGGER.info("\n")
  187. parse_opt()
  188. notebook_init() # print system info
  189. py = pd.DataFrame(y, columns=["Format", "Export"])
  190. LOGGER.info(f"\nExports complete ({time.time() - t:.2f}s)")
  191. LOGGER.info(str(py))
  192. return py
  193. def parse_opt():
  194. """
  195. Parses command-line arguments for YOLOv5 model inference configuration.
  196. Args:
  197. weights (str): The path to the weights file. Defaults to 'ROOT / "yolov5s.pt"'.
  198. imgsz (int): Inference size in pixels. Defaults to 640.
  199. batch_size (int): Batch size. Defaults to 1.
  200. data (str): Path to the dataset YAML file. Defaults to 'ROOT / "data/coco128.yaml"'.
  201. device (str): CUDA device, e.g., '0' or '0,1,2,3' or 'cpu'. Defaults to an empty string (auto-select).
  202. half (bool): Use FP16 half-precision inference. This is a flag and defaults to False.
  203. test (bool): Test exports only. This is a flag and defaults to False.
  204. pt_only (bool): Test PyTorch only. This is a flag and defaults to False.
  205. hard_fail (bool | str): Throw an error on benchmark failure. Can be a boolean or a string representing a minimum
  206. metric floor, e.g., '0.29'. Defaults to False.
  207. Returns:
  208. argparse.Namespace: Parsed command-line arguments encapsulated in an argparse Namespace object.
  209. Notes:
  210. The function modifies the 'opt.data' by checking and validating the YAML path using 'check_yaml()'.
  211. The parsed arguments are printed for reference using 'print_args()'.
  212. """
  213. parser = argparse.ArgumentParser()
  214. parser.add_argument("--weights", type=str, default=ROOT / "yolov5s.pt", help="weights path")
  215. parser.add_argument("--imgsz", "--img", "--img-size", type=int, default=640, help="inference size (pixels)")
  216. parser.add_argument("--batch-size", type=int, default=1, help="batch size")
  217. parser.add_argument("--data", type=str, default=ROOT / "data/coco128.yaml", help="dataset.yaml path")
  218. parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
  219. parser.add_argument("--half", action="store_true", help="use FP16 half-precision inference")
  220. parser.add_argument("--test", action="store_true", help="test exports only")
  221. parser.add_argument("--pt-only", action="store_true", help="test PyTorch only")
  222. parser.add_argument("--hard-fail", nargs="?", const=True, default=False, help="Exception on error or < min metric")
  223. opt = parser.parse_args()
  224. opt.data = check_yaml(opt.data) # check YAML
  225. print_args(vars(opt))
  226. return opt
  227. def main(opt):
  228. """
  229. Executes YOLOv5 benchmark tests or main training/inference routines based on the provided command-line arguments.
  230. Args:
  231. opt (argparse.Namespace): Parsed command-line arguments including options for weights, image size, batch size, data
  232. configuration, device, and other flags for inference settings.
  233. Returns:
  234. None: This function does not return any value. It leverages side-effects such as logging and running benchmarks.
  235. Example:
  236. ```python
  237. if __name__ == "__main__":
  238. opt = parse_opt()
  239. main(opt)
  240. ```
  241. Notes:
  242. - For a complete list of supported export formats and their respective requirements, refer to the
  243. [Ultralytics YOLOv5 Export Formats](https://github.com/ultralytics/yolov5#export-formats).
  244. - Ensure that you have installed all necessary dependencies by following the installation instructions detailed in
  245. the [main repository](https://github.com/ultralytics/yolov5#installation).
  246. ```shell
  247. # Running benchmarks on default weights and image size
  248. $ python benchmarks.py --weights yolov5s.pt --img 640
  249. ```
  250. """
  251. test(**vars(opt)) if opt.test else run(**vars(opt))
  252. if __name__ == "__main__":
  253. opt = parse_opt()
  254. main(opt)
Discard
Tip!

Press p or to see the previous file or, n or to see the next file