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
tests/__init__.py ADDED
@@ -0,0 +1,23 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ from ultralytics.cfg import TASK2DATA, TASK2MODEL, TASKS
4
+ from ultralytics.utils import ASSETS, WEIGHTS_DIR, checks
5
+
6
+ # Constants used in tests
7
+ MODEL = WEIGHTS_DIR / "path with spaces" / "yolo11n.pt" # test spaces in path
8
+ CFG = "yolo11n.yaml"
9
+ SOURCE = ASSETS / "bus.jpg"
10
+ SOURCES_LIST = [ASSETS / "bus.jpg", ASSETS, ASSETS / "*", ASSETS / "**/*.jpg"]
11
+ CUDA_IS_AVAILABLE = checks.cuda_is_available()
12
+ CUDA_DEVICE_COUNT = checks.cuda_device_count()
13
+ TASK_MODEL_DATA = [(task, WEIGHTS_DIR / TASK2MODEL[task], TASK2DATA[task]) for task in TASKS]
14
+ MODELS = frozenset([*list(TASK2MODEL.values()), "yolo11n-grayscale.pt"])
15
+
16
+ __all__ = (
17
+ "CFG",
18
+ "CUDA_DEVICE_COUNT",
19
+ "CUDA_IS_AVAILABLE",
20
+ "MODEL",
21
+ "SOURCE",
22
+ "SOURCES_LIST",
23
+ )
tests/conftest.py ADDED
@@ -0,0 +1,59 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ import shutil
4
+ from pathlib import Path
5
+
6
+
7
+ def pytest_addoption(parser):
8
+ """Add custom command-line options to pytest."""
9
+ parser.addoption("--slow", action="store_true", default=False, help="Run slow tests")
10
+
11
+
12
+ def pytest_collection_modifyitems(config, items):
13
+ """Modify the list of test items to exclude tests marked as slow if the --slow option is not specified.
14
+
15
+ Args:
16
+ config: The pytest configuration object that provides access to command-line options.
17
+ items (list): The list of collected pytest item objects to be modified based on the presence of --slow option.
18
+ """
19
+ if not config.getoption("--slow"):
20
+ # Remove the item entirely from the list of test items if it's marked as 'slow'
21
+ items[:] = [item for item in items if "slow" not in item.keywords]
22
+
23
+
24
+ def pytest_sessionstart(session):
25
+ """Initialize session configurations for pytest.
26
+
27
+ This function is automatically called by pytest after the 'Session' object has been created but before performing
28
+ test collection. It sets the initial seeds for the test session.
29
+
30
+ Args:
31
+ session: The pytest session object.
32
+ """
33
+ from ultralytics.utils.torch_utils import init_seeds
34
+
35
+ init_seeds()
36
+
37
+
38
+ def pytest_terminal_summary(terminalreporter, exitstatus, config):
39
+ """Cleanup operations after pytest session.
40
+
41
+ This function is automatically called by pytest at the end of the entire test session. It removes certain files and
42
+ directories used during testing.
43
+
44
+ Args:
45
+ terminalreporter: The terminal reporter object used for terminal output.
46
+ exitstatus (int): The exit status of the test run.
47
+ config: The pytest config object.
48
+ """
49
+ from ultralytics.utils import WEIGHTS_DIR
50
+
51
+ # Remove files
52
+ models = [path for x in {"*.onnx", "*.torchscript"} for path in WEIGHTS_DIR.rglob(x)]
53
+ for file in ["decelera_portrait_min.mov", "bus.jpg", "yolo11n.onnx", "yolo11n.torchscript", *models]:
54
+ Path(file).unlink(missing_ok=True)
55
+
56
+ # Remove directories
57
+ models = [path for x in {"*.mlpackage", "*_openvino_model"} for path in WEIGHTS_DIR.rglob(x)]
58
+ for directory in [WEIGHTS_DIR / "path with spaces", *models]:
59
+ shutil.rmtree(directory, ignore_errors=True)
tests/test_cli.py ADDED
@@ -0,0 +1,131 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ import subprocess
4
+ from pathlib import Path
5
+
6
+ import pytest
7
+ from PIL import Image
8
+
9
+ from tests import CUDA_DEVICE_COUNT, CUDA_IS_AVAILABLE, MODELS, TASK_MODEL_DATA
10
+ from ultralytics.utils import ARM64, ASSETS, LINUX, WEIGHTS_DIR, checks
11
+ from ultralytics.utils.torch_utils import TORCH_1_11
12
+
13
+
14
+ def run(cmd: str) -> None:
15
+ """Execute a shell command using subprocess."""
16
+ subprocess.run(cmd.split(), check=True)
17
+
18
+
19
+ def test_special_modes() -> None:
20
+ """Test various special command-line modes for YOLO functionality."""
21
+ run("yolo help")
22
+ run("yolo checks")
23
+ run("yolo version")
24
+ run("yolo settings reset")
25
+ run("yolo cfg")
26
+
27
+
28
+ @pytest.mark.parametrize("task,model,data", TASK_MODEL_DATA)
29
+ def test_train(task: str, model: str, data: str) -> None:
30
+ """Test YOLO training for different tasks, models, and datasets."""
31
+ run(f"yolo train {task} model={model} data={data} imgsz=32 epochs=1 cache=disk")
32
+
33
+
34
+ @pytest.mark.parametrize("task,model,data", TASK_MODEL_DATA)
35
+ def test_val(task: str, model: str, data: str) -> None:
36
+ """Test YOLO validation process for specified task, model, and data using a shell command."""
37
+ run(f"yolo val {task} model={model} data={data} imgsz=32 save_txt save_json visualize")
38
+
39
+
40
+ @pytest.mark.parametrize("task,model,data", TASK_MODEL_DATA)
41
+ def test_predict(task: str, model: str, data: str) -> None:
42
+ """Test YOLO prediction on provided sample assets for specified task and model."""
43
+ run(f"yolo {task} predict model={model} source={ASSETS} imgsz=32 save save_crop save_txt visualize")
44
+
45
+
46
+ @pytest.mark.parametrize("model", MODELS)
47
+ def test_export(model: str) -> None:
48
+ """Test exporting a YOLO model to TorchScript format."""
49
+ run(f"yolo export model={model} format=torchscript imgsz=32")
50
+
51
+
52
+ @pytest.mark.skipif(not TORCH_1_11, reason="RTDETR requires torch>=1.11")
53
+ def test_rtdetr(task: str = "detect", model: Path = WEIGHTS_DIR / "rtdetr-l.pt", data: str = "coco8.yaml") -> None:
54
+ """Test the RTDETR functionality within Ultralytics for detection tasks using specified model and data."""
55
+ # Add comma, spaces, fraction=0.25 args to test single-image training
56
+ run(f"yolo predict {task} model={model} source={ASSETS / 'bus.jpg'} imgsz=160 save save_crop save_txt")
57
+ run(f"yolo train {task} model={model} data={data} --imgsz= 160 epochs =1, cache = disk fraction=0.25")
58
+
59
+
60
+ @pytest.mark.skipif(checks.IS_PYTHON_3_12, reason="MobileSAM with CLIP is not supported in Python 3.12")
61
+ @pytest.mark.skipif(
62
+ checks.IS_PYTHON_3_8 and LINUX and ARM64,
63
+ reason="MobileSAM with CLIP is not supported in Python 3.8 and aarch64 Linux",
64
+ )
65
+ def test_fastsam(
66
+ task: str = "segment", model: str = WEIGHTS_DIR / "FastSAM-s.pt", data: str = "coco8-seg.yaml"
67
+ ) -> None:
68
+ """Test FastSAM model for segmenting objects in images using various prompts within Ultralytics."""
69
+ source = ASSETS / "bus.jpg"
70
+
71
+ run(f"yolo segment val {task} model={model} data={data} imgsz=32")
72
+ run(f"yolo segment predict model={model} source={source} imgsz=32 save save_crop save_txt")
73
+
74
+ from ultralytics import FastSAM
75
+ from ultralytics.models.sam import Predictor
76
+
77
+ # Create a FastSAM model
78
+ sam_model = FastSAM(model) # or FastSAM-x.pt
79
+
80
+ # Run inference on an image
81
+ for s in (source, Image.open(source)):
82
+ everything_results = sam_model(s, device="cpu", retina_masks=True, imgsz=320, conf=0.4, iou=0.9)
83
+
84
+ # Remove small regions
85
+ _new_masks, _ = Predictor.remove_small_regions(everything_results[0].masks.data, min_area=20)
86
+
87
+ # Run inference with bboxes and points and texts prompt at the same time
88
+ sam_model(source, bboxes=[439, 437, 524, 709], points=[[200, 200]], labels=[1], texts="a photo of a dog")
89
+
90
+
91
+ def test_mobilesam() -> None:
92
+ """Test MobileSAM segmentation with point prompts using Ultralytics."""
93
+ from ultralytics import SAM
94
+
95
+ # Load the model
96
+ model = SAM(WEIGHTS_DIR / "mobile_sam.pt")
97
+
98
+ # Source
99
+ source = ASSETS / "zidane.jpg"
100
+
101
+ # Predict a segment based on a 1D point prompt and 1D labels.
102
+ model.predict(source, points=[900, 370], labels=[1])
103
+
104
+ # Predict a segment based on 3D points and 2D labels (multiple points per object).
105
+ model.predict(source, points=[[[900, 370], [1000, 100]]], labels=[[1, 1]])
106
+
107
+ # Predict a segment based on a box prompt
108
+ model.predict(source, bboxes=[439, 437, 524, 709], save=True)
109
+
110
+ # Predict all
111
+ # model(source)
112
+
113
+
114
+ # Slow Tests -----------------------------------------------------------------------------------------------------------
115
+ @pytest.mark.slow
116
+ @pytest.mark.parametrize("task,model,data", TASK_MODEL_DATA)
117
+ @pytest.mark.skipif(not CUDA_IS_AVAILABLE, reason="CUDA is not available")
118
+ @pytest.mark.skipif(CUDA_DEVICE_COUNT < 2, reason="DDP is not available")
119
+ def test_train_gpu(task: str, model: str, data: str) -> None:
120
+ """Test YOLO training on GPU(s) for various tasks and models."""
121
+ run(f"yolo train {task} model={model} data={data} imgsz=32 epochs=1 device=0") # single GPU
122
+ run(f"yolo train {task} model={model} data={data} imgsz=32 epochs=1 device=0,1") # multi GPU
123
+
124
+
125
+ @pytest.mark.parametrize(
126
+ "solution",
127
+ ["count", "blur", "workout", "heatmap", "isegment", "visioneye", "speed", "queue", "analytics", "trackzone"],
128
+ )
129
+ def test_solutions(solution: str) -> None:
130
+ """Test yolo solutions command-line modes."""
131
+ run(f"yolo solutions {solution} verbose=False")
tests/test_cuda.py ADDED
@@ -0,0 +1,216 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ import os
4
+ from itertools import product
5
+ from pathlib import Path
6
+
7
+ import pytest
8
+ import torch
9
+
10
+ from tests import CUDA_DEVICE_COUNT, CUDA_IS_AVAILABLE, MODEL, SOURCE
11
+ from ultralytics import YOLO
12
+ from ultralytics.cfg import TASK2DATA, TASK2MODEL, TASKS
13
+ from ultralytics.utils import ASSETS, IS_JETSON, WEIGHTS_DIR
14
+ from ultralytics.utils.autodevice import GPUInfo
15
+ from ultralytics.utils.checks import check_amp
16
+ from ultralytics.utils.torch_utils import TORCH_1_13
17
+
18
+ # Try to find idle devices if CUDA is available
19
+ DEVICES = []
20
+ if CUDA_IS_AVAILABLE:
21
+ if IS_JETSON:
22
+ DEVICES = [0] # NVIDIA Jetson only has one GPU and does not fully support pynvml library
23
+ else:
24
+ gpu_info = GPUInfo()
25
+ gpu_info.print_status()
26
+ autodevice_fraction = __import__("os").environ.get("YOLO_AUTODEVICE_FRACTION_FREE", 0.3)
27
+ if idle_gpus := gpu_info.select_idle_gpu(
28
+ count=2,
29
+ min_memory_fraction=autodevice_fraction,
30
+ min_util_fraction=autodevice_fraction,
31
+ ):
32
+ DEVICES = idle_gpus
33
+
34
+
35
+ def test_checks():
36
+ """Validate CUDA settings against torch CUDA functions."""
37
+ assert torch.cuda.is_available() == CUDA_IS_AVAILABLE
38
+ assert torch.cuda.device_count() == CUDA_DEVICE_COUNT
39
+
40
+
41
+ @pytest.mark.skipif(not DEVICES, reason="No CUDA devices available")
42
+ def test_amp():
43
+ """Test AMP training checks."""
44
+ model = YOLO("yolo11n.pt").model.to(f"cuda:{DEVICES[0]}")
45
+ assert check_amp(model)
46
+
47
+
48
+ @pytest.mark.slow
49
+ @pytest.mark.skipif(not DEVICES, reason="No CUDA devices available")
50
+ @pytest.mark.parametrize(
51
+ "task, dynamic, int8, half, batch, simplify, nms",
52
+ [ # generate all combinations except for exclusion cases
53
+ (task, dynamic, int8, half, batch, simplify, nms)
54
+ for task, dynamic, int8, half, batch, simplify, nms in product(
55
+ TASKS, [True, False], [False], [False], [1, 2], [True, False], [True, False]
56
+ )
57
+ if not (
58
+ (int8 and half) or (task == "classify" and nms) or (task == "obb" and nms and (not TORCH_1_13 or IS_JETSON))
59
+ )
60
+ ],
61
+ )
62
+ def test_export_onnx_matrix(task, dynamic, int8, half, batch, simplify, nms):
63
+ """Test YOLO exports to ONNX format with various configurations and parameters."""
64
+ file = YOLO(TASK2MODEL[task]).export(
65
+ format="onnx",
66
+ imgsz=32,
67
+ dynamic=dynamic,
68
+ int8=int8,
69
+ half=half,
70
+ batch=batch,
71
+ simplify=simplify,
72
+ nms=nms,
73
+ device=DEVICES[0],
74
+ # opset=20 if nms else None, # fix ONNX Runtime errors with NMS
75
+ )
76
+ YOLO(file)([SOURCE] * batch, imgsz=64 if dynamic else 32, device=DEVICES[0]) # exported model inference
77
+ Path(file).unlink() # cleanup
78
+
79
+
80
+ @pytest.mark.slow
81
+ @pytest.mark.skipif(not DEVICES, reason="No CUDA devices available")
82
+ @pytest.mark.parametrize(
83
+ "task, dynamic, int8, half, batch",
84
+ [ # generate all combinations but exclude those where both int8 and half are True
85
+ (task, dynamic, int8, half, batch)
86
+ # Note: tests reduced below pending compute availability expansion as GPU CI runner utilization is high
87
+ # for task, dynamic, int8, half, batch in product(TASKS, [True, False], [True, False], [True, False], [1, 2])
88
+ for task, dynamic, int8, half, batch in product(TASKS, [True], [True], [False], [2])
89
+ if not (int8 and half) # exclude cases where both int8 and half are True
90
+ ],
91
+ )
92
+ def test_export_engine_matrix(task, dynamic, int8, half, batch):
93
+ """Test YOLO model export to TensorRT format for various configurations and run inference."""
94
+ file = YOLO(TASK2MODEL[task]).export(
95
+ format="engine",
96
+ imgsz=32,
97
+ dynamic=dynamic,
98
+ int8=int8,
99
+ half=half,
100
+ batch=batch,
101
+ data=TASK2DATA[task],
102
+ workspace=1, # reduce workspace GB for less resource utilization during testing
103
+ simplify=True,
104
+ device=DEVICES[0],
105
+ )
106
+ YOLO(file)([SOURCE] * batch, imgsz=64 if dynamic else 32, device=DEVICES[0]) # exported model inference
107
+ Path(file).unlink() # cleanup
108
+ Path(file).with_suffix(".cache").unlink(missing_ok=True) if int8 else None # cleanup INT8 cache
109
+
110
+
111
+ @pytest.mark.skipif(not DEVICES, reason="No CUDA devices available")
112
+ def test_train():
113
+ """Test model training on a minimal dataset using available CUDA devices."""
114
+ device = tuple(DEVICES) if len(DEVICES) > 1 else DEVICES[0]
115
+ # NVIDIA Jetson only has one GPU and therefore skipping checks
116
+ if not IS_JETSON:
117
+ results = YOLO(MODEL).train(data="coco8.yaml", imgsz=64, epochs=1, device=device, batch=15)
118
+ results = YOLO(MODEL).train(data="coco128.yaml", imgsz=64, epochs=1, device=device, batch=15, val=False)
119
+ visible = eval(os.environ["CUDA_VISIBLE_DEVICES"])
120
+ assert visible == device, f"Passed GPUs '{device}', but used GPUs '{visible}'"
121
+ # Note DDP training returns None, single-GPU returns metrics
122
+ assert (results is None) if len(DEVICES) > 1 else (results is not None)
123
+
124
+
125
+ @pytest.mark.slow
126
+ @pytest.mark.skipif(not DEVICES, reason="No CUDA devices available")
127
+ def test_predict_multiple_devices():
128
+ """Validate model prediction consistency across CPU and CUDA devices."""
129
+ model = YOLO("yolo11n.pt")
130
+
131
+ # Test CPU
132
+ model = model.cpu()
133
+ assert str(model.device) == "cpu"
134
+ _ = model(SOURCE)
135
+ assert str(model.device) == "cpu"
136
+
137
+ # Test CUDA
138
+ cuda_device = f"cuda:{DEVICES[0]}"
139
+ model = model.to(cuda_device)
140
+ assert str(model.device) == cuda_device
141
+ _ = model(SOURCE)
142
+ assert str(model.device) == cuda_device
143
+
144
+ # Test CPU again
145
+ model = model.cpu()
146
+ assert str(model.device) == "cpu"
147
+ _ = model(SOURCE)
148
+ assert str(model.device) == "cpu"
149
+
150
+ # Test CUDA again
151
+ model = model.to(cuda_device)
152
+ assert str(model.device) == cuda_device
153
+ _ = model(SOURCE)
154
+ assert str(model.device) == cuda_device
155
+
156
+
157
+ @pytest.mark.skipif(not DEVICES, reason="No CUDA devices available")
158
+ def test_autobatch():
159
+ """Check optimal batch size for YOLO model training using autobatch utility."""
160
+ from ultralytics.utils.autobatch import check_train_batch_size
161
+
162
+ check_train_batch_size(YOLO(MODEL).model.to(f"cuda:{DEVICES[0]}"), imgsz=128, amp=True)
163
+
164
+
165
+ @pytest.mark.slow
166
+ @pytest.mark.skipif(not DEVICES, reason="No CUDA devices available")
167
+ def test_utils_benchmarks():
168
+ """Profile YOLO models for performance benchmarks."""
169
+ from ultralytics.utils.benchmarks import ProfileModels
170
+
171
+ # Pre-export a dynamic engine model to use dynamic inference
172
+ YOLO(MODEL).export(format="engine", imgsz=32, dynamic=True, batch=1, device=DEVICES[0])
173
+ ProfileModels(
174
+ [MODEL],
175
+ imgsz=32,
176
+ half=False,
177
+ min_time=1,
178
+ num_timed_runs=3,
179
+ num_warmup_runs=1,
180
+ device=DEVICES[0],
181
+ ).run()
182
+
183
+
184
+ @pytest.mark.skipif(not DEVICES, reason="No CUDA devices available")
185
+ def test_predict_sam():
186
+ """Test SAM model predictions using different prompts."""
187
+ from ultralytics import SAM
188
+ from ultralytics.models.sam import Predictor as SAMPredictor
189
+
190
+ model = SAM(WEIGHTS_DIR / "sam2.1_b.pt")
191
+ model.info()
192
+
193
+ # Run inference with various prompts
194
+ model(SOURCE, device=DEVICES[0])
195
+ model(SOURCE, bboxes=[439, 437, 524, 709], device=DEVICES[0])
196
+ model(ASSETS / "zidane.jpg", points=[900, 370], device=DEVICES[0])
197
+ model(ASSETS / "zidane.jpg", points=[900, 370], labels=[1], device=DEVICES[0])
198
+ model(ASSETS / "zidane.jpg", points=[[900, 370]], labels=[1], device=DEVICES[0])
199
+ model(ASSETS / "zidane.jpg", points=[[400, 370], [900, 370]], labels=[1, 1], device=DEVICES[0])
200
+ model(ASSETS / "zidane.jpg", points=[[[900, 370], [1000, 100]]], labels=[[1, 1]], device=DEVICES[0])
201
+
202
+ # Test predictor
203
+ predictor = SAMPredictor(
204
+ overrides=dict(
205
+ conf=0.25,
206
+ task="segment",
207
+ mode="predict",
208
+ imgsz=1024,
209
+ model=WEIGHTS_DIR / "mobile_sam.pt",
210
+ device=DEVICES[0],
211
+ )
212
+ )
213
+ predictor.set_image(ASSETS / "zidane.jpg")
214
+ # predictor(bboxes=[439, 437, 524, 709])
215
+ # predictor(points=[900, 370], labels=[1])
216
+ predictor.reset_image()
tests/test_engine.py ADDED
@@ -0,0 +1,157 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ import sys
4
+ from unittest import mock
5
+
6
+ import torch
7
+
8
+ from tests import MODEL
9
+ from ultralytics import YOLO
10
+ from ultralytics.cfg import get_cfg
11
+ from ultralytics.engine.exporter import Exporter
12
+ from ultralytics.models.yolo import classify, detect, segment
13
+ from ultralytics.utils import ASSETS, DEFAULT_CFG, WEIGHTS_DIR
14
+
15
+
16
+ def test_func(*args, **kwargs):
17
+ """Test function callback for evaluating YOLO model performance metrics."""
18
+ print("callback test passed")
19
+
20
+
21
+ def test_export():
22
+ """Test model exporting functionality by adding a callback and verifying its execution."""
23
+ exporter = Exporter()
24
+ exporter.add_callback("on_export_start", test_func)
25
+ assert test_func in exporter.callbacks["on_export_start"], "callback test failed"
26
+ f = exporter(model=YOLO("yolo11n.yaml").model)
27
+ YOLO(f)(ASSETS) # exported model inference
28
+
29
+
30
+ def test_detect():
31
+ """Test YOLO object detection training, validation, and prediction functionality."""
32
+ overrides = {"data": "coco8.yaml", "model": "yolo11n.yaml", "imgsz": 32, "epochs": 1, "save": False}
33
+ cfg = get_cfg(DEFAULT_CFG)
34
+ cfg.data = "coco8.yaml"
35
+ cfg.imgsz = 32
36
+
37
+ # Trainer
38
+ trainer = detect.DetectionTrainer(overrides=overrides)
39
+ trainer.add_callback("on_train_start", test_func)
40
+ assert test_func in trainer.callbacks["on_train_start"], "callback test failed"
41
+ trainer.train()
42
+
43
+ # Validator
44
+ val = detect.DetectionValidator(args=cfg)
45
+ val.add_callback("on_val_start", test_func)
46
+ assert test_func in val.callbacks["on_val_start"], "callback test failed"
47
+ val(model=trainer.best) # validate best.pt
48
+
49
+ # Predictor
50
+ pred = detect.DetectionPredictor(overrides={"imgsz": [64, 64]})
51
+ pred.add_callback("on_predict_start", test_func)
52
+ assert test_func in pred.callbacks["on_predict_start"], "callback test failed"
53
+ # Confirm there is no issue with sys.argv being empty
54
+ with mock.patch.object(sys, "argv", []):
55
+ result = pred(source=ASSETS, model=MODEL)
56
+ assert len(result), "predictor test failed"
57
+
58
+ # Test resume functionality
59
+ overrides["resume"] = trainer.last
60
+ trainer = detect.DetectionTrainer(overrides=overrides)
61
+ try:
62
+ trainer.train()
63
+ except Exception as e:
64
+ print(f"Expected exception caught: {e}")
65
+ return
66
+
67
+ raise Exception("Resume test failed!")
68
+
69
+
70
+ def test_segment():
71
+ """Test image segmentation training, validation, and prediction pipelines using YOLO models."""
72
+ overrides = {
73
+ "data": "coco8-seg.yaml",
74
+ "model": "yolo11n-seg.yaml",
75
+ "imgsz": 32,
76
+ "epochs": 1,
77
+ "save": False,
78
+ "mask_ratio": 1,
79
+ "overlap_mask": False,
80
+ }
81
+ cfg = get_cfg(DEFAULT_CFG)
82
+ cfg.data = "coco8-seg.yaml"
83
+ cfg.imgsz = 32
84
+
85
+ # Trainer
86
+ trainer = segment.SegmentationTrainer(overrides=overrides)
87
+ trainer.add_callback("on_train_start", test_func)
88
+ assert test_func in trainer.callbacks["on_train_start"], "callback test failed"
89
+ trainer.train()
90
+
91
+ # Validator
92
+ val = segment.SegmentationValidator(args=cfg)
93
+ val.add_callback("on_val_start", test_func)
94
+ assert test_func in val.callbacks["on_val_start"], "callback test failed"
95
+ val(model=trainer.best) # validate best.pt
96
+
97
+ # Predictor
98
+ pred = segment.SegmentationPredictor(overrides={"imgsz": [64, 64]})
99
+ pred.add_callback("on_predict_start", test_func)
100
+ assert test_func in pred.callbacks["on_predict_start"], "callback test failed"
101
+ result = pred(source=ASSETS, model=WEIGHTS_DIR / "yolo11n-seg.pt")
102
+ assert len(result), "predictor test failed"
103
+
104
+ # Test resume functionality
105
+ overrides["resume"] = trainer.last
106
+ trainer = segment.SegmentationTrainer(overrides=overrides)
107
+ try:
108
+ trainer.train()
109
+ except Exception as e:
110
+ print(f"Expected exception caught: {e}")
111
+ return
112
+
113
+ raise Exception("Resume test failed!")
114
+
115
+
116
+ def test_classify():
117
+ """Test image classification including training, validation, and prediction phases."""
118
+ overrides = {"data": "imagenet10", "model": "yolo11n-cls.yaml", "imgsz": 32, "epochs": 1, "save": False}
119
+ cfg = get_cfg(DEFAULT_CFG)
120
+ cfg.data = "imagenet10"
121
+ cfg.imgsz = 32
122
+
123
+ # Trainer
124
+ trainer = classify.ClassificationTrainer(overrides=overrides)
125
+ trainer.add_callback("on_train_start", test_func)
126
+ assert test_func in trainer.callbacks["on_train_start"], "callback test failed"
127
+ trainer.train()
128
+
129
+ # Validator
130
+ val = classify.ClassificationValidator(args=cfg)
131
+ val.add_callback("on_val_start", test_func)
132
+ assert test_func in val.callbacks["on_val_start"], "callback test failed"
133
+ val(model=trainer.best)
134
+
135
+ # Predictor
136
+ pred = classify.ClassificationPredictor(overrides={"imgsz": [64, 64]})
137
+ pred.add_callback("on_predict_start", test_func)
138
+ assert test_func in pred.callbacks["on_predict_start"], "callback test failed"
139
+ result = pred(source=ASSETS, model=trainer.best)
140
+ assert len(result), "predictor test failed"
141
+
142
+
143
+ def test_nan_recovery():
144
+ """Test NaN loss detection and recovery during training."""
145
+ nan_injected = [False]
146
+
147
+ def inject_nan(trainer):
148
+ """Inject NaN into loss during batch processing to test recovery mechanism."""
149
+ if trainer.epoch == 1 and trainer.tloss is not None and not nan_injected[0]:
150
+ trainer.tloss *= torch.tensor(float("nan"))
151
+ nan_injected[0] = True
152
+
153
+ overrides = {"data": "coco8.yaml", "model": "yolo11n.yaml", "imgsz": 32, "epochs": 3}
154
+ trainer = detect.DetectionTrainer(overrides=overrides)
155
+ trainer.add_callback("on_train_batch_end", inject_nan)
156
+ trainer.train()
157
+ assert nan_injected[0], "NaN injection failed"