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,205 @@
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
+ """
31
+ Log images at specified path with an optional prefix using DVCLive.
32
+
33
+ This function logs images found at the given path to DVCLive, organizing them by batch to enable slider
34
+ functionality in the UI. It processes image filenames to extract batch information and restructures the path
35
+ accordingly.
36
+
37
+ Args:
38
+ path (Path): Path to the image file to be logged.
39
+ prefix (str): Optional prefix to add to the image name when logging.
40
+
41
+ Examples:
42
+ >>> from pathlib import Path
43
+ >>> _log_images(Path("runs/train/exp/val_batch0_pred.jpg"), prefix="validation")
44
+ """
45
+ if live:
46
+ name = path.name
47
+
48
+ # Group images by batch to enable sliders in UI
49
+ if m := re.search(r"_batch(\d+)", name):
50
+ ni = m[1]
51
+ new_stem = re.sub(r"_batch(\d+)", "_batch", path.stem)
52
+ name = (Path(new_stem) / ni).with_suffix(path.suffix)
53
+
54
+ live.log_image(os.path.join(prefix, name), path)
55
+
56
+
57
+ def _log_plots(plots: dict, prefix: str = "") -> None:
58
+ """
59
+ Log plot images for training progress if they have not been previously processed.
60
+
61
+ Args:
62
+ plots (dict): Dictionary containing plot information with timestamps.
63
+ prefix (str, optional): Optional prefix to add to the logged image paths.
64
+ """
65
+ for name, params in plots.items():
66
+ timestamp = params["timestamp"]
67
+ if _processed_plots.get(name) != timestamp:
68
+ _log_images(name, prefix)
69
+ _processed_plots[name] = timestamp
70
+
71
+
72
+ def _log_confusion_matrix(validator) -> None:
73
+ """
74
+ Log confusion matrix for a validator using DVCLive.
75
+
76
+ This function processes the confusion matrix from a validator object and logs it to DVCLive by converting
77
+ the matrix into lists of target and prediction labels.
78
+
79
+ Args:
80
+ validator (BaseValidator): The validator object containing the confusion matrix and class names.
81
+ Must have attributes: confusion_matrix.matrix, confusion_matrix.task, and names.
82
+
83
+ Returns:
84
+ None
85
+ """
86
+ targets = []
87
+ preds = []
88
+ matrix = validator.confusion_matrix.matrix
89
+ names = list(validator.names.values())
90
+ if validator.confusion_matrix.task == "detect":
91
+ names += ["background"]
92
+
93
+ for ti, pred in enumerate(matrix.T.astype(int)):
94
+ for pi, num in enumerate(pred):
95
+ targets.extend([names[ti]] * num)
96
+ preds.extend([names[pi]] * num)
97
+
98
+ live.log_sklearn_plot("confusion_matrix", targets, preds, name="cf.json", normalized=True)
99
+
100
+
101
+ def on_pretrain_routine_start(trainer) -> None:
102
+ """Initializes DVCLive logger for training metadata during pre-training routine."""
103
+ try:
104
+ global live
105
+ live = dvclive.Live(save_dvc_exp=True, cache_images=True)
106
+ LOGGER.info("DVCLive is detected and auto logging is enabled (run 'yolo settings dvc=False' to disable).")
107
+ except Exception as e:
108
+ LOGGER.warning(f"DVCLive installed but not initialized correctly, not logging this run. {e}")
109
+
110
+
111
+ def on_pretrain_routine_end(trainer) -> None:
112
+ """Logs plots related to the training process at the end of the pretraining routine."""
113
+ _log_plots(trainer.plots, "train")
114
+
115
+
116
+ def on_train_start(trainer) -> None:
117
+ """Logs the training parameters if DVCLive logging is active."""
118
+ if live:
119
+ live.log_params(trainer.args)
120
+
121
+
122
+ def on_train_epoch_start(trainer) -> None:
123
+ """Sets the global variable _training_epoch value to True at the start of training each epoch."""
124
+ global _training_epoch
125
+ _training_epoch = True
126
+
127
+
128
+ def on_fit_epoch_end(trainer) -> None:
129
+ """
130
+ Log training metrics, model info, and advance to next step at the end of each fit epoch.
131
+
132
+ This function is called at the end of each fit epoch during training. It logs various metrics including
133
+ training loss items, validation metrics, and learning rates. On the first epoch, it also logs model
134
+ information. Additionally, it logs training and validation plots and advances the DVCLive step counter.
135
+
136
+ Args:
137
+ trainer (BaseTrainer): The trainer object containing training state, metrics, and plots.
138
+
139
+ Notes:
140
+ This function only performs logging operations when DVCLive logging is active and during a training epoch.
141
+ The global variable _training_epoch is used to track whether the current epoch is a training epoch.
142
+ """
143
+ global _training_epoch
144
+ if live and _training_epoch:
145
+ all_metrics = {**trainer.label_loss_items(trainer.tloss, prefix="train"), **trainer.metrics, **trainer.lr}
146
+ for metric, value in all_metrics.items():
147
+ live.log_metric(metric, value)
148
+
149
+ if trainer.epoch == 0:
150
+ from ultralytics.utils.torch_utils import model_info_for_loggers
151
+
152
+ for metric, value in model_info_for_loggers(trainer).items():
153
+ live.log_metric(metric, value, plot=False)
154
+
155
+ _log_plots(trainer.plots, "train")
156
+ _log_plots(trainer.validator.plots, "val")
157
+
158
+ live.next_step()
159
+ _training_epoch = False
160
+
161
+
162
+ def on_train_end(trainer) -> None:
163
+ """
164
+ Log best metrics, plots, and confusion matrix at the end of training.
165
+
166
+ This function is called at the conclusion of the training process to log final metrics, visualizations, and
167
+ model artifacts if DVCLive logging is active. It captures the best model performance metrics, training plots,
168
+ validation plots, and confusion matrix for later analysis.
169
+
170
+ Args:
171
+ trainer (BaseTrainer): The trainer object containing training state, metrics, and validation results.
172
+
173
+ Examples:
174
+ >>> # Inside a custom training loop
175
+ >>> from ultralytics.utils.callbacks.dvc import on_train_end
176
+ >>> on_train_end(trainer) # Log final metrics and artifacts
177
+ """
178
+ if live:
179
+ # At the end log the best metrics. It runs validator on the best model internally.
180
+ all_metrics = {**trainer.label_loss_items(trainer.tloss, prefix="train"), **trainer.metrics, **trainer.lr}
181
+ for metric, value in all_metrics.items():
182
+ live.log_metric(metric, value, plot=False)
183
+
184
+ _log_plots(trainer.plots, "val")
185
+ _log_plots(trainer.validator.plots, "val")
186
+ _log_confusion_matrix(trainer.validator)
187
+
188
+ if trainer.best.exists():
189
+ live.log_artifact(trainer.best, copy=True, type="model")
190
+
191
+ live.end()
192
+
193
+
194
+ callbacks = (
195
+ {
196
+ "on_pretrain_routine_start": on_pretrain_routine_start,
197
+ "on_pretrain_routine_end": on_pretrain_routine_end,
198
+ "on_train_start": on_train_start,
199
+ "on_train_epoch_start": on_train_epoch_start,
200
+ "on_fit_epoch_end": on_fit_epoch_end,
201
+ "on_train_end": on_train_end,
202
+ }
203
+ if dvclive
204
+ else {}
205
+ )
@@ -0,0 +1,108 @@
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, events
7
+ from ultralytics.utils import LOGGER, RANK, SETTINGS
8
+
9
+
10
+ def on_pretrain_routine_start(trainer):
11
+ """Create a remote Ultralytics HUB session to log local model training."""
12
+ if RANK in {-1, 0} and SETTINGS["hub"] is True and SETTINGS["api_key"] and trainer.hub_session is None:
13
+ trainer.hub_session = HUBTrainingSession.create_session(trainer.args.model, trainer.args)
14
+
15
+
16
+ def on_pretrain_routine_end(trainer):
17
+ """Initialize timers for upload rate limiting before training begins."""
18
+ if session := getattr(trainer, "hub_session", None):
19
+ # Start timer for upload rate limit
20
+ session.timers = {"metrics": time(), "ckpt": time()} # start timer for session rate limiting
21
+
22
+
23
+ def on_fit_epoch_end(trainer):
24
+ """Upload training progress metrics to Ultralytics HUB at the end of each epoch."""
25
+ if session := getattr(trainer, "hub_session", None):
26
+ # Upload metrics after validation ends
27
+ all_plots = {
28
+ **trainer.label_loss_items(trainer.tloss, prefix="train"),
29
+ **trainer.metrics,
30
+ }
31
+ if trainer.epoch == 0:
32
+ from ultralytics.utils.torch_utils import model_info_for_loggers
33
+
34
+ all_plots = {**all_plots, **model_info_for_loggers(trainer)}
35
+
36
+ session.metrics_queue[trainer.epoch] = json.dumps(all_plots)
37
+
38
+ # If any metrics failed to upload previously, add them to the queue to attempt uploading again
39
+ if session.metrics_upload_failed_queue:
40
+ session.metrics_queue.update(session.metrics_upload_failed_queue)
41
+
42
+ if time() - session.timers["metrics"] > session.rate_limits["metrics"]:
43
+ session.upload_metrics()
44
+ session.timers["metrics"] = time() # reset timer
45
+ session.metrics_queue = {} # reset queue
46
+
47
+
48
+ def on_model_save(trainer):
49
+ """Upload model checkpoints to Ultralytics HUB with rate limiting."""
50
+ if session := getattr(trainer, "hub_session", None):
51
+ # Upload checkpoints with rate limiting
52
+ is_best = trainer.best_fitness == trainer.fitness
53
+ if time() - session.timers["ckpt"] > session.rate_limits["ckpt"]:
54
+ LOGGER.info(f"{PREFIX}Uploading checkpoint {HUB_WEB_ROOT}/models/{session.model.id}")
55
+ session.upload_model(trainer.epoch, trainer.last, is_best)
56
+ session.timers["ckpt"] = time() # reset timer
57
+
58
+
59
+ def on_train_end(trainer):
60
+ """Upload final model and metrics to Ultralytics HUB at the end of training."""
61
+ if session := getattr(trainer, "hub_session", None):
62
+ # Upload final model and metrics with exponential standoff
63
+ LOGGER.info(f"{PREFIX}Syncing final model...")
64
+ session.upload_model(
65
+ trainer.epoch,
66
+ trainer.best,
67
+ map=trainer.metrics.get("metrics/mAP50-95(B)", 0),
68
+ final=True,
69
+ )
70
+ session.alive = False # stop heartbeats
71
+ LOGGER.info(f"{PREFIX}Done ✅\n{PREFIX}View model at {session.model_url} 🚀")
72
+
73
+
74
+ def on_train_start(trainer):
75
+ """Run events on train start."""
76
+ events(trainer.args)
77
+
78
+
79
+ def on_val_start(validator):
80
+ """Run events on validation start."""
81
+ events(validator.args)
82
+
83
+
84
+ def on_predict_start(predictor):
85
+ """Run events on predict start."""
86
+ events(predictor.args)
87
+
88
+
89
+ def on_export_start(exporter):
90
+ """Run events on export start."""
91
+ events(exporter.args)
92
+
93
+
94
+ callbacks = (
95
+ {
96
+ "on_pretrain_routine_start": on_pretrain_routine_start,
97
+ "on_pretrain_routine_end": on_pretrain_routine_end,
98
+ "on_fit_epoch_end": on_fit_epoch_end,
99
+ "on_model_save": on_model_save,
100
+ "on_train_end": on_train_end,
101
+ "on_train_start": on_train_start,
102
+ "on_val_start": on_val_start,
103
+ "on_predict_start": on_predict_start,
104
+ "on_export_start": on_export_start,
105
+ }
106
+ if SETTINGS["hub"] is True
107
+ else {}
108
+ ) # verify hub is enabled before registering callbacks
@@ -0,0 +1,138 @@
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
+ """
49
+ Log training parameters to MLflow at the end of the pretraining routine.
50
+
51
+ This function sets up MLflow logging based on environment variables and trainer arguments. It sets the tracking URI,
52
+ experiment name, and run name, then starts the MLflow run if not already active. It finally logs the parameters
53
+ from the trainer.
54
+
55
+ Args:
56
+ trainer (ultralytics.engine.trainer.BaseTrainer): The training object with arguments and parameters to log.
57
+
58
+ Global:
59
+ mlflow: The imported mlflow module to use for logging.
60
+
61
+ Environment Variables:
62
+ MLFLOW_TRACKING_URI: The URI for MLflow tracking. If not set, defaults to 'runs/mlflow'.
63
+ MLFLOW_EXPERIMENT_NAME: The name of the MLflow experiment. If not set, defaults to trainer.args.project.
64
+ MLFLOW_RUN: The name of the MLflow run. If not set, defaults to trainer.args.name.
65
+ MLFLOW_KEEP_RUN_ACTIVE: Boolean indicating whether to keep the MLflow run active after the end of training.
66
+ """
67
+ global mlflow
68
+
69
+ uri = os.environ.get("MLFLOW_TRACKING_URI") or str(RUNS_DIR / "mlflow")
70
+ LOGGER.debug(f"{PREFIX} tracking uri: {uri}")
71
+ mlflow.set_tracking_uri(uri)
72
+
73
+ # Set experiment and run names
74
+ experiment_name = os.environ.get("MLFLOW_EXPERIMENT_NAME") or trainer.args.project or "/Shared/Ultralytics"
75
+ run_name = os.environ.get("MLFLOW_RUN") or trainer.args.name
76
+ mlflow.set_experiment(experiment_name)
77
+
78
+ mlflow.autolog()
79
+ try:
80
+ active_run = mlflow.active_run() or mlflow.start_run(run_name=run_name)
81
+ LOGGER.info(f"{PREFIX}logging run_id({active_run.info.run_id}) to {uri}")
82
+ if Path(uri).is_dir():
83
+ LOGGER.info(f"{PREFIX}view at http://127.0.0.1:5000 with 'mlflow server --backend-store-uri {uri}'")
84
+ LOGGER.info(f"{PREFIX}disable with 'yolo settings mlflow=False'")
85
+ mlflow.log_params(dict(trainer.args))
86
+ except Exception as e:
87
+ LOGGER.warning(f"{PREFIX}Failed to initialize: {e}")
88
+ LOGGER.warning(f"{PREFIX}Not tracking this run")
89
+
90
+
91
+ def on_train_epoch_end(trainer):
92
+ """Log training metrics at the end of each train epoch to MLflow."""
93
+ if mlflow:
94
+ mlflow.log_metrics(
95
+ metrics={
96
+ **sanitize_dict(trainer.lr),
97
+ **sanitize_dict(trainer.label_loss_items(trainer.tloss, prefix="train")),
98
+ },
99
+ step=trainer.epoch,
100
+ )
101
+
102
+
103
+ def on_fit_epoch_end(trainer):
104
+ """Log training metrics at the end of each fit epoch to MLflow."""
105
+ if mlflow:
106
+ mlflow.log_metrics(metrics=sanitize_dict(trainer.metrics), step=trainer.epoch)
107
+
108
+
109
+ def on_train_end(trainer):
110
+ """Log model artifacts at the end of the training."""
111
+ if not mlflow:
112
+ return
113
+ mlflow.log_artifact(str(trainer.best.parent)) # log save_dir/weights directory with best.pt and last.pt
114
+ for f in trainer.save_dir.glob("*"): # log all other files in save_dir
115
+ if f.suffix in {".png", ".jpg", ".csv", ".pt", ".yaml"}:
116
+ mlflow.log_artifact(str(f))
117
+ keep_run_active = os.environ.get("MLFLOW_KEEP_RUN_ACTIVE", "False").lower() == "true"
118
+ if keep_run_active:
119
+ LOGGER.info(f"{PREFIX}mlflow run still alive, remember to close it using mlflow.end_run()")
120
+ else:
121
+ mlflow.end_run()
122
+ LOGGER.debug(f"{PREFIX}mlflow run ended")
123
+
124
+ LOGGER.info(
125
+ f"{PREFIX}results logged to {mlflow.get_tracking_uri()}\n{PREFIX}disable with 'yolo settings mlflow=False'"
126
+ )
127
+
128
+
129
+ callbacks = (
130
+ {
131
+ "on_pretrain_routine_end": on_pretrain_routine_end,
132
+ "on_train_epoch_end": on_train_epoch_end,
133
+ "on_fit_epoch_end": on_fit_epoch_end,
134
+ "on_train_end": on_train_end,
135
+ }
136
+ if mlflow
137
+ else {}
138
+ )
@@ -0,0 +1,140 @@
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
+ """
22
+ Log scalars to the NeptuneAI experiment logger.
23
+
24
+ Args:
25
+ scalars (dict): Dictionary of scalar values to log to NeptuneAI.
26
+ step (int): The current step or iteration number for logging.
27
+
28
+ Examples:
29
+ >>> metrics = {"mAP": 0.85, "loss": 0.32}
30
+ >>> _log_scalars(metrics, step=100)
31
+ """
32
+ if run:
33
+ for k, v in scalars.items():
34
+ run[k].append(value=v, step=step)
35
+
36
+
37
+ def _log_images(imgs_dict: dict, group: str = "") -> None:
38
+ """
39
+ Log images to the NeptuneAI experiment logger.
40
+
41
+ This function logs image data to Neptune.ai when a valid Neptune run is active. Images are organized
42
+ under the specified group name.
43
+
44
+ Args:
45
+ imgs_dict (dict): Dictionary of images to log, with keys as image names and values as image data.
46
+ group (str, optional): Group name to organize images under in the Neptune UI.
47
+
48
+ Examples:
49
+ >>> # Log validation images
50
+ >>> _log_images({"val_batch": img_tensor}, group="validation")
51
+ """
52
+ if run:
53
+ for k, v in imgs_dict.items():
54
+ run[f"{group}/{k}"].upload(File(v))
55
+
56
+
57
+ def _log_plot(title: str, plot_path: str) -> None:
58
+ """
59
+ Log plots to the NeptuneAI experiment logger.
60
+
61
+ Args:
62
+ title (str): Title of the plot.
63
+ plot_path (str): Path to the saved image file.
64
+ """
65
+ import matplotlib.image as mpimg
66
+ import matplotlib.pyplot as plt
67
+
68
+ img = mpimg.imread(plot_path)
69
+ fig = plt.figure()
70
+ ax = fig.add_axes([0, 0, 1, 1], frameon=False, aspect="auto", xticks=[], yticks=[]) # no ticks
71
+ ax.imshow(img)
72
+ run[f"Plots/{title}"].upload(fig)
73
+
74
+
75
+ def on_pretrain_routine_start(trainer) -> None:
76
+ """Callback function called before the training routine starts."""
77
+ try:
78
+ global run
79
+ run = neptune.init_run(
80
+ project=trainer.args.project or "Ultralytics",
81
+ name=trainer.args.name,
82
+ tags=["Ultralytics"],
83
+ )
84
+ run["Configuration/Hyperparameters"] = {k: "" if v is None else v for k, v in vars(trainer.args).items()}
85
+ except Exception as e:
86
+ LOGGER.warning(f"NeptuneAI installed but not initialized correctly, not logging this run. {e}")
87
+
88
+
89
+ def on_train_epoch_end(trainer) -> None:
90
+ """Callback function called at end of each training epoch."""
91
+ _log_scalars(trainer.label_loss_items(trainer.tloss, prefix="train"), trainer.epoch + 1)
92
+ _log_scalars(trainer.lr, trainer.epoch + 1)
93
+ if trainer.epoch == 1:
94
+ _log_images({f.stem: str(f) for f in trainer.save_dir.glob("train_batch*.jpg")}, "Mosaic")
95
+
96
+
97
+ def on_fit_epoch_end(trainer) -> None:
98
+ """Callback function called at end of each fit (train+val) epoch."""
99
+ if run and trainer.epoch == 0:
100
+ from ultralytics.utils.torch_utils import model_info_for_loggers
101
+
102
+ run["Configuration/Model"] = model_info_for_loggers(trainer)
103
+ _log_scalars(trainer.metrics, trainer.epoch + 1)
104
+
105
+
106
+ def on_val_end(validator) -> None:
107
+ """Callback function called at end of each validation."""
108
+ if run:
109
+ # Log val_labels and val_pred
110
+ _log_images({f.stem: str(f) for f in validator.save_dir.glob("val*.jpg")}, "Validation")
111
+
112
+
113
+ def on_train_end(trainer) -> None:
114
+ """Callback function called at end of training."""
115
+ if run:
116
+ # Log final results, CM matrix + PR plots
117
+ files = [
118
+ "results.png",
119
+ "confusion_matrix.png",
120
+ "confusion_matrix_normalized.png",
121
+ *(f"{x}_curve.png" for x in ("F1", "PR", "P", "R")),
122
+ ]
123
+ files = [(trainer.save_dir / f) for f in files if (trainer.save_dir / f).exists()] # filter
124
+ for f in files:
125
+ _log_plot(title=f.stem, plot_path=f)
126
+ # Log the final model
127
+ run[f"weights/{trainer.args.name or trainer.args.task}/{trainer.best.name}"].upload(File(str(trainer.best)))
128
+
129
+
130
+ callbacks = (
131
+ {
132
+ "on_pretrain_routine_start": on_pretrain_routine_start,
133
+ "on_train_epoch_end": on_train_epoch_end,
134
+ "on_fit_epoch_end": on_fit_epoch_end,
135
+ "on_val_end": on_val_end,
136
+ "on_train_end": on_train_end,
137
+ }
138
+ if neptune
139
+ else {}
140
+ )
@@ -0,0 +1,43 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ from ultralytics.utils import SETTINGS
4
+
5
+ try:
6
+ assert SETTINGS["raytune"] is True # verify integration is enabled
7
+ import ray
8
+ from ray import tune
9
+ from ray.air import session
10
+
11
+ except (ImportError, AssertionError):
12
+ tune = None
13
+
14
+
15
+ def on_fit_epoch_end(trainer):
16
+ """
17
+ Reports training metrics to Ray Tune at epoch end when a Ray session is active.
18
+
19
+ Captures metrics from the trainer object and sends them to Ray Tune with the current epoch number,
20
+ enabling hyperparameter tuning optimization. Only executes when within an active Ray Tune session.
21
+
22
+ Args:
23
+ trainer (ultralytics.engine.trainer.BaseTrainer): The Ultralytics trainer object containing metrics and epochs.
24
+
25
+ Examples:
26
+ >>> # Called automatically by the Ultralytics training loop
27
+ >>> on_fit_epoch_end(trainer)
28
+
29
+ References:
30
+ Ray Tune docs: https://docs.ray.io/en/latest/tune/index.html
31
+ """
32
+ if ray.train._internal.session.get_session(): # check if Ray Tune session is active
33
+ metrics = trainer.metrics
34
+ session.report({**metrics, **{"epoch": trainer.epoch + 1}})
35
+
36
+
37
+ callbacks = (
38
+ {
39
+ "on_fit_epoch_end": on_fit_epoch_end,
40
+ }
41
+ if tune
42
+ else {}
43
+ )