ultralytics-opencv-headless 8.3.246__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (298) hide show
  1. tests/__init__.py +23 -0
  2. tests/conftest.py +59 -0
  3. tests/test_cli.py +131 -0
  4. tests/test_cuda.py +216 -0
  5. tests/test_engine.py +157 -0
  6. tests/test_exports.py +309 -0
  7. tests/test_integrations.py +151 -0
  8. tests/test_python.py +777 -0
  9. tests/test_solutions.py +371 -0
  10. ultralytics/__init__.py +48 -0
  11. ultralytics/assets/bus.jpg +0 -0
  12. ultralytics/assets/zidane.jpg +0 -0
  13. ultralytics/cfg/__init__.py +1026 -0
  14. ultralytics/cfg/datasets/Argoverse.yaml +78 -0
  15. ultralytics/cfg/datasets/DOTAv1.5.yaml +37 -0
  16. ultralytics/cfg/datasets/DOTAv1.yaml +36 -0
  17. ultralytics/cfg/datasets/GlobalWheat2020.yaml +68 -0
  18. ultralytics/cfg/datasets/HomeObjects-3K.yaml +32 -0
  19. ultralytics/cfg/datasets/ImageNet.yaml +2025 -0
  20. ultralytics/cfg/datasets/Objects365.yaml +447 -0
  21. ultralytics/cfg/datasets/SKU-110K.yaml +58 -0
  22. ultralytics/cfg/datasets/VOC.yaml +102 -0
  23. ultralytics/cfg/datasets/VisDrone.yaml +87 -0
  24. ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
  25. ultralytics/cfg/datasets/brain-tumor.yaml +22 -0
  26. ultralytics/cfg/datasets/carparts-seg.yaml +44 -0
  27. ultralytics/cfg/datasets/coco-pose.yaml +64 -0
  28. ultralytics/cfg/datasets/coco.yaml +118 -0
  29. ultralytics/cfg/datasets/coco128-seg.yaml +101 -0
  30. ultralytics/cfg/datasets/coco128.yaml +101 -0
  31. ultralytics/cfg/datasets/coco8-grayscale.yaml +103 -0
  32. ultralytics/cfg/datasets/coco8-multispectral.yaml +104 -0
  33. ultralytics/cfg/datasets/coco8-pose.yaml +47 -0
  34. ultralytics/cfg/datasets/coco8-seg.yaml +101 -0
  35. ultralytics/cfg/datasets/coco8.yaml +101 -0
  36. ultralytics/cfg/datasets/construction-ppe.yaml +32 -0
  37. ultralytics/cfg/datasets/crack-seg.yaml +22 -0
  38. ultralytics/cfg/datasets/dog-pose.yaml +52 -0
  39. ultralytics/cfg/datasets/dota8-multispectral.yaml +38 -0
  40. ultralytics/cfg/datasets/dota8.yaml +35 -0
  41. ultralytics/cfg/datasets/hand-keypoints.yaml +50 -0
  42. ultralytics/cfg/datasets/kitti.yaml +27 -0
  43. ultralytics/cfg/datasets/lvis.yaml +1240 -0
  44. ultralytics/cfg/datasets/medical-pills.yaml +21 -0
  45. ultralytics/cfg/datasets/open-images-v7.yaml +663 -0
  46. ultralytics/cfg/datasets/package-seg.yaml +22 -0
  47. ultralytics/cfg/datasets/signature.yaml +21 -0
  48. ultralytics/cfg/datasets/tiger-pose.yaml +41 -0
  49. ultralytics/cfg/datasets/xView.yaml +155 -0
  50. ultralytics/cfg/default.yaml +130 -0
  51. ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +17 -0
  52. ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
  53. ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
  54. ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
  55. ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
  56. ultralytics/cfg/models/11/yolo11.yaml +50 -0
  57. ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
  58. ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
  59. ultralytics/cfg/models/12/yolo12-cls.yaml +32 -0
  60. ultralytics/cfg/models/12/yolo12-obb.yaml +48 -0
  61. ultralytics/cfg/models/12/yolo12-pose.yaml +49 -0
  62. ultralytics/cfg/models/12/yolo12-seg.yaml +48 -0
  63. ultralytics/cfg/models/12/yolo12.yaml +48 -0
  64. ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +53 -0
  65. ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +45 -0
  66. ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +45 -0
  67. ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +57 -0
  68. ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
  69. ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
  70. ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
  71. ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
  72. ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
  73. ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
  74. ultralytics/cfg/models/v3/yolov3-spp.yaml +49 -0
  75. ultralytics/cfg/models/v3/yolov3-tiny.yaml +40 -0
  76. ultralytics/cfg/models/v3/yolov3.yaml +49 -0
  77. ultralytics/cfg/models/v5/yolov5-p6.yaml +62 -0
  78. ultralytics/cfg/models/v5/yolov5.yaml +51 -0
  79. ultralytics/cfg/models/v6/yolov6.yaml +56 -0
  80. ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +48 -0
  81. ultralytics/cfg/models/v8/yoloe-v8.yaml +48 -0
  82. ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +28 -0
  83. ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +28 -0
  84. ultralytics/cfg/models/v8/yolov8-cls.yaml +32 -0
  85. ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +58 -0
  86. ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +60 -0
  87. ultralytics/cfg/models/v8/yolov8-ghost.yaml +50 -0
  88. ultralytics/cfg/models/v8/yolov8-obb.yaml +49 -0
  89. ultralytics/cfg/models/v8/yolov8-p2.yaml +57 -0
  90. ultralytics/cfg/models/v8/yolov8-p6.yaml +59 -0
  91. ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +60 -0
  92. ultralytics/cfg/models/v8/yolov8-pose.yaml +50 -0
  93. ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +49 -0
  94. ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +59 -0
  95. ultralytics/cfg/models/v8/yolov8-seg.yaml +49 -0
  96. ultralytics/cfg/models/v8/yolov8-world.yaml +51 -0
  97. ultralytics/cfg/models/v8/yolov8-worldv2.yaml +49 -0
  98. ultralytics/cfg/models/v8/yolov8.yaml +49 -0
  99. ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
  100. ultralytics/cfg/models/v9/yolov9c.yaml +41 -0
  101. ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
  102. ultralytics/cfg/models/v9/yolov9e.yaml +64 -0
  103. ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
  104. ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
  105. ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
  106. ultralytics/cfg/trackers/botsort.yaml +21 -0
  107. ultralytics/cfg/trackers/bytetrack.yaml +12 -0
  108. ultralytics/data/__init__.py +26 -0
  109. ultralytics/data/annotator.py +66 -0
  110. ultralytics/data/augment.py +2801 -0
  111. ultralytics/data/base.py +435 -0
  112. ultralytics/data/build.py +437 -0
  113. ultralytics/data/converter.py +855 -0
  114. ultralytics/data/dataset.py +834 -0
  115. ultralytics/data/loaders.py +704 -0
  116. ultralytics/data/scripts/download_weights.sh +18 -0
  117. ultralytics/data/scripts/get_coco.sh +61 -0
  118. ultralytics/data/scripts/get_coco128.sh +18 -0
  119. ultralytics/data/scripts/get_imagenet.sh +52 -0
  120. ultralytics/data/split.py +138 -0
  121. ultralytics/data/split_dota.py +344 -0
  122. ultralytics/data/utils.py +798 -0
  123. ultralytics/engine/__init__.py +1 -0
  124. ultralytics/engine/exporter.py +1578 -0
  125. ultralytics/engine/model.py +1124 -0
  126. ultralytics/engine/predictor.py +508 -0
  127. ultralytics/engine/results.py +1522 -0
  128. ultralytics/engine/trainer.py +974 -0
  129. ultralytics/engine/tuner.py +448 -0
  130. ultralytics/engine/validator.py +384 -0
  131. ultralytics/hub/__init__.py +166 -0
  132. ultralytics/hub/auth.py +151 -0
  133. ultralytics/hub/google/__init__.py +174 -0
  134. ultralytics/hub/session.py +422 -0
  135. ultralytics/hub/utils.py +162 -0
  136. ultralytics/models/__init__.py +9 -0
  137. ultralytics/models/fastsam/__init__.py +7 -0
  138. ultralytics/models/fastsam/model.py +79 -0
  139. ultralytics/models/fastsam/predict.py +169 -0
  140. ultralytics/models/fastsam/utils.py +23 -0
  141. ultralytics/models/fastsam/val.py +38 -0
  142. ultralytics/models/nas/__init__.py +7 -0
  143. ultralytics/models/nas/model.py +98 -0
  144. ultralytics/models/nas/predict.py +56 -0
  145. ultralytics/models/nas/val.py +38 -0
  146. ultralytics/models/rtdetr/__init__.py +7 -0
  147. ultralytics/models/rtdetr/model.py +63 -0
  148. ultralytics/models/rtdetr/predict.py +88 -0
  149. ultralytics/models/rtdetr/train.py +89 -0
  150. ultralytics/models/rtdetr/val.py +216 -0
  151. ultralytics/models/sam/__init__.py +25 -0
  152. ultralytics/models/sam/amg.py +275 -0
  153. ultralytics/models/sam/build.py +365 -0
  154. ultralytics/models/sam/build_sam3.py +377 -0
  155. ultralytics/models/sam/model.py +169 -0
  156. ultralytics/models/sam/modules/__init__.py +1 -0
  157. ultralytics/models/sam/modules/blocks.py +1067 -0
  158. ultralytics/models/sam/modules/decoders.py +495 -0
  159. ultralytics/models/sam/modules/encoders.py +794 -0
  160. ultralytics/models/sam/modules/memory_attention.py +298 -0
  161. ultralytics/models/sam/modules/sam.py +1160 -0
  162. ultralytics/models/sam/modules/tiny_encoder.py +979 -0
  163. ultralytics/models/sam/modules/transformer.py +344 -0
  164. ultralytics/models/sam/modules/utils.py +512 -0
  165. ultralytics/models/sam/predict.py +3940 -0
  166. ultralytics/models/sam/sam3/__init__.py +3 -0
  167. ultralytics/models/sam/sam3/decoder.py +546 -0
  168. ultralytics/models/sam/sam3/encoder.py +529 -0
  169. ultralytics/models/sam/sam3/geometry_encoders.py +415 -0
  170. ultralytics/models/sam/sam3/maskformer_segmentation.py +286 -0
  171. ultralytics/models/sam/sam3/model_misc.py +199 -0
  172. ultralytics/models/sam/sam3/necks.py +129 -0
  173. ultralytics/models/sam/sam3/sam3_image.py +339 -0
  174. ultralytics/models/sam/sam3/text_encoder_ve.py +307 -0
  175. ultralytics/models/sam/sam3/vitdet.py +547 -0
  176. ultralytics/models/sam/sam3/vl_combiner.py +160 -0
  177. ultralytics/models/utils/__init__.py +1 -0
  178. ultralytics/models/utils/loss.py +466 -0
  179. ultralytics/models/utils/ops.py +315 -0
  180. ultralytics/models/yolo/__init__.py +7 -0
  181. ultralytics/models/yolo/classify/__init__.py +7 -0
  182. ultralytics/models/yolo/classify/predict.py +90 -0
  183. ultralytics/models/yolo/classify/train.py +202 -0
  184. ultralytics/models/yolo/classify/val.py +216 -0
  185. ultralytics/models/yolo/detect/__init__.py +7 -0
  186. ultralytics/models/yolo/detect/predict.py +122 -0
  187. ultralytics/models/yolo/detect/train.py +227 -0
  188. ultralytics/models/yolo/detect/val.py +507 -0
  189. ultralytics/models/yolo/model.py +430 -0
  190. ultralytics/models/yolo/obb/__init__.py +7 -0
  191. ultralytics/models/yolo/obb/predict.py +56 -0
  192. ultralytics/models/yolo/obb/train.py +79 -0
  193. ultralytics/models/yolo/obb/val.py +302 -0
  194. ultralytics/models/yolo/pose/__init__.py +7 -0
  195. ultralytics/models/yolo/pose/predict.py +65 -0
  196. ultralytics/models/yolo/pose/train.py +110 -0
  197. ultralytics/models/yolo/pose/val.py +248 -0
  198. ultralytics/models/yolo/segment/__init__.py +7 -0
  199. ultralytics/models/yolo/segment/predict.py +109 -0
  200. ultralytics/models/yolo/segment/train.py +69 -0
  201. ultralytics/models/yolo/segment/val.py +307 -0
  202. ultralytics/models/yolo/world/__init__.py +5 -0
  203. ultralytics/models/yolo/world/train.py +173 -0
  204. ultralytics/models/yolo/world/train_world.py +178 -0
  205. ultralytics/models/yolo/yoloe/__init__.py +22 -0
  206. ultralytics/models/yolo/yoloe/predict.py +162 -0
  207. ultralytics/models/yolo/yoloe/train.py +287 -0
  208. ultralytics/models/yolo/yoloe/train_seg.py +122 -0
  209. ultralytics/models/yolo/yoloe/val.py +206 -0
  210. ultralytics/nn/__init__.py +27 -0
  211. ultralytics/nn/autobackend.py +958 -0
  212. ultralytics/nn/modules/__init__.py +182 -0
  213. ultralytics/nn/modules/activation.py +54 -0
  214. ultralytics/nn/modules/block.py +1947 -0
  215. ultralytics/nn/modules/conv.py +669 -0
  216. ultralytics/nn/modules/head.py +1183 -0
  217. ultralytics/nn/modules/transformer.py +793 -0
  218. ultralytics/nn/modules/utils.py +159 -0
  219. ultralytics/nn/tasks.py +1768 -0
  220. ultralytics/nn/text_model.py +356 -0
  221. ultralytics/py.typed +1 -0
  222. ultralytics/solutions/__init__.py +41 -0
  223. ultralytics/solutions/ai_gym.py +108 -0
  224. ultralytics/solutions/analytics.py +264 -0
  225. ultralytics/solutions/config.py +107 -0
  226. ultralytics/solutions/distance_calculation.py +123 -0
  227. ultralytics/solutions/heatmap.py +125 -0
  228. ultralytics/solutions/instance_segmentation.py +86 -0
  229. ultralytics/solutions/object_blurrer.py +89 -0
  230. ultralytics/solutions/object_counter.py +190 -0
  231. ultralytics/solutions/object_cropper.py +87 -0
  232. ultralytics/solutions/parking_management.py +280 -0
  233. ultralytics/solutions/queue_management.py +93 -0
  234. ultralytics/solutions/region_counter.py +133 -0
  235. ultralytics/solutions/security_alarm.py +151 -0
  236. ultralytics/solutions/similarity_search.py +219 -0
  237. ultralytics/solutions/solutions.py +828 -0
  238. ultralytics/solutions/speed_estimation.py +114 -0
  239. ultralytics/solutions/streamlit_inference.py +260 -0
  240. ultralytics/solutions/templates/similarity-search.html +156 -0
  241. ultralytics/solutions/trackzone.py +88 -0
  242. ultralytics/solutions/vision_eye.py +67 -0
  243. ultralytics/trackers/__init__.py +7 -0
  244. ultralytics/trackers/basetrack.py +115 -0
  245. ultralytics/trackers/bot_sort.py +257 -0
  246. ultralytics/trackers/byte_tracker.py +469 -0
  247. ultralytics/trackers/track.py +116 -0
  248. ultralytics/trackers/utils/__init__.py +1 -0
  249. ultralytics/trackers/utils/gmc.py +339 -0
  250. ultralytics/trackers/utils/kalman_filter.py +482 -0
  251. ultralytics/trackers/utils/matching.py +154 -0
  252. ultralytics/utils/__init__.py +1450 -0
  253. ultralytics/utils/autobatch.py +118 -0
  254. ultralytics/utils/autodevice.py +205 -0
  255. ultralytics/utils/benchmarks.py +728 -0
  256. ultralytics/utils/callbacks/__init__.py +5 -0
  257. ultralytics/utils/callbacks/base.py +233 -0
  258. ultralytics/utils/callbacks/clearml.py +146 -0
  259. ultralytics/utils/callbacks/comet.py +625 -0
  260. ultralytics/utils/callbacks/dvc.py +197 -0
  261. ultralytics/utils/callbacks/hub.py +110 -0
  262. ultralytics/utils/callbacks/mlflow.py +134 -0
  263. ultralytics/utils/callbacks/neptune.py +126 -0
  264. ultralytics/utils/callbacks/platform.py +313 -0
  265. ultralytics/utils/callbacks/raytune.py +42 -0
  266. ultralytics/utils/callbacks/tensorboard.py +123 -0
  267. ultralytics/utils/callbacks/wb.py +188 -0
  268. ultralytics/utils/checks.py +1006 -0
  269. ultralytics/utils/cpu.py +85 -0
  270. ultralytics/utils/dist.py +123 -0
  271. ultralytics/utils/downloads.py +529 -0
  272. ultralytics/utils/errors.py +35 -0
  273. ultralytics/utils/events.py +113 -0
  274. ultralytics/utils/export/__init__.py +7 -0
  275. ultralytics/utils/export/engine.py +237 -0
  276. ultralytics/utils/export/imx.py +315 -0
  277. ultralytics/utils/export/tensorflow.py +231 -0
  278. ultralytics/utils/files.py +219 -0
  279. ultralytics/utils/git.py +137 -0
  280. ultralytics/utils/instance.py +484 -0
  281. ultralytics/utils/logger.py +501 -0
  282. ultralytics/utils/loss.py +849 -0
  283. ultralytics/utils/metrics.py +1563 -0
  284. ultralytics/utils/nms.py +337 -0
  285. ultralytics/utils/ops.py +664 -0
  286. ultralytics/utils/patches.py +201 -0
  287. ultralytics/utils/plotting.py +1045 -0
  288. ultralytics/utils/tal.py +403 -0
  289. ultralytics/utils/torch_utils.py +984 -0
  290. ultralytics/utils/tqdm.py +440 -0
  291. ultralytics/utils/triton.py +112 -0
  292. ultralytics/utils/tuner.py +160 -0
  293. ultralytics_opencv_headless-8.3.246.dist-info/METADATA +374 -0
  294. ultralytics_opencv_headless-8.3.246.dist-info/RECORD +298 -0
  295. ultralytics_opencv_headless-8.3.246.dist-info/WHEEL +5 -0
  296. ultralytics_opencv_headless-8.3.246.dist-info/entry_points.txt +3 -0
  297. ultralytics_opencv_headless-8.3.246.dist-info/licenses/LICENSE +661 -0
  298. ultralytics_opencv_headless-8.3.246.dist-info/top_level.txt +1 -0
@@ -0,0 +1,197 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ from pathlib import Path
4
+
5
+ from ultralytics.utils import LOGGER, SETTINGS, TESTS_RUNNING, checks
6
+
7
+ try:
8
+ assert not TESTS_RUNNING # do not log pytest
9
+ assert SETTINGS["dvc"] is True # verify integration is enabled
10
+ import dvclive
11
+
12
+ assert checks.check_version("dvclive", "2.11.0", verbose=True)
13
+
14
+ import os
15
+ import re
16
+
17
+ # DVCLive logger instance
18
+ live = None
19
+ _processed_plots = {}
20
+
21
+ # `on_fit_epoch_end` is called on final validation (probably need to be fixed) for now this is the way we
22
+ # distinguish final evaluation of the best model vs last epoch validation
23
+ _training_epoch = False
24
+
25
+ except (ImportError, AssertionError, TypeError):
26
+ dvclive = None
27
+
28
+
29
+ def _log_images(path: Path, prefix: str = "") -> None:
30
+ """Log images at specified path with an optional prefix using DVCLive.
31
+
32
+ This function logs images found at the given path to DVCLive, organizing them by batch to enable slider
33
+ functionality in the UI. It processes image filenames to extract batch information and restructures the path
34
+ accordingly.
35
+
36
+ Args:
37
+ path (Path): Path to the image file to be logged.
38
+ prefix (str, optional): Optional prefix to add to the image name when logging.
39
+
40
+ Examples:
41
+ >>> from pathlib import Path
42
+ >>> _log_images(Path("runs/train/exp/val_batch0_pred.jpg"), prefix="validation")
43
+ """
44
+ if live:
45
+ name = path.name
46
+
47
+ # Group images by batch to enable sliders in UI
48
+ if m := re.search(r"_batch(\d+)", name):
49
+ ni = m[1]
50
+ new_stem = re.sub(r"_batch(\d+)", "_batch", path.stem)
51
+ name = (Path(new_stem) / ni).with_suffix(path.suffix)
52
+
53
+ live.log_image(os.path.join(prefix, name), path)
54
+
55
+
56
+ def _log_plots(plots: dict, prefix: str = "") -> None:
57
+ """Log plot images for training progress if they have not been previously processed.
58
+
59
+ Args:
60
+ plots (dict): Dictionary containing plot information with timestamps.
61
+ prefix (str, optional): Optional prefix to add to the logged image paths.
62
+ """
63
+ for name, params in plots.items():
64
+ timestamp = params["timestamp"]
65
+ if _processed_plots.get(name) != timestamp:
66
+ _log_images(name, prefix)
67
+ _processed_plots[name] = timestamp
68
+
69
+
70
+ def _log_confusion_matrix(validator) -> None:
71
+ """Log confusion matrix for a validator using DVCLive.
72
+
73
+ This function processes the confusion matrix from a validator object and logs it to DVCLive by converting the matrix
74
+ into lists of target and prediction labels.
75
+
76
+ Args:
77
+ validator (BaseValidator): The validator object containing the confusion matrix and class names. Must have
78
+ attributes confusion_matrix.matrix, confusion_matrix.task, and names.
79
+ """
80
+ targets = []
81
+ preds = []
82
+ matrix = validator.confusion_matrix.matrix
83
+ names = list(validator.names.values())
84
+ if validator.confusion_matrix.task == "detect":
85
+ names += ["background"]
86
+
87
+ for ti, pred in enumerate(matrix.T.astype(int)):
88
+ for pi, num in enumerate(pred):
89
+ targets.extend([names[ti]] * num)
90
+ preds.extend([names[pi]] * num)
91
+
92
+ live.log_sklearn_plot("confusion_matrix", targets, preds, name="cf.json", normalized=True)
93
+
94
+
95
+ def on_pretrain_routine_start(trainer) -> None:
96
+ """Initialize DVCLive logger for training metadata during pre-training routine."""
97
+ try:
98
+ global live
99
+ live = dvclive.Live(save_dvc_exp=True, cache_images=True)
100
+ LOGGER.info("DVCLive is detected and auto logging is enabled (run 'yolo settings dvc=False' to disable).")
101
+ except Exception as e:
102
+ LOGGER.warning(f"DVCLive installed but not initialized correctly, not logging this run. {e}")
103
+
104
+
105
+ def on_pretrain_routine_end(trainer) -> None:
106
+ """Log plots related to the training process at the end of the pretraining routine."""
107
+ _log_plots(trainer.plots, "train")
108
+
109
+
110
+ def on_train_start(trainer) -> None:
111
+ """Log the training parameters if DVCLive logging is active."""
112
+ if live:
113
+ live.log_params(trainer.args)
114
+
115
+
116
+ def on_train_epoch_start(trainer) -> None:
117
+ """Set the global variable _training_epoch value to True at the start of training each epoch."""
118
+ global _training_epoch
119
+ _training_epoch = True
120
+
121
+
122
+ def on_fit_epoch_end(trainer) -> None:
123
+ """Log training metrics, model info, and advance to next step at the end of each fit epoch.
124
+
125
+ This function is called at the end of each fit epoch during training. It logs various metrics including training
126
+ loss items, validation metrics, and learning rates. On the first epoch, it also logs model
127
+ information. Additionally, it logs training and validation plots and advances the DVCLive step counter.
128
+
129
+ Args:
130
+ trainer (BaseTrainer): The trainer object containing training state, metrics, and plots.
131
+
132
+ Notes:
133
+ This function only performs logging operations when DVCLive logging is active and during a training epoch.
134
+ The global variable _training_epoch is used to track whether the current epoch is a training epoch.
135
+ """
136
+ global _training_epoch
137
+ if live and _training_epoch:
138
+ all_metrics = {**trainer.label_loss_items(trainer.tloss, prefix="train"), **trainer.metrics, **trainer.lr}
139
+ for metric, value in all_metrics.items():
140
+ live.log_metric(metric, value)
141
+
142
+ if trainer.epoch == 0:
143
+ from ultralytics.utils.torch_utils import model_info_for_loggers
144
+
145
+ for metric, value in model_info_for_loggers(trainer).items():
146
+ live.log_metric(metric, value, plot=False)
147
+
148
+ _log_plots(trainer.plots, "train")
149
+ _log_plots(trainer.validator.plots, "val")
150
+
151
+ live.next_step()
152
+ _training_epoch = False
153
+
154
+
155
+ def on_train_end(trainer) -> None:
156
+ """Log best metrics, plots, and confusion matrix at the end of training.
157
+
158
+ This function is called at the conclusion of the training process to log final metrics, visualizations, and model
159
+ artifacts if DVCLive logging is active. It captures the best model performance metrics, training plots, validation
160
+ plots, and confusion matrix for later analysis.
161
+
162
+ Args:
163
+ trainer (BaseTrainer): The trainer object containing training state, metrics, and validation results.
164
+
165
+ Examples:
166
+ >>> # Inside a custom training loop
167
+ >>> from ultralytics.utils.callbacks.dvc import on_train_end
168
+ >>> on_train_end(trainer) # Log final metrics and artifacts
169
+ """
170
+ if live:
171
+ # At the end log the best metrics. It runs validator on the best model internally.
172
+ all_metrics = {**trainer.label_loss_items(trainer.tloss, prefix="train"), **trainer.metrics, **trainer.lr}
173
+ for metric, value in all_metrics.items():
174
+ live.log_metric(metric, value, plot=False)
175
+
176
+ _log_plots(trainer.plots, "val")
177
+ _log_plots(trainer.validator.plots, "val")
178
+ _log_confusion_matrix(trainer.validator)
179
+
180
+ if trainer.best.exists():
181
+ live.log_artifact(trainer.best, copy=True, type="model")
182
+
183
+ live.end()
184
+
185
+
186
+ callbacks = (
187
+ {
188
+ "on_pretrain_routine_start": on_pretrain_routine_start,
189
+ "on_pretrain_routine_end": on_pretrain_routine_end,
190
+ "on_train_start": on_train_start,
191
+ "on_train_epoch_start": on_train_epoch_start,
192
+ "on_fit_epoch_end": on_fit_epoch_end,
193
+ "on_train_end": on_train_end,
194
+ }
195
+ if dvclive
196
+ else {}
197
+ )
@@ -0,0 +1,110 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ import json
4
+ from time import time
5
+
6
+ from ultralytics.hub import HUB_WEB_ROOT, PREFIX, HUBTrainingSession
7
+ from ultralytics.utils import LOGGER, RANK, SETTINGS
8
+ from ultralytics.utils.events import events
9
+
10
+
11
+ def on_pretrain_routine_start(trainer):
12
+ """Create a remote Ultralytics HUB session to log local model training."""
13
+ if RANK in {-1, 0} and SETTINGS["hub"] is True and SETTINGS["api_key"] and trainer.hub_session is None:
14
+ trainer.hub_session = HUBTrainingSession.create_session(trainer.args.model, trainer.args)
15
+
16
+
17
+ def on_pretrain_routine_end(trainer):
18
+ """Initialize timers for upload rate limiting before training begins."""
19
+ if session := getattr(trainer, "hub_session", None):
20
+ # Start timer for upload rate limit
21
+ session.timers = {"metrics": time(), "ckpt": time()} # start timer for session rate limiting
22
+
23
+
24
+ def on_fit_epoch_end(trainer):
25
+ """Upload training progress metrics to Ultralytics HUB at the end of each epoch."""
26
+ if session := getattr(trainer, "hub_session", None):
27
+ # Upload metrics after validation ends
28
+ all_plots = {
29
+ **trainer.label_loss_items(trainer.tloss, prefix="train"),
30
+ **trainer.metrics,
31
+ }
32
+ if trainer.epoch == 0:
33
+ from ultralytics.utils.torch_utils import model_info_for_loggers
34
+
35
+ all_plots = {**all_plots, **model_info_for_loggers(trainer)}
36
+
37
+ session.metrics_queue[trainer.epoch] = json.dumps(all_plots)
38
+
39
+ # If any metrics failed to upload previously, add them to the queue to attempt uploading again
40
+ if session.metrics_upload_failed_queue:
41
+ session.metrics_queue.update(session.metrics_upload_failed_queue)
42
+
43
+ if time() - session.timers["metrics"] > session.rate_limits["metrics"]:
44
+ session.upload_metrics()
45
+ session.timers["metrics"] = time() # reset timer
46
+ session.metrics_queue = {} # reset queue
47
+
48
+
49
+ def on_model_save(trainer):
50
+ """Upload model checkpoints to Ultralytics HUB with rate limiting."""
51
+ if session := getattr(trainer, "hub_session", None):
52
+ # Upload checkpoints with rate limiting
53
+ is_best = trainer.best_fitness == trainer.fitness
54
+ if time() - session.timers["ckpt"] > session.rate_limits["ckpt"]:
55
+ LOGGER.info(f"{PREFIX}Uploading checkpoint {HUB_WEB_ROOT}/models/{session.model.id}")
56
+ session.upload_model(trainer.epoch, trainer.last, is_best)
57
+ session.timers["ckpt"] = time() # reset timer
58
+
59
+
60
+ def on_train_end(trainer):
61
+ """Upload final model and metrics to Ultralytics HUB at the end of training."""
62
+ if session := getattr(trainer, "hub_session", None):
63
+ # Upload final model and metrics with exponential standoff
64
+ LOGGER.info(f"{PREFIX}Syncing final model...")
65
+ session.upload_model(
66
+ trainer.epoch,
67
+ trainer.best,
68
+ map=trainer.metrics.get("metrics/mAP50-95(B)", 0),
69
+ final=True,
70
+ )
71
+ session.alive = False # stop heartbeats
72
+ LOGGER.info(f"{PREFIX}Done ✅\n{PREFIX}View model at {session.model_url} 🚀")
73
+
74
+
75
+ def on_train_start(trainer):
76
+ """Run events on train start."""
77
+ events(trainer.args, trainer.device)
78
+
79
+
80
+ def on_val_start(validator):
81
+ """Run events on validation start."""
82
+ if not validator.training:
83
+ events(validator.args, validator.device)
84
+
85
+
86
+ def on_predict_start(predictor):
87
+ """Run events on predict start."""
88
+ events(predictor.args, predictor.device)
89
+
90
+
91
+ def on_export_start(exporter):
92
+ """Run events on export start."""
93
+ events(exporter.args, exporter.device)
94
+
95
+
96
+ callbacks = (
97
+ {
98
+ "on_pretrain_routine_start": on_pretrain_routine_start,
99
+ "on_pretrain_routine_end": on_pretrain_routine_end,
100
+ "on_fit_epoch_end": on_fit_epoch_end,
101
+ "on_model_save": on_model_save,
102
+ "on_train_end": on_train_end,
103
+ "on_train_start": on_train_start,
104
+ "on_val_start": on_val_start,
105
+ "on_predict_start": on_predict_start,
106
+ "on_export_start": on_export_start,
107
+ }
108
+ if SETTINGS["hub"] is True
109
+ else {}
110
+ )
@@ -0,0 +1,134 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+ """
3
+ MLflow Logging for Ultralytics YOLO.
4
+
5
+ This module enables MLflow logging for Ultralytics YOLO. It logs metrics, parameters, and model artifacts.
6
+ For setting up, a tracking URI should be specified. The logging can be customized using environment variables.
7
+
8
+ Commands:
9
+ 1. To set a project name:
10
+ `export MLFLOW_EXPERIMENT_NAME=<your_experiment_name>` or use the project=<project> argument
11
+
12
+ 2. To set a run name:
13
+ `export MLFLOW_RUN=<your_run_name>` or use the name=<name> argument
14
+
15
+ 3. To start a local MLflow server:
16
+ mlflow server --backend-store-uri runs/mlflow
17
+ It will by default start a local server at http://127.0.0.1:5000.
18
+ To specify a different URI, set the MLFLOW_TRACKING_URI environment variable.
19
+
20
+ 4. To kill all running MLflow server instances:
21
+ ps aux | grep 'mlflow' | grep -v 'grep' | awk '{print $2}' | xargs kill -9
22
+ """
23
+
24
+ from ultralytics.utils import LOGGER, RUNS_DIR, SETTINGS, TESTS_RUNNING, colorstr
25
+
26
+ try:
27
+ import os
28
+
29
+ assert not TESTS_RUNNING or "test_mlflow" in os.environ.get("PYTEST_CURRENT_TEST", "") # do not log pytest
30
+ assert SETTINGS["mlflow"] is True # verify integration is enabled
31
+ import mlflow
32
+
33
+ assert hasattr(mlflow, "__version__") # verify package is not directory
34
+ from pathlib import Path
35
+
36
+ PREFIX = colorstr("MLflow: ")
37
+
38
+ except (ImportError, AssertionError):
39
+ mlflow = None
40
+
41
+
42
+ def sanitize_dict(x: dict) -> dict:
43
+ """Sanitize dictionary keys by removing parentheses and converting values to floats."""
44
+ return {k.replace("(", "").replace(")", ""): float(v) for k, v in x.items()}
45
+
46
+
47
+ def on_pretrain_routine_end(trainer):
48
+ """Log training parameters to MLflow at the end of the pretraining routine.
49
+
50
+ This function sets up MLflow logging based on environment variables and trainer arguments. It sets the tracking URI,
51
+ experiment name, and run name, then starts the MLflow run if not already active. It finally logs the parameters from
52
+ the trainer.
53
+
54
+ Args:
55
+ trainer (ultralytics.engine.trainer.BaseTrainer): The training object with arguments and parameters to log.
56
+
57
+ Notes:
58
+ MLFLOW_TRACKING_URI: The URI for MLflow tracking. If not set, defaults to 'runs/mlflow'.
59
+ MLFLOW_EXPERIMENT_NAME: The name of the MLflow experiment. If not set, defaults to trainer.args.project.
60
+ MLFLOW_RUN: The name of the MLflow run. If not set, defaults to trainer.args.name.
61
+ MLFLOW_KEEP_RUN_ACTIVE: Boolean indicating whether to keep the MLflow run active after training ends.
62
+ """
63
+ global mlflow
64
+
65
+ uri = os.environ.get("MLFLOW_TRACKING_URI") or str(RUNS_DIR / "mlflow")
66
+ LOGGER.debug(f"{PREFIX} tracking uri: {uri}")
67
+ mlflow.set_tracking_uri(uri)
68
+
69
+ # Set experiment and run names
70
+ experiment_name = os.environ.get("MLFLOW_EXPERIMENT_NAME") or trainer.args.project or "/Shared/Ultralytics"
71
+ run_name = os.environ.get("MLFLOW_RUN") or trainer.args.name
72
+ mlflow.set_experiment(experiment_name)
73
+
74
+ mlflow.autolog()
75
+ try:
76
+ active_run = mlflow.active_run() or mlflow.start_run(run_name=run_name)
77
+ LOGGER.info(f"{PREFIX}logging run_id({active_run.info.run_id}) to {uri}")
78
+ if Path(uri).is_dir():
79
+ LOGGER.info(f"{PREFIX}view at http://127.0.0.1:5000 with 'mlflow server --backend-store-uri {uri}'")
80
+ LOGGER.info(f"{PREFIX}disable with 'yolo settings mlflow=False'")
81
+ mlflow.log_params(dict(trainer.args))
82
+ except Exception as e:
83
+ LOGGER.warning(f"{PREFIX}Failed to initialize: {e}")
84
+ LOGGER.warning(f"{PREFIX}Not tracking this run")
85
+
86
+
87
+ def on_train_epoch_end(trainer):
88
+ """Log training metrics at the end of each train epoch to MLflow."""
89
+ if mlflow:
90
+ mlflow.log_metrics(
91
+ metrics={
92
+ **sanitize_dict(trainer.lr),
93
+ **sanitize_dict(trainer.label_loss_items(trainer.tloss, prefix="train")),
94
+ },
95
+ step=trainer.epoch,
96
+ )
97
+
98
+
99
+ def on_fit_epoch_end(trainer):
100
+ """Log training metrics at the end of each fit epoch to MLflow."""
101
+ if mlflow:
102
+ mlflow.log_metrics(metrics=sanitize_dict(trainer.metrics), step=trainer.epoch)
103
+
104
+
105
+ def on_train_end(trainer):
106
+ """Log model artifacts at the end of training."""
107
+ if not mlflow:
108
+ return
109
+ mlflow.log_artifact(str(trainer.best.parent)) # log save_dir/weights directory with best.pt and last.pt
110
+ for f in trainer.save_dir.glob("*"): # log all other files in save_dir
111
+ if f.suffix in {".png", ".jpg", ".csv", ".pt", ".yaml"}:
112
+ mlflow.log_artifact(str(f))
113
+ keep_run_active = os.environ.get("MLFLOW_KEEP_RUN_ACTIVE", "False").lower() == "true"
114
+ if keep_run_active:
115
+ LOGGER.info(f"{PREFIX}mlflow run still alive, remember to close it using mlflow.end_run()")
116
+ else:
117
+ mlflow.end_run()
118
+ LOGGER.debug(f"{PREFIX}mlflow run ended")
119
+
120
+ LOGGER.info(
121
+ f"{PREFIX}results logged to {mlflow.get_tracking_uri()}\n{PREFIX}disable with 'yolo settings mlflow=False'"
122
+ )
123
+
124
+
125
+ callbacks = (
126
+ {
127
+ "on_pretrain_routine_end": on_pretrain_routine_end,
128
+ "on_train_epoch_end": on_train_epoch_end,
129
+ "on_fit_epoch_end": on_fit_epoch_end,
130
+ "on_train_end": on_train_end,
131
+ }
132
+ if mlflow
133
+ else {}
134
+ )
@@ -0,0 +1,126 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ from ultralytics.utils import LOGGER, SETTINGS, TESTS_RUNNING
4
+
5
+ try:
6
+ assert not TESTS_RUNNING # do not log pytest
7
+ assert SETTINGS["neptune"] is True # verify integration is enabled
8
+
9
+ import neptune
10
+ from neptune.types import File
11
+
12
+ assert hasattr(neptune, "__version__")
13
+
14
+ run = None # NeptuneAI experiment logger instance
15
+
16
+ except (ImportError, AssertionError):
17
+ neptune = None
18
+
19
+
20
+ def _log_scalars(scalars: dict, step: int = 0) -> None:
21
+ """Log scalars to the NeptuneAI experiment logger.
22
+
23
+ Args:
24
+ scalars (dict): Dictionary of scalar values to log to NeptuneAI.
25
+ step (int, optional): The current step or iteration number for logging.
26
+
27
+ Examples:
28
+ >>> metrics = {"mAP": 0.85, "loss": 0.32}
29
+ >>> _log_scalars(metrics, step=100)
30
+ """
31
+ if run:
32
+ for k, v in scalars.items():
33
+ run[k].append(value=v, step=step)
34
+
35
+
36
+ def _log_images(imgs_dict: dict, group: str = "") -> None:
37
+ """Log images to the NeptuneAI experiment logger.
38
+
39
+ This function logs image data to Neptune.ai when a valid Neptune run is active. Images are organized under the
40
+ specified group name.
41
+
42
+ Args:
43
+ imgs_dict (dict): Dictionary of images to log, with keys as image names and values as image data.
44
+ group (str, optional): Group name to organize images under in the Neptune UI.
45
+
46
+ Examples:
47
+ >>> # Log validation images
48
+ >>> _log_images({"val_batch": img_tensor}, group="validation")
49
+ """
50
+ if run:
51
+ for k, v in imgs_dict.items():
52
+ run[f"{group}/{k}"].upload(File(v))
53
+
54
+
55
+ def _log_plot(title: str, plot_path: str) -> None:
56
+ """Log plots to the NeptuneAI experiment logger."""
57
+ import matplotlib.image as mpimg
58
+ import matplotlib.pyplot as plt
59
+
60
+ img = mpimg.imread(plot_path)
61
+ fig = plt.figure()
62
+ ax = fig.add_axes([0, 0, 1, 1], frameon=False, aspect="auto", xticks=[], yticks=[]) # no ticks
63
+ ax.imshow(img)
64
+ run[f"Plots/{title}"].upload(fig)
65
+
66
+
67
+ def on_pretrain_routine_start(trainer) -> None:
68
+ """Initialize NeptuneAI run and log hyperparameters before training starts."""
69
+ try:
70
+ global run
71
+ run = neptune.init_run(
72
+ project=trainer.args.project or "Ultralytics",
73
+ name=trainer.args.name,
74
+ tags=["Ultralytics"],
75
+ )
76
+ run["Configuration/Hyperparameters"] = {k: "" if v is None else v for k, v in vars(trainer.args).items()}
77
+ except Exception as e:
78
+ LOGGER.warning(f"NeptuneAI installed but not initialized correctly, not logging this run. {e}")
79
+
80
+
81
+ def on_train_epoch_end(trainer) -> None:
82
+ """Log training metrics and learning rate at the end of each training epoch."""
83
+ _log_scalars(trainer.label_loss_items(trainer.tloss, prefix="train"), trainer.epoch + 1)
84
+ _log_scalars(trainer.lr, trainer.epoch + 1)
85
+ if trainer.epoch == 1:
86
+ _log_images({f.stem: str(f) for f in trainer.save_dir.glob("train_batch*.jpg")}, "Mosaic")
87
+
88
+
89
+ def on_fit_epoch_end(trainer) -> None:
90
+ """Log model info and validation metrics at the end of each fit epoch."""
91
+ if run and trainer.epoch == 0:
92
+ from ultralytics.utils.torch_utils import model_info_for_loggers
93
+
94
+ run["Configuration/Model"] = model_info_for_loggers(trainer)
95
+ _log_scalars(trainer.metrics, trainer.epoch + 1)
96
+
97
+
98
+ def on_val_end(validator) -> None:
99
+ """Log validation images at the end of validation."""
100
+ if run:
101
+ # Log val_labels and val_pred
102
+ _log_images({f.stem: str(f) for f in validator.save_dir.glob("val*.jpg")}, "Validation")
103
+
104
+
105
+ def on_train_end(trainer) -> None:
106
+ """Log final results, plots, and model weights at the end of training."""
107
+ if run:
108
+ # Log final results, CM matrix + PR plots
109
+ for f in [*trainer.plots.keys(), *trainer.validator.plots.keys()]:
110
+ if "batch" not in f.name:
111
+ _log_plot(title=f.stem, plot_path=f)
112
+ # Log the final model
113
+ run[f"weights/{trainer.args.name or trainer.args.task}/{trainer.best.name}"].upload(File(str(trainer.best)))
114
+
115
+
116
+ callbacks = (
117
+ {
118
+ "on_pretrain_routine_start": on_pretrain_routine_start,
119
+ "on_train_epoch_end": on_train_epoch_end,
120
+ "on_fit_epoch_end": on_fit_epoch_end,
121
+ "on_val_end": on_val_end,
122
+ "on_train_end": on_train_end,
123
+ }
124
+ if neptune
125
+ else {}
126
+ )