dgenerate-ultralytics-headless 8.3.134__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 (272) hide show
  1. dgenerate_ultralytics_headless-8.3.134.dist-info/METADATA +400 -0
  2. dgenerate_ultralytics_headless-8.3.134.dist-info/RECORD +272 -0
  3. dgenerate_ultralytics_headless-8.3.134.dist-info/WHEEL +5 -0
  4. dgenerate_ultralytics_headless-8.3.134.dist-info/entry_points.txt +3 -0
  5. dgenerate_ultralytics_headless-8.3.134.dist-info/licenses/LICENSE +661 -0
  6. dgenerate_ultralytics_headless-8.3.134.dist-info/top_level.txt +1 -0
  7. tests/__init__.py +22 -0
  8. tests/conftest.py +83 -0
  9. tests/test_cli.py +138 -0
  10. tests/test_cuda.py +215 -0
  11. tests/test_engine.py +131 -0
  12. tests/test_exports.py +236 -0
  13. tests/test_integrations.py +154 -0
  14. tests/test_python.py +694 -0
  15. tests/test_solutions.py +187 -0
  16. ultralytics/__init__.py +30 -0
  17. ultralytics/assets/bus.jpg +0 -0
  18. ultralytics/assets/zidane.jpg +0 -0
  19. ultralytics/cfg/__init__.py +1023 -0
  20. ultralytics/cfg/datasets/Argoverse.yaml +77 -0
  21. ultralytics/cfg/datasets/DOTAv1.5.yaml +37 -0
  22. ultralytics/cfg/datasets/DOTAv1.yaml +36 -0
  23. ultralytics/cfg/datasets/GlobalWheat2020.yaml +68 -0
  24. ultralytics/cfg/datasets/HomeObjects-3K.yaml +33 -0
  25. ultralytics/cfg/datasets/ImageNet.yaml +2025 -0
  26. ultralytics/cfg/datasets/Objects365.yaml +443 -0
  27. ultralytics/cfg/datasets/SKU-110K.yaml +58 -0
  28. ultralytics/cfg/datasets/VOC.yaml +106 -0
  29. ultralytics/cfg/datasets/VisDrone.yaml +77 -0
  30. ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
  31. ultralytics/cfg/datasets/brain-tumor.yaml +23 -0
  32. ultralytics/cfg/datasets/carparts-seg.yaml +44 -0
  33. ultralytics/cfg/datasets/coco-pose.yaml +42 -0
  34. ultralytics/cfg/datasets/coco.yaml +118 -0
  35. ultralytics/cfg/datasets/coco128-seg.yaml +101 -0
  36. ultralytics/cfg/datasets/coco128.yaml +101 -0
  37. ultralytics/cfg/datasets/coco8-multispectral.yaml +104 -0
  38. ultralytics/cfg/datasets/coco8-pose.yaml +26 -0
  39. ultralytics/cfg/datasets/coco8-seg.yaml +101 -0
  40. ultralytics/cfg/datasets/coco8.yaml +101 -0
  41. ultralytics/cfg/datasets/crack-seg.yaml +22 -0
  42. ultralytics/cfg/datasets/dog-pose.yaml +24 -0
  43. ultralytics/cfg/datasets/dota8-multispectral.yaml +38 -0
  44. ultralytics/cfg/datasets/dota8.yaml +35 -0
  45. ultralytics/cfg/datasets/hand-keypoints.yaml +26 -0
  46. ultralytics/cfg/datasets/lvis.yaml +1240 -0
  47. ultralytics/cfg/datasets/medical-pills.yaml +22 -0
  48. ultralytics/cfg/datasets/open-images-v7.yaml +666 -0
  49. ultralytics/cfg/datasets/package-seg.yaml +22 -0
  50. ultralytics/cfg/datasets/signature.yaml +21 -0
  51. ultralytics/cfg/datasets/tiger-pose.yaml +25 -0
  52. ultralytics/cfg/datasets/xView.yaml +155 -0
  53. ultralytics/cfg/default.yaml +127 -0
  54. ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +17 -0
  55. ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
  56. ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
  57. ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
  58. ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
  59. ultralytics/cfg/models/11/yolo11.yaml +50 -0
  60. ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
  61. ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
  62. ultralytics/cfg/models/12/yolo12-cls.yaml +32 -0
  63. ultralytics/cfg/models/12/yolo12-obb.yaml +48 -0
  64. ultralytics/cfg/models/12/yolo12-pose.yaml +49 -0
  65. ultralytics/cfg/models/12/yolo12-seg.yaml +48 -0
  66. ultralytics/cfg/models/12/yolo12.yaml +48 -0
  67. ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +53 -0
  68. ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +45 -0
  69. ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +45 -0
  70. ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +57 -0
  71. ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
  72. ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
  73. ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
  74. ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
  75. ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
  76. ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
  77. ultralytics/cfg/models/v3/yolov3-spp.yaml +49 -0
  78. ultralytics/cfg/models/v3/yolov3-tiny.yaml +40 -0
  79. ultralytics/cfg/models/v3/yolov3.yaml +49 -0
  80. ultralytics/cfg/models/v5/yolov5-p6.yaml +62 -0
  81. ultralytics/cfg/models/v5/yolov5.yaml +51 -0
  82. ultralytics/cfg/models/v6/yolov6.yaml +56 -0
  83. ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +45 -0
  84. ultralytics/cfg/models/v8/yoloe-v8.yaml +45 -0
  85. ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +28 -0
  86. ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +28 -0
  87. ultralytics/cfg/models/v8/yolov8-cls.yaml +32 -0
  88. ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +58 -0
  89. ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +60 -0
  90. ultralytics/cfg/models/v8/yolov8-ghost.yaml +50 -0
  91. ultralytics/cfg/models/v8/yolov8-obb.yaml +49 -0
  92. ultralytics/cfg/models/v8/yolov8-p2.yaml +57 -0
  93. ultralytics/cfg/models/v8/yolov8-p6.yaml +59 -0
  94. ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +60 -0
  95. ultralytics/cfg/models/v8/yolov8-pose.yaml +50 -0
  96. ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +49 -0
  97. ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +59 -0
  98. ultralytics/cfg/models/v8/yolov8-seg.yaml +49 -0
  99. ultralytics/cfg/models/v8/yolov8-world.yaml +51 -0
  100. ultralytics/cfg/models/v8/yolov8-worldv2.yaml +49 -0
  101. ultralytics/cfg/models/v8/yolov8.yaml +49 -0
  102. ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
  103. ultralytics/cfg/models/v9/yolov9c.yaml +41 -0
  104. ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
  105. ultralytics/cfg/models/v9/yolov9e.yaml +64 -0
  106. ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
  107. ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
  108. ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
  109. ultralytics/cfg/trackers/botsort.yaml +22 -0
  110. ultralytics/cfg/trackers/bytetrack.yaml +14 -0
  111. ultralytics/data/__init__.py +26 -0
  112. ultralytics/data/annotator.py +66 -0
  113. ultralytics/data/augment.py +2945 -0
  114. ultralytics/data/base.py +438 -0
  115. ultralytics/data/build.py +258 -0
  116. ultralytics/data/converter.py +754 -0
  117. ultralytics/data/dataset.py +834 -0
  118. ultralytics/data/loaders.py +676 -0
  119. ultralytics/data/scripts/download_weights.sh +18 -0
  120. ultralytics/data/scripts/get_coco.sh +61 -0
  121. ultralytics/data/scripts/get_coco128.sh +18 -0
  122. ultralytics/data/scripts/get_imagenet.sh +52 -0
  123. ultralytics/data/split.py +125 -0
  124. ultralytics/data/split_dota.py +325 -0
  125. ultralytics/data/utils.py +777 -0
  126. ultralytics/engine/__init__.py +1 -0
  127. ultralytics/engine/exporter.py +1519 -0
  128. ultralytics/engine/model.py +1156 -0
  129. ultralytics/engine/predictor.py +502 -0
  130. ultralytics/engine/results.py +1840 -0
  131. ultralytics/engine/trainer.py +853 -0
  132. ultralytics/engine/tuner.py +243 -0
  133. ultralytics/engine/validator.py +377 -0
  134. ultralytics/hub/__init__.py +168 -0
  135. ultralytics/hub/auth.py +137 -0
  136. ultralytics/hub/google/__init__.py +176 -0
  137. ultralytics/hub/session.py +446 -0
  138. ultralytics/hub/utils.py +248 -0
  139. ultralytics/models/__init__.py +9 -0
  140. ultralytics/models/fastsam/__init__.py +7 -0
  141. ultralytics/models/fastsam/model.py +61 -0
  142. ultralytics/models/fastsam/predict.py +181 -0
  143. ultralytics/models/fastsam/utils.py +24 -0
  144. ultralytics/models/fastsam/val.py +40 -0
  145. ultralytics/models/nas/__init__.py +7 -0
  146. ultralytics/models/nas/model.py +102 -0
  147. ultralytics/models/nas/predict.py +58 -0
  148. ultralytics/models/nas/val.py +39 -0
  149. ultralytics/models/rtdetr/__init__.py +7 -0
  150. ultralytics/models/rtdetr/model.py +63 -0
  151. ultralytics/models/rtdetr/predict.py +84 -0
  152. ultralytics/models/rtdetr/train.py +85 -0
  153. ultralytics/models/rtdetr/val.py +191 -0
  154. ultralytics/models/sam/__init__.py +6 -0
  155. ultralytics/models/sam/amg.py +260 -0
  156. ultralytics/models/sam/build.py +358 -0
  157. ultralytics/models/sam/model.py +170 -0
  158. ultralytics/models/sam/modules/__init__.py +1 -0
  159. ultralytics/models/sam/modules/blocks.py +1129 -0
  160. ultralytics/models/sam/modules/decoders.py +515 -0
  161. ultralytics/models/sam/modules/encoders.py +854 -0
  162. ultralytics/models/sam/modules/memory_attention.py +299 -0
  163. ultralytics/models/sam/modules/sam.py +1006 -0
  164. ultralytics/models/sam/modules/tiny_encoder.py +1002 -0
  165. ultralytics/models/sam/modules/transformer.py +351 -0
  166. ultralytics/models/sam/modules/utils.py +394 -0
  167. ultralytics/models/sam/predict.py +1605 -0
  168. ultralytics/models/utils/__init__.py +1 -0
  169. ultralytics/models/utils/loss.py +455 -0
  170. ultralytics/models/utils/ops.py +268 -0
  171. ultralytics/models/yolo/__init__.py +7 -0
  172. ultralytics/models/yolo/classify/__init__.py +7 -0
  173. ultralytics/models/yolo/classify/predict.py +88 -0
  174. ultralytics/models/yolo/classify/train.py +233 -0
  175. ultralytics/models/yolo/classify/val.py +215 -0
  176. ultralytics/models/yolo/detect/__init__.py +7 -0
  177. ultralytics/models/yolo/detect/predict.py +124 -0
  178. ultralytics/models/yolo/detect/train.py +217 -0
  179. ultralytics/models/yolo/detect/val.py +451 -0
  180. ultralytics/models/yolo/model.py +354 -0
  181. ultralytics/models/yolo/obb/__init__.py +7 -0
  182. ultralytics/models/yolo/obb/predict.py +66 -0
  183. ultralytics/models/yolo/obb/train.py +81 -0
  184. ultralytics/models/yolo/obb/val.py +283 -0
  185. ultralytics/models/yolo/pose/__init__.py +7 -0
  186. ultralytics/models/yolo/pose/predict.py +79 -0
  187. ultralytics/models/yolo/pose/train.py +154 -0
  188. ultralytics/models/yolo/pose/val.py +394 -0
  189. ultralytics/models/yolo/segment/__init__.py +7 -0
  190. ultralytics/models/yolo/segment/predict.py +113 -0
  191. ultralytics/models/yolo/segment/train.py +123 -0
  192. ultralytics/models/yolo/segment/val.py +428 -0
  193. ultralytics/models/yolo/world/__init__.py +5 -0
  194. ultralytics/models/yolo/world/train.py +119 -0
  195. ultralytics/models/yolo/world/train_world.py +176 -0
  196. ultralytics/models/yolo/yoloe/__init__.py +22 -0
  197. ultralytics/models/yolo/yoloe/predict.py +169 -0
  198. ultralytics/models/yolo/yoloe/train.py +298 -0
  199. ultralytics/models/yolo/yoloe/train_seg.py +124 -0
  200. ultralytics/models/yolo/yoloe/val.py +191 -0
  201. ultralytics/nn/__init__.py +29 -0
  202. ultralytics/nn/autobackend.py +842 -0
  203. ultralytics/nn/modules/__init__.py +182 -0
  204. ultralytics/nn/modules/activation.py +53 -0
  205. ultralytics/nn/modules/block.py +1966 -0
  206. ultralytics/nn/modules/conv.py +712 -0
  207. ultralytics/nn/modules/head.py +880 -0
  208. ultralytics/nn/modules/transformer.py +713 -0
  209. ultralytics/nn/modules/utils.py +164 -0
  210. ultralytics/nn/tasks.py +1627 -0
  211. ultralytics/nn/text_model.py +351 -0
  212. ultralytics/solutions/__init__.py +41 -0
  213. ultralytics/solutions/ai_gym.py +116 -0
  214. ultralytics/solutions/analytics.py +252 -0
  215. ultralytics/solutions/config.py +106 -0
  216. ultralytics/solutions/distance_calculation.py +124 -0
  217. ultralytics/solutions/heatmap.py +127 -0
  218. ultralytics/solutions/instance_segmentation.py +84 -0
  219. ultralytics/solutions/object_blurrer.py +90 -0
  220. ultralytics/solutions/object_counter.py +195 -0
  221. ultralytics/solutions/object_cropper.py +84 -0
  222. ultralytics/solutions/parking_management.py +273 -0
  223. ultralytics/solutions/queue_management.py +93 -0
  224. ultralytics/solutions/region_counter.py +120 -0
  225. ultralytics/solutions/security_alarm.py +154 -0
  226. ultralytics/solutions/similarity_search.py +172 -0
  227. ultralytics/solutions/solutions.py +724 -0
  228. ultralytics/solutions/speed_estimation.py +110 -0
  229. ultralytics/solutions/streamlit_inference.py +196 -0
  230. ultralytics/solutions/templates/similarity-search.html +160 -0
  231. ultralytics/solutions/trackzone.py +88 -0
  232. ultralytics/solutions/vision_eye.py +68 -0
  233. ultralytics/trackers/__init__.py +7 -0
  234. ultralytics/trackers/basetrack.py +124 -0
  235. ultralytics/trackers/bot_sort.py +260 -0
  236. ultralytics/trackers/byte_tracker.py +480 -0
  237. ultralytics/trackers/track.py +125 -0
  238. ultralytics/trackers/utils/__init__.py +1 -0
  239. ultralytics/trackers/utils/gmc.py +376 -0
  240. ultralytics/trackers/utils/kalman_filter.py +493 -0
  241. ultralytics/trackers/utils/matching.py +157 -0
  242. ultralytics/utils/__init__.py +1435 -0
  243. ultralytics/utils/autobatch.py +106 -0
  244. ultralytics/utils/autodevice.py +174 -0
  245. ultralytics/utils/benchmarks.py +695 -0
  246. ultralytics/utils/callbacks/__init__.py +5 -0
  247. ultralytics/utils/callbacks/base.py +234 -0
  248. ultralytics/utils/callbacks/clearml.py +153 -0
  249. ultralytics/utils/callbacks/comet.py +552 -0
  250. ultralytics/utils/callbacks/dvc.py +205 -0
  251. ultralytics/utils/callbacks/hub.py +108 -0
  252. ultralytics/utils/callbacks/mlflow.py +138 -0
  253. ultralytics/utils/callbacks/neptune.py +140 -0
  254. ultralytics/utils/callbacks/raytune.py +43 -0
  255. ultralytics/utils/callbacks/tensorboard.py +132 -0
  256. ultralytics/utils/callbacks/wb.py +185 -0
  257. ultralytics/utils/checks.py +897 -0
  258. ultralytics/utils/dist.py +119 -0
  259. ultralytics/utils/downloads.py +499 -0
  260. ultralytics/utils/errors.py +43 -0
  261. ultralytics/utils/export.py +219 -0
  262. ultralytics/utils/files.py +221 -0
  263. ultralytics/utils/instance.py +499 -0
  264. ultralytics/utils/loss.py +813 -0
  265. ultralytics/utils/metrics.py +1356 -0
  266. ultralytics/utils/ops.py +885 -0
  267. ultralytics/utils/patches.py +143 -0
  268. ultralytics/utils/plotting.py +1011 -0
  269. ultralytics/utils/tal.py +416 -0
  270. ultralytics/utils/torch_utils.py +990 -0
  271. ultralytics/utils/triton.py +116 -0
  272. ultralytics/utils/tuner.py +159 -0
@@ -0,0 +1,897 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ import glob
4
+ import inspect
5
+ import math
6
+ import os
7
+ import platform
8
+ import re
9
+ import shutil
10
+ import subprocess
11
+ import time
12
+ from importlib import metadata
13
+ from pathlib import Path
14
+ from types import SimpleNamespace
15
+ from typing import Optional
16
+
17
+ import cv2
18
+ import numpy as np
19
+ import torch
20
+
21
+ from ultralytics.utils import (
22
+ ARM64,
23
+ ASSETS,
24
+ AUTOINSTALL,
25
+ IS_COLAB,
26
+ IS_GIT_DIR,
27
+ IS_JETSON,
28
+ IS_KAGGLE,
29
+ IS_PIP_PACKAGE,
30
+ LINUX,
31
+ LOGGER,
32
+ MACOS,
33
+ ONLINE,
34
+ PYTHON_VERSION,
35
+ RKNN_CHIPS,
36
+ ROOT,
37
+ TORCHVISION_VERSION,
38
+ USER_CONFIG_DIR,
39
+ WINDOWS,
40
+ Retry,
41
+ ThreadingLocked,
42
+ TryExcept,
43
+ clean_url,
44
+ colorstr,
45
+ downloads,
46
+ is_github_action_running,
47
+ url2file,
48
+ )
49
+
50
+
51
+ def parse_requirements(file_path=ROOT.parent / "requirements.txt", package=""):
52
+ """
53
+ Parse a requirements.txt file, ignoring lines that start with '#' and any text after '#'.
54
+
55
+ Args:
56
+ file_path (Path): Path to the requirements.txt file.
57
+ package (str, optional): Python package to use instead of requirements.txt file.
58
+
59
+ Returns:
60
+ (List[SimpleNamespace]): List of parsed requirements as SimpleNamespace objects with `name` and `specifier` attributes.
61
+
62
+ Examples:
63
+ >>> from ultralytics.utils.checks import parse_requirements
64
+ >>> parse_requirements(package="ultralytics")
65
+ """
66
+ if package:
67
+ requires = [x for x in metadata.distribution(package).requires if "extra == " not in x]
68
+ else:
69
+ requires = Path(file_path).read_text().splitlines()
70
+
71
+ requirements = []
72
+ for line in requires:
73
+ line = line.strip()
74
+ if line and not line.startswith("#"):
75
+ line = line.split("#")[0].strip() # ignore inline comments
76
+ if match := re.match(r"([a-zA-Z0-9-_]+)\s*([<>!=~]+.*)?", line):
77
+ requirements.append(SimpleNamespace(name=match[1], specifier=match[2].strip() if match[2] else ""))
78
+
79
+ return requirements
80
+
81
+
82
+ def parse_version(version="0.0.0") -> tuple:
83
+ """
84
+ Convert a version string to a tuple of integers, ignoring any extra non-numeric string attached to the version.
85
+
86
+ Args:
87
+ version (str): Version string, i.e. '2.0.1+cpu'
88
+
89
+ Returns:
90
+ (Tuple[int, int, int]): Tuple of integers representing the numeric part of the version, i.e. (2, 0, 1)
91
+ """
92
+ try:
93
+ return tuple(map(int, re.findall(r"\d+", version)[:3])) # '2.0.1+cpu' -> (2, 0, 1)
94
+ except Exception as e:
95
+ LOGGER.warning(f"failure for parse_version({version}), returning (0, 0, 0): {e}")
96
+ return 0, 0, 0
97
+
98
+
99
+ def is_ascii(s) -> bool:
100
+ """
101
+ Check if a string is composed of only ASCII characters.
102
+
103
+ Args:
104
+ s (str | list | tuple | dict): Input to be checked (all are converted to string for checking).
105
+
106
+ Returns:
107
+ (bool): True if the string is composed only of ASCII characters, False otherwise.
108
+ """
109
+ return all(ord(c) < 128 for c in str(s))
110
+
111
+
112
+ def check_imgsz(imgsz, stride=32, min_dim=1, max_dim=2, floor=0):
113
+ """
114
+ Verify image size is a multiple of the given stride in each dimension. If the image size is not a multiple of the
115
+ stride, update it to the nearest multiple of the stride that is greater than or equal to the given floor value.
116
+
117
+ Args:
118
+ imgsz (int | List[int]): Image size.
119
+ stride (int): Stride value.
120
+ min_dim (int): Minimum number of dimensions.
121
+ max_dim (int): Maximum number of dimensions.
122
+ floor (int): Minimum allowed value for image size.
123
+
124
+ Returns:
125
+ (List[int] | int): Updated image size.
126
+ """
127
+ # Convert stride to integer if it is a tensor
128
+ stride = int(stride.max() if isinstance(stride, torch.Tensor) else stride)
129
+
130
+ # Convert image size to list if it is an integer
131
+ if isinstance(imgsz, int):
132
+ imgsz = [imgsz]
133
+ elif isinstance(imgsz, (list, tuple)):
134
+ imgsz = list(imgsz)
135
+ elif isinstance(imgsz, str): # i.e. '640' or '[640,640]'
136
+ imgsz = [int(imgsz)] if imgsz.isnumeric() else eval(imgsz)
137
+ else:
138
+ raise TypeError(
139
+ f"'imgsz={imgsz}' is of invalid type {type(imgsz).__name__}. "
140
+ f"Valid imgsz types are int i.e. 'imgsz=640' or list i.e. 'imgsz=[640,640]'"
141
+ )
142
+
143
+ # Apply max_dim
144
+ if len(imgsz) > max_dim:
145
+ msg = (
146
+ "'train' and 'val' imgsz must be an integer, while 'predict' and 'export' imgsz may be a [h, w] list "
147
+ "or an integer, i.e. 'yolo export imgsz=640,480' or 'yolo export imgsz=640'"
148
+ )
149
+ if max_dim != 1:
150
+ raise ValueError(f"imgsz={imgsz} is not a valid image size. {msg}")
151
+ LOGGER.warning(f"updating to 'imgsz={max(imgsz)}'. {msg}")
152
+ imgsz = [max(imgsz)]
153
+ # Make image size a multiple of the stride
154
+ sz = [max(math.ceil(x / stride) * stride, floor) for x in imgsz]
155
+
156
+ # Print warning message if image size was updated
157
+ if sz != imgsz:
158
+ LOGGER.warning(f"imgsz={imgsz} must be multiple of max stride {stride}, updating to {sz}")
159
+
160
+ # Add missing dimensions if necessary
161
+ sz = [sz[0], sz[0]] if min_dim == 2 and len(sz) == 1 else sz[0] if min_dim == 1 and len(sz) == 1 else sz
162
+
163
+ return sz
164
+
165
+
166
+ def check_version(
167
+ current: str = "0.0.0",
168
+ required: str = "0.0.0",
169
+ name: str = "version",
170
+ hard: bool = False,
171
+ verbose: bool = False,
172
+ msg: str = "",
173
+ ) -> bool:
174
+ """
175
+ Check current version against the required version or range.
176
+
177
+ Args:
178
+ current (str): Current version or package name to get version from.
179
+ required (str): Required version or range (in pip-style format).
180
+ name (str): Name to be used in warning message.
181
+ hard (bool): If True, raise an AssertionError if the requirement is not met.
182
+ verbose (bool): If True, print warning message if requirement is not met.
183
+ msg (str): Extra message to display if verbose.
184
+
185
+ Returns:
186
+ (bool): True if requirement is met, False otherwise.
187
+
188
+ Examples:
189
+ Check if current version is exactly 22.04
190
+ >>> check_version(current="22.04", required="==22.04")
191
+
192
+ Check if current version is greater than or equal to 22.04
193
+ >>> check_version(current="22.10", required="22.04") # assumes '>=' inequality if none passed
194
+
195
+ Check if current version is less than or equal to 22.04
196
+ >>> check_version(current="22.04", required="<=22.04")
197
+
198
+ Check if current version is between 20.04 (inclusive) and 22.04 (exclusive)
199
+ >>> check_version(current="21.10", required=">20.04,<22.04")
200
+ """
201
+ if not current: # if current is '' or None
202
+ LOGGER.warning(f"invalid check_version({current}, {required}) requested, please check values.")
203
+ return True
204
+ elif not current[0].isdigit(): # current is package name rather than version string, i.e. current='ultralytics'
205
+ try:
206
+ name = current # assigned package name to 'name' arg
207
+ current = metadata.version(current) # get version string from package name
208
+ except metadata.PackageNotFoundError as e:
209
+ if hard:
210
+ raise ModuleNotFoundError(f"{current} package is required but not installed") from e
211
+ else:
212
+ return False
213
+
214
+ if not required: # if required is '' or None
215
+ return True
216
+
217
+ if "sys_platform" in required and ( # i.e. required='<2.4.0,>=1.8.0; sys_platform == "win32"'
218
+ (WINDOWS and "win32" not in required)
219
+ or (LINUX and "linux" not in required)
220
+ or (MACOS and "macos" not in required and "darwin" not in required)
221
+ ):
222
+ return True
223
+
224
+ op = ""
225
+ version = ""
226
+ result = True
227
+ c = parse_version(current) # '1.2.3' -> (1, 2, 3)
228
+ for r in required.strip(",").split(","):
229
+ op, version = re.match(r"([^0-9]*)([\d.]+)", r).groups() # split '>=22.04' -> ('>=', '22.04')
230
+ if not op:
231
+ op = ">=" # assume >= if no op passed
232
+ v = parse_version(version) # '1.2.3' -> (1, 2, 3)
233
+ if op == "==" and c != v:
234
+ result = False
235
+ elif op == "!=" and c == v:
236
+ result = False
237
+ elif op == ">=" and not (c >= v):
238
+ result = False
239
+ elif op == "<=" and not (c <= v):
240
+ result = False
241
+ elif op == ">" and not (c > v):
242
+ result = False
243
+ elif op == "<" and not (c < v):
244
+ result = False
245
+ if not result:
246
+ warning = f"{name}{required} is required, but {name}=={current} is currently installed {msg}"
247
+ if hard:
248
+ raise ModuleNotFoundError(warning) # assert version requirements met
249
+ if verbose:
250
+ LOGGER.warning(warning)
251
+ return result
252
+
253
+
254
+ def check_latest_pypi_version(package_name="ultralytics"):
255
+ """
256
+ Returns the latest version of a PyPI package without downloading or installing it.
257
+
258
+ Args:
259
+ package_name (str): The name of the package to find the latest version for.
260
+
261
+ Returns:
262
+ (str): The latest version of the package.
263
+ """
264
+ import requests # slow import
265
+
266
+ try:
267
+ requests.packages.urllib3.disable_warnings() # Disable the InsecureRequestWarning
268
+ response = requests.get(f"https://pypi.org/pypi/{package_name}/json", timeout=3)
269
+ if response.status_code == 200:
270
+ return response.json()["info"]["version"]
271
+ except Exception:
272
+ return None
273
+
274
+
275
+ def check_pip_update_available():
276
+ """
277
+ Checks if a new version of the ultralytics package is available on PyPI.
278
+
279
+ Returns:
280
+ (bool): True if an update is available, False otherwise.
281
+ """
282
+ if ONLINE and IS_PIP_PACKAGE:
283
+ try:
284
+ from ultralytics import __version__
285
+
286
+ latest = check_latest_pypi_version()
287
+ if check_version(__version__, f"<{latest}"): # check if current version is < latest version
288
+ LOGGER.info(
289
+ f"New https://pypi.org/project/ultralytics/{latest} available 😃 "
290
+ f"Update with 'pip install -U ultralytics'"
291
+ )
292
+ return True
293
+ except Exception:
294
+ pass
295
+ return False
296
+
297
+
298
+ @ThreadingLocked()
299
+ def check_font(font="Arial.ttf"):
300
+ """
301
+ Find font locally or download to user's configuration directory if it does not already exist.
302
+
303
+ Args:
304
+ font (str): Path or name of font.
305
+
306
+ Returns:
307
+ (Path): Resolved font file path.
308
+ """
309
+ from matplotlib import font_manager # scope for faster 'import ultralytics'
310
+
311
+ # Check USER_CONFIG_DIR
312
+ name = Path(font).name
313
+ file = USER_CONFIG_DIR / name
314
+ if file.exists():
315
+ return file
316
+
317
+ # Check system fonts
318
+ matches = [s for s in font_manager.findSystemFonts() if font in s]
319
+ if any(matches):
320
+ return matches[0]
321
+
322
+ # Download to USER_CONFIG_DIR if missing
323
+ url = f"https://github.com/ultralytics/assets/releases/download/v0.0.0/{name}"
324
+ if downloads.is_url(url, check=True):
325
+ downloads.safe_download(url=url, file=file)
326
+ return file
327
+
328
+
329
+ def check_python(minimum: str = "3.8.0", hard: bool = True, verbose: bool = False) -> bool:
330
+ """
331
+ Check current python version against the required minimum version.
332
+
333
+ Args:
334
+ minimum (str): Required minimum version of python.
335
+ hard (bool): If True, raise an AssertionError if the requirement is not met.
336
+ verbose (bool): If True, print warning message if requirement is not met.
337
+
338
+ Returns:
339
+ (bool): Whether the installed Python version meets the minimum constraints.
340
+ """
341
+ return check_version(PYTHON_VERSION, minimum, name="Python", hard=hard, verbose=verbose)
342
+
343
+
344
+ @TryExcept()
345
+ def check_requirements(requirements=ROOT.parent / "requirements.txt", exclude=(), install=True, cmds=""):
346
+ """
347
+ Check if installed dependencies meet Ultralytics YOLO models requirements and attempt to auto-update if needed.
348
+
349
+ Args:
350
+ requirements (Union[Path, str, List[str]]): Path to a requirements.txt file, a single package requirement as a
351
+ string, or a list of package requirements as strings.
352
+ exclude (Tuple[str]): Tuple of package names to exclude from checking.
353
+ install (bool): If True, attempt to auto-update packages that don't meet requirements.
354
+ cmds (str): Additional commands to pass to the pip install command when auto-updating.
355
+
356
+ Examples:
357
+ >>> from ultralytics.utils.checks import check_requirements
358
+
359
+ Check a requirements.txt file
360
+ >>> check_requirements("path/to/requirements.txt")
361
+
362
+ Check a single package
363
+ >>> check_requirements("ultralytics>=8.0.0")
364
+
365
+ Check multiple packages
366
+ >>> check_requirements(["numpy", "ultralytics>=8.0.0"])
367
+ """
368
+ prefix = colorstr("red", "bold", "requirements:")
369
+ if isinstance(requirements, Path): # requirements.txt file
370
+ file = requirements.resolve()
371
+ assert file.exists(), f"{prefix} {file} not found, check failed."
372
+ requirements = [f"{x.name}{x.specifier}" for x in parse_requirements(file) if x.name not in exclude]
373
+ elif isinstance(requirements, str):
374
+ requirements = [requirements]
375
+
376
+ pkgs = []
377
+ for r in requirements:
378
+ r_stripped = r.split("/")[-1].replace(".git", "") # replace git+https://org/repo.git -> 'repo'
379
+ match = re.match(r"([a-zA-Z0-9-_]+)([<>!=~]+.*)?", r_stripped)
380
+ name, required = match[1], match[2].strip() if match[2] else ""
381
+ try:
382
+ assert check_version(metadata.version(name), required) # exception if requirements not met
383
+ except (AssertionError, metadata.PackageNotFoundError):
384
+ pkgs.append(r)
385
+
386
+ @Retry(times=2, delay=1)
387
+ def attempt_install(packages, commands):
388
+ """Attempt pip install command with retries on failure."""
389
+ return subprocess.check_output(f"pip install --no-cache-dir {packages} {commands}", shell=True).decode()
390
+
391
+ s = " ".join(f'"{x}"' for x in pkgs) # console string
392
+ if s:
393
+ if install and AUTOINSTALL: # check environment variable
394
+ n = len(pkgs) # number of packages updates
395
+ LOGGER.info(f"{prefix} Ultralytics requirement{'s' * (n > 1)} {pkgs} not found, attempting AutoUpdate...")
396
+ try:
397
+ t = time.time()
398
+ assert ONLINE, "AutoUpdate skipped (offline)"
399
+ LOGGER.info(attempt_install(s, cmds))
400
+ dt = time.time() - t
401
+ LOGGER.info(f"{prefix} AutoUpdate success ✅ {dt:.1f}s, installed {n} package{'s' * (n > 1)}: {pkgs}")
402
+ LOGGER.warning(
403
+ f"{prefix} {colorstr('bold', 'Restart runtime or rerun command for updates to take effect')}\n"
404
+ )
405
+ except Exception as e:
406
+ LOGGER.warning(f"{prefix} ❌ {e}")
407
+ return False
408
+ else:
409
+ return False
410
+
411
+ return True
412
+
413
+
414
+ def check_torchvision():
415
+ """
416
+ Checks the installed versions of PyTorch and Torchvision to ensure they're compatible.
417
+
418
+ This function checks the installed versions of PyTorch and Torchvision, and warns if they're incompatible according
419
+ to the compatibility table based on: https://github.com/pytorch/vision#installation.
420
+ """
421
+ compatibility_table = {
422
+ "2.6": ["0.21"],
423
+ "2.5": ["0.20"],
424
+ "2.4": ["0.19"],
425
+ "2.3": ["0.18"],
426
+ "2.2": ["0.17"],
427
+ "2.1": ["0.16"],
428
+ "2.0": ["0.15"],
429
+ "1.13": ["0.14"],
430
+ "1.12": ["0.13"],
431
+ }
432
+
433
+ # Check major and minor versions
434
+ v_torch = ".".join(torch.__version__.split("+")[0].split(".")[:2])
435
+ if v_torch in compatibility_table:
436
+ compatible_versions = compatibility_table[v_torch]
437
+ v_torchvision = ".".join(TORCHVISION_VERSION.split("+")[0].split(".")[:2])
438
+ if all(v_torchvision != v for v in compatible_versions):
439
+ LOGGER.warning(
440
+ f"torchvision=={v_torchvision} is incompatible with torch=={v_torch}.\n"
441
+ f"Run 'pip install torchvision=={compatible_versions[0]}' to fix torchvision or "
442
+ "'pip install -U torch torchvision' to update both.\n"
443
+ "For a full compatibility table see https://github.com/pytorch/vision#installation"
444
+ )
445
+
446
+
447
+ def check_suffix(file="yolo11n.pt", suffix=".pt", msg=""):
448
+ """
449
+ Check file(s) for acceptable suffix.
450
+
451
+ Args:
452
+ file (str | List[str]): File or list of files to check.
453
+ suffix (str | Tuple[str]): Acceptable suffix or tuple of suffixes.
454
+ msg (str): Additional message to display in case of error.
455
+ """
456
+ if file and suffix:
457
+ if isinstance(suffix, str):
458
+ suffix = {suffix}
459
+ for f in file if isinstance(file, (list, tuple)) else [file]:
460
+ s = Path(f).suffix.lower().strip() # file suffix
461
+ if len(s):
462
+ assert s in suffix, f"{msg}{f} acceptable suffix is {suffix}, not {s}"
463
+
464
+
465
+ def check_yolov5u_filename(file: str, verbose: bool = True):
466
+ """
467
+ Replace legacy YOLOv5 filenames with updated YOLOv5u filenames.
468
+
469
+ Args:
470
+ file (str): Filename to check and potentially update.
471
+ verbose (bool): Whether to print information about the replacement.
472
+
473
+ Returns:
474
+ (str): Updated filename.
475
+ """
476
+ if "yolov3" in file or "yolov5" in file:
477
+ if "u.yaml" in file:
478
+ file = file.replace("u.yaml", ".yaml") # i.e. yolov5nu.yaml -> yolov5n.yaml
479
+ elif ".pt" in file and "u" not in file:
480
+ original_file = file
481
+ file = re.sub(r"(.*yolov5([nsmlx]))\.pt", "\\1u.pt", file) # i.e. yolov5n.pt -> yolov5nu.pt
482
+ file = re.sub(r"(.*yolov5([nsmlx])6)\.pt", "\\1u.pt", file) # i.e. yolov5n6.pt -> yolov5n6u.pt
483
+ file = re.sub(r"(.*yolov3(|-tiny|-spp))\.pt", "\\1u.pt", file) # i.e. yolov3-spp.pt -> yolov3-sppu.pt
484
+ if file != original_file and verbose:
485
+ LOGGER.info(
486
+ f"PRO TIP 💡 Replace 'model={original_file}' with new 'model={file}'.\nYOLOv5 'u' models are "
487
+ f"trained with https://github.com/ultralytics/ultralytics and feature improved performance vs "
488
+ f"standard YOLOv5 models trained with https://github.com/ultralytics/yolov5.\n"
489
+ )
490
+ return file
491
+
492
+
493
+ def check_model_file_from_stem(model="yolo11n"):
494
+ """
495
+ Return a model filename from a valid model stem.
496
+
497
+ Args:
498
+ model (str): Model stem to check.
499
+
500
+ Returns:
501
+ (str | Path): Model filename with appropriate suffix.
502
+ """
503
+ if model and not Path(model).suffix and Path(model).stem in downloads.GITHUB_ASSETS_STEMS:
504
+ return Path(model).with_suffix(".pt") # add suffix, i.e. yolo11n -> yolo11n.pt
505
+ else:
506
+ return model
507
+
508
+
509
+ def check_file(file, suffix="", download=True, download_dir=".", hard=True):
510
+ """
511
+ Search/download file (if necessary), check suffix (if provided), and return path.
512
+
513
+ Args:
514
+ file (str): File name or path.
515
+ suffix (str | Tuple[str]): Acceptable suffix or tuple of suffixes to validate against the file.
516
+ download (bool): Whether to download the file if it doesn't exist locally.
517
+ download_dir (str): Directory to download the file to.
518
+ hard (bool): Whether to raise an error if the file is not found.
519
+
520
+ Returns:
521
+ (str): Path to the file.
522
+ """
523
+ check_suffix(file, suffix) # optional
524
+ file = str(file).strip() # convert to string and strip spaces
525
+ file = check_yolov5u_filename(file) # yolov5n -> yolov5nu
526
+ if (
527
+ not file
528
+ or ("://" not in file and Path(file).exists()) # '://' check required in Windows Python<3.10
529
+ or file.lower().startswith("grpc://")
530
+ ): # file exists or gRPC Triton images
531
+ return file
532
+ elif download and file.lower().startswith(("https://", "http://", "rtsp://", "rtmp://", "tcp://")): # download
533
+ url = file # warning: Pathlib turns :// -> :/
534
+ file = Path(download_dir) / url2file(file) # '%2F' to '/', split https://url.com/file.txt?auth
535
+ if file.exists():
536
+ LOGGER.info(f"Found {clean_url(url)} locally at {file}") # file already exists
537
+ else:
538
+ downloads.safe_download(url=url, file=file, unzip=False)
539
+ return str(file)
540
+ else: # search
541
+ files = glob.glob(str(ROOT / "**" / file), recursive=True) or glob.glob(str(ROOT.parent / file)) # find file
542
+ if not files and hard:
543
+ raise FileNotFoundError(f"'{file}' does not exist")
544
+ elif len(files) > 1 and hard:
545
+ raise FileNotFoundError(f"Multiple files match '{file}', specify exact path: {files}")
546
+ return files[0] if len(files) else [] # return file
547
+
548
+
549
+ def check_yaml(file, suffix=(".yaml", ".yml"), hard=True):
550
+ """
551
+ Search/download YAML file (if necessary) and return path, checking suffix.
552
+
553
+ Args:
554
+ file (str | Path): File name or path.
555
+ suffix (Tuple[str]): Tuple of acceptable YAML file suffixes.
556
+ hard (bool): Whether to raise an error if the file is not found or multiple files are found.
557
+
558
+ Returns:
559
+ (str): Path to the YAML file.
560
+ """
561
+ return check_file(file, suffix, hard=hard)
562
+
563
+
564
+ def check_is_path_safe(basedir, path):
565
+ """
566
+ Check if the resolved path is under the intended directory to prevent path traversal.
567
+
568
+ Args:
569
+ basedir (Path | str): The intended directory.
570
+ path (Path | str): The path to check.
571
+
572
+ Returns:
573
+ (bool): True if the path is safe, False otherwise.
574
+ """
575
+ base_dir_resolved = Path(basedir).resolve()
576
+ path_resolved = Path(path).resolve()
577
+
578
+ return path_resolved.exists() and path_resolved.parts[: len(base_dir_resolved.parts)] == base_dir_resolved.parts
579
+
580
+
581
+ def check_imshow(warn=False):
582
+ """
583
+ Check if environment supports image displays.
584
+
585
+ Args:
586
+ warn (bool): Whether to warn if environment doesn't support image displays.
587
+
588
+ Returns:
589
+ (bool): True if environment supports image displays, False otherwise.
590
+ """
591
+ try:
592
+ if LINUX:
593
+ assert not IS_COLAB and not IS_KAGGLE
594
+ assert "DISPLAY" in os.environ, "The DISPLAY environment variable isn't set."
595
+ cv2.imshow("test", np.zeros((8, 8, 3), dtype=np.uint8)) # show a small 8-pixel image
596
+ cv2.waitKey(1)
597
+ cv2.destroyAllWindows()
598
+ cv2.waitKey(1)
599
+ return True
600
+ except Exception as e:
601
+ if warn:
602
+ LOGGER.warning(f"Environment does not support cv2.imshow() or PIL Image.show()\n{e}")
603
+ return False
604
+
605
+
606
+ def check_yolo(verbose=True, device=""):
607
+ """
608
+ Return a human-readable YOLO software and hardware summary.
609
+
610
+ Args:
611
+ verbose (bool): Whether to print verbose information.
612
+ device (str | torch.device): Device to use for YOLO.
613
+ """
614
+ import psutil
615
+
616
+ from ultralytics.utils.torch_utils import select_device
617
+
618
+ if IS_COLAB:
619
+ shutil.rmtree("sample_data", ignore_errors=True) # remove colab /sample_data directory
620
+
621
+ if verbose:
622
+ # System info
623
+ gib = 1 << 30 # bytes per GiB
624
+ ram = psutil.virtual_memory().total
625
+ total, used, free = shutil.disk_usage("/")
626
+ s = f"({os.cpu_count()} CPUs, {ram / gib:.1f} GB RAM, {(total - free) / gib:.1f}/{total / gib:.1f} GB disk)"
627
+ try:
628
+ from IPython import display
629
+
630
+ display.clear_output() # clear display if notebook
631
+ except ImportError:
632
+ pass
633
+ else:
634
+ s = ""
635
+
636
+ select_device(device=device, newline=False)
637
+ LOGGER.info(f"Setup complete ✅ {s}")
638
+
639
+
640
+ def collect_system_info():
641
+ """
642
+ Collect and print relevant system information including OS, Python, RAM, CPU, and CUDA.
643
+
644
+ Returns:
645
+ (dict): Dictionary containing system information.
646
+ """
647
+ import psutil
648
+
649
+ from ultralytics.utils import ENVIRONMENT # scope to avoid circular import
650
+ from ultralytics.utils.torch_utils import get_cpu_info, get_gpu_info
651
+
652
+ gib = 1 << 30 # bytes per GiB
653
+ cuda = torch and torch.cuda.is_available()
654
+ check_yolo()
655
+ total, used, free = shutil.disk_usage("/")
656
+
657
+ info_dict = {
658
+ "OS": platform.platform(),
659
+ "Environment": ENVIRONMENT,
660
+ "Python": PYTHON_VERSION,
661
+ "Install": "git" if IS_GIT_DIR else "pip" if IS_PIP_PACKAGE else "other",
662
+ "Path": str(ROOT),
663
+ "RAM": f"{psutil.virtual_memory().total / gib:.2f} GB",
664
+ "Disk": f"{(total - free) / gib:.1f}/{total / gib:.1f} GB",
665
+ "CPU": get_cpu_info(),
666
+ "CPU count": os.cpu_count(),
667
+ "GPU": get_gpu_info(index=0) if cuda else None,
668
+ "GPU count": torch.cuda.device_count() if cuda else None,
669
+ "CUDA": torch.version.cuda if cuda else None,
670
+ }
671
+ LOGGER.info("\n" + "\n".join(f"{k:<20}{v}" for k, v in info_dict.items()) + "\n")
672
+
673
+ package_info = {}
674
+ for r in parse_requirements(package="ultralytics"):
675
+ try:
676
+ current = metadata.version(r.name)
677
+ is_met = "✅ " if check_version(current, str(r.specifier), name=r.name, hard=True) else "❌ "
678
+ except metadata.PackageNotFoundError:
679
+ current = "(not installed)"
680
+ is_met = "❌ "
681
+ package_info[r.name] = f"{is_met}{current}{r.specifier}"
682
+ LOGGER.info(f"{r.name:<20}{package_info[r.name]}")
683
+
684
+ info_dict["Package Info"] = package_info
685
+
686
+ if is_github_action_running():
687
+ github_info = {
688
+ "RUNNER_OS": os.getenv("RUNNER_OS"),
689
+ "GITHUB_EVENT_NAME": os.getenv("GITHUB_EVENT_NAME"),
690
+ "GITHUB_WORKFLOW": os.getenv("GITHUB_WORKFLOW"),
691
+ "GITHUB_ACTOR": os.getenv("GITHUB_ACTOR"),
692
+ "GITHUB_REPOSITORY": os.getenv("GITHUB_REPOSITORY"),
693
+ "GITHUB_REPOSITORY_OWNER": os.getenv("GITHUB_REPOSITORY_OWNER"),
694
+ }
695
+ LOGGER.info("\n" + "\n".join(f"{k}: {v}" for k, v in github_info.items()))
696
+ info_dict["GitHub Info"] = github_info
697
+
698
+ return info_dict
699
+
700
+
701
+ def check_amp(model):
702
+ """
703
+ Checks the PyTorch Automatic Mixed Precision (AMP) functionality of a YOLO11 model.
704
+
705
+ If the checks fail, it means there are anomalies with AMP on the system that may cause NaN losses or zero-mAP
706
+ results, so AMP will be disabled during training.
707
+
708
+ Args:
709
+ model (nn.Module): A YOLO11 model instance.
710
+
711
+ Returns:
712
+ (bool): Returns True if the AMP functionality works correctly with YOLO11 model, else False.
713
+
714
+ Examples:
715
+ >>> from ultralytics import YOLO
716
+ >>> from ultralytics.utils.checks import check_amp
717
+ >>> model = YOLO("yolo11n.pt").model.cuda()
718
+ >>> check_amp(model)
719
+ """
720
+ from ultralytics.utils.torch_utils import autocast
721
+
722
+ device = next(model.parameters()).device # get model device
723
+ prefix = colorstr("AMP: ")
724
+ if device.type in {"cpu", "mps"}:
725
+ return False # AMP only used on CUDA devices
726
+ else:
727
+ # GPUs that have issues with AMP
728
+ pattern = re.compile(
729
+ r"(nvidia|geforce|quadro|tesla).*?(1660|1650|1630|t400|t550|t600|t1000|t1200|t2000|k40m)", re.IGNORECASE
730
+ )
731
+
732
+ gpu = torch.cuda.get_device_name(device)
733
+ if bool(pattern.search(gpu)):
734
+ LOGGER.warning(
735
+ f"{prefix}checks failed ❌. AMP training on {gpu} GPU may cause "
736
+ f"NaN losses or zero-mAP results, so AMP will be disabled during training."
737
+ )
738
+ return False
739
+
740
+ def amp_allclose(m, im):
741
+ """All close FP32 vs AMP results."""
742
+ batch = [im] * 8
743
+ imgsz = max(256, int(model.stride.max() * 4)) # max stride P5-32 and P6-64
744
+ a = m(batch, imgsz=imgsz, device=device, verbose=False)[0].boxes.data # FP32 inference
745
+ with autocast(enabled=True):
746
+ b = m(batch, imgsz=imgsz, device=device, verbose=False)[0].boxes.data # AMP inference
747
+ del m
748
+ return a.shape == b.shape and torch.allclose(a, b.float(), atol=0.5) # close to 0.5 absolute tolerance
749
+
750
+ im = ASSETS / "bus.jpg" # image to check
751
+ LOGGER.info(f"{prefix}running Automatic Mixed Precision (AMP) checks...")
752
+ warning_msg = "Setting 'amp=True'. If you experience zero-mAP or NaN losses you can disable AMP with amp=False."
753
+ try:
754
+ from ultralytics import YOLO
755
+
756
+ assert amp_allclose(YOLO("yolo11n.pt"), im)
757
+ LOGGER.info(f"{prefix}checks passed ✅")
758
+ except ConnectionError:
759
+ LOGGER.warning(f"{prefix}checks skipped. Offline and unable to download YOLO11n for AMP checks. {warning_msg}")
760
+ except (AttributeError, ModuleNotFoundError):
761
+ LOGGER.warning(
762
+ f"{prefix}checks skipped. "
763
+ f"Unable to load YOLO11n for AMP checks due to possible Ultralytics package modifications. {warning_msg}"
764
+ )
765
+ except AssertionError:
766
+ LOGGER.error(
767
+ f"{prefix}checks failed. Anomalies were detected with AMP on your system that may lead to "
768
+ f"NaN losses or zero-mAP results, so AMP will be disabled during training."
769
+ )
770
+ return False
771
+ return True
772
+
773
+
774
+ def git_describe(path=ROOT): # path must be a directory
775
+ """
776
+ Return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe.
777
+
778
+ Args:
779
+ path (Path): Path to git repository.
780
+
781
+ Returns:
782
+ (str): Human-readable git description.
783
+ """
784
+ try:
785
+ return subprocess.check_output(f"git -C {path} describe --tags --long --always", shell=True).decode()[:-1]
786
+ except Exception:
787
+ return ""
788
+
789
+
790
+ def print_args(args: Optional[dict] = None, show_file=True, show_func=False):
791
+ """
792
+ Print function arguments (optional args dict).
793
+
794
+ Args:
795
+ args (dict, optional): Arguments to print.
796
+ show_file (bool): Whether to show the file name.
797
+ show_func (bool): Whether to show the function name.
798
+ """
799
+
800
+ def strip_auth(v):
801
+ """Clean longer Ultralytics HUB URLs by stripping potential authentication information."""
802
+ return clean_url(v) if (isinstance(v, str) and v.startswith("http") and len(v) > 100) else v
803
+
804
+ x = inspect.currentframe().f_back # previous frame
805
+ file, _, func, _, _ = inspect.getframeinfo(x)
806
+ if args is None: # get args automatically
807
+ args, _, _, frm = inspect.getargvalues(x)
808
+ args = {k: v for k, v in frm.items() if k in args}
809
+ try:
810
+ file = Path(file).resolve().relative_to(ROOT).with_suffix("")
811
+ except ValueError:
812
+ file = Path(file).stem
813
+ s = (f"{file}: " if show_file else "") + (f"{func}: " if show_func else "")
814
+ LOGGER.info(colorstr(s) + ", ".join(f"{k}={strip_auth(v)}" for k, v in sorted(args.items())))
815
+
816
+
817
+ def cuda_device_count() -> int:
818
+ """
819
+ Get the number of NVIDIA GPUs available in the environment.
820
+
821
+ Returns:
822
+ (int): The number of NVIDIA GPUs available.
823
+ """
824
+ if IS_JETSON:
825
+ # NVIDIA Jetson does not fully support nvidia-smi and therefore use PyTorch instead
826
+ return torch.cuda.device_count()
827
+ else:
828
+ try:
829
+ # Run the nvidia-smi command and capture its output
830
+ output = subprocess.check_output(
831
+ ["nvidia-smi", "--query-gpu=count", "--format=csv,noheader,nounits"], encoding="utf-8"
832
+ )
833
+
834
+ # Take the first line and strip any leading/trailing white space
835
+ first_line = output.strip().split("\n")[0]
836
+
837
+ return int(first_line)
838
+ except (subprocess.CalledProcessError, FileNotFoundError, ValueError):
839
+ # If the command fails, nvidia-smi is not found, or output is not an integer, assume no GPUs are available
840
+ return 0
841
+
842
+
843
+ def cuda_is_available() -> bool:
844
+ """
845
+ Check if CUDA is available in the environment.
846
+
847
+ Returns:
848
+ (bool): True if one or more NVIDIA GPUs are available, False otherwise.
849
+ """
850
+ return cuda_device_count() > 0
851
+
852
+
853
+ def is_rockchip():
854
+ """
855
+ Check if the current environment is running on a Rockchip SoC.
856
+
857
+ Returns:
858
+ (bool): True if running on a Rockchip SoC, False otherwise.
859
+ """
860
+ if LINUX and ARM64:
861
+ try:
862
+ with open("/proc/device-tree/compatible") as f:
863
+ dev_str = f.read()
864
+ *_, soc = dev_str.split(",")
865
+ if soc.replace("\x00", "") in RKNN_CHIPS:
866
+ return True
867
+ except OSError:
868
+ return False
869
+ else:
870
+ return False
871
+
872
+
873
+ def is_sudo_available() -> bool:
874
+ """
875
+ Check if the sudo command is available in the environment.
876
+
877
+ Returns:
878
+ (bool): True if the sudo command is available, False otherwise.
879
+ """
880
+ if WINDOWS:
881
+ return False
882
+ cmd = "sudo --version"
883
+ return subprocess.run(cmd, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
884
+
885
+
886
+ # Run checks and define constants
887
+ check_python("3.8", hard=False, verbose=True) # check python version
888
+ check_torchvision() # check torch-torchvision compatibility
889
+
890
+ # Define constants
891
+ IS_PYTHON_3_8 = PYTHON_VERSION.startswith("3.8")
892
+ IS_PYTHON_3_11 = PYTHON_VERSION.startswith("3.11")
893
+ IS_PYTHON_3_12 = PYTHON_VERSION.startswith("3.12")
894
+ IS_PYTHON_3_13 = PYTHON_VERSION.startswith("3.13")
895
+
896
+ IS_PYTHON_MINIMUM_3_10 = check_python("3.10", hard=False)
897
+ IS_PYTHON_MINIMUM_3_12 = check_python("3.12", hard=False)