dgenerate-ultralytics-headless 8.3.253__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 (299) hide show
  1. dgenerate_ultralytics_headless-8.3.253.dist-info/METADATA +405 -0
  2. dgenerate_ultralytics_headless-8.3.253.dist-info/RECORD +299 -0
  3. dgenerate_ultralytics_headless-8.3.253.dist-info/WHEEL +5 -0
  4. dgenerate_ultralytics_headless-8.3.253.dist-info/entry_points.txt +3 -0
  5. dgenerate_ultralytics_headless-8.3.253.dist-info/licenses/LICENSE +661 -0
  6. dgenerate_ultralytics_headless-8.3.253.dist-info/top_level.txt +1 -0
  7. tests/__init__.py +23 -0
  8. tests/conftest.py +59 -0
  9. tests/test_cli.py +131 -0
  10. tests/test_cuda.py +216 -0
  11. tests/test_engine.py +157 -0
  12. tests/test_exports.py +309 -0
  13. tests/test_integrations.py +151 -0
  14. tests/test_python.py +777 -0
  15. tests/test_solutions.py +371 -0
  16. ultralytics/__init__.py +48 -0
  17. ultralytics/assets/bus.jpg +0 -0
  18. ultralytics/assets/zidane.jpg +0 -0
  19. ultralytics/cfg/__init__.py +1028 -0
  20. ultralytics/cfg/datasets/Argoverse.yaml +78 -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 +32 -0
  25. ultralytics/cfg/datasets/ImageNet.yaml +2025 -0
  26. ultralytics/cfg/datasets/Objects365.yaml +447 -0
  27. ultralytics/cfg/datasets/SKU-110K.yaml +58 -0
  28. ultralytics/cfg/datasets/TT100K.yaml +346 -0
  29. ultralytics/cfg/datasets/VOC.yaml +102 -0
  30. ultralytics/cfg/datasets/VisDrone.yaml +87 -0
  31. ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
  32. ultralytics/cfg/datasets/brain-tumor.yaml +22 -0
  33. ultralytics/cfg/datasets/carparts-seg.yaml +44 -0
  34. ultralytics/cfg/datasets/coco-pose.yaml +64 -0
  35. ultralytics/cfg/datasets/coco.yaml +118 -0
  36. ultralytics/cfg/datasets/coco128-seg.yaml +101 -0
  37. ultralytics/cfg/datasets/coco128.yaml +101 -0
  38. ultralytics/cfg/datasets/coco8-grayscale.yaml +103 -0
  39. ultralytics/cfg/datasets/coco8-multispectral.yaml +104 -0
  40. ultralytics/cfg/datasets/coco8-pose.yaml +47 -0
  41. ultralytics/cfg/datasets/coco8-seg.yaml +101 -0
  42. ultralytics/cfg/datasets/coco8.yaml +101 -0
  43. ultralytics/cfg/datasets/construction-ppe.yaml +32 -0
  44. ultralytics/cfg/datasets/crack-seg.yaml +22 -0
  45. ultralytics/cfg/datasets/dog-pose.yaml +52 -0
  46. ultralytics/cfg/datasets/dota8-multispectral.yaml +38 -0
  47. ultralytics/cfg/datasets/dota8.yaml +35 -0
  48. ultralytics/cfg/datasets/hand-keypoints.yaml +50 -0
  49. ultralytics/cfg/datasets/kitti.yaml +27 -0
  50. ultralytics/cfg/datasets/lvis.yaml +1240 -0
  51. ultralytics/cfg/datasets/medical-pills.yaml +21 -0
  52. ultralytics/cfg/datasets/open-images-v7.yaml +663 -0
  53. ultralytics/cfg/datasets/package-seg.yaml +22 -0
  54. ultralytics/cfg/datasets/signature.yaml +21 -0
  55. ultralytics/cfg/datasets/tiger-pose.yaml +41 -0
  56. ultralytics/cfg/datasets/xView.yaml +155 -0
  57. ultralytics/cfg/default.yaml +130 -0
  58. ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +17 -0
  59. ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
  60. ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
  61. ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
  62. ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
  63. ultralytics/cfg/models/11/yolo11.yaml +50 -0
  64. ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
  65. ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
  66. ultralytics/cfg/models/12/yolo12-cls.yaml +32 -0
  67. ultralytics/cfg/models/12/yolo12-obb.yaml +48 -0
  68. ultralytics/cfg/models/12/yolo12-pose.yaml +49 -0
  69. ultralytics/cfg/models/12/yolo12-seg.yaml +48 -0
  70. ultralytics/cfg/models/12/yolo12.yaml +48 -0
  71. ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +53 -0
  72. ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +45 -0
  73. ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +45 -0
  74. ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +57 -0
  75. ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
  76. ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
  77. ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
  78. ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
  79. ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
  80. ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
  81. ultralytics/cfg/models/v3/yolov3-spp.yaml +49 -0
  82. ultralytics/cfg/models/v3/yolov3-tiny.yaml +40 -0
  83. ultralytics/cfg/models/v3/yolov3.yaml +49 -0
  84. ultralytics/cfg/models/v5/yolov5-p6.yaml +62 -0
  85. ultralytics/cfg/models/v5/yolov5.yaml +51 -0
  86. ultralytics/cfg/models/v6/yolov6.yaml +56 -0
  87. ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +48 -0
  88. ultralytics/cfg/models/v8/yoloe-v8.yaml +48 -0
  89. ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +28 -0
  90. ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +28 -0
  91. ultralytics/cfg/models/v8/yolov8-cls.yaml +32 -0
  92. ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +58 -0
  93. ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +60 -0
  94. ultralytics/cfg/models/v8/yolov8-ghost.yaml +50 -0
  95. ultralytics/cfg/models/v8/yolov8-obb.yaml +49 -0
  96. ultralytics/cfg/models/v8/yolov8-p2.yaml +57 -0
  97. ultralytics/cfg/models/v8/yolov8-p6.yaml +59 -0
  98. ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +60 -0
  99. ultralytics/cfg/models/v8/yolov8-pose.yaml +50 -0
  100. ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +49 -0
  101. ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +59 -0
  102. ultralytics/cfg/models/v8/yolov8-seg.yaml +49 -0
  103. ultralytics/cfg/models/v8/yolov8-world.yaml +51 -0
  104. ultralytics/cfg/models/v8/yolov8-worldv2.yaml +49 -0
  105. ultralytics/cfg/models/v8/yolov8.yaml +49 -0
  106. ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
  107. ultralytics/cfg/models/v9/yolov9c.yaml +41 -0
  108. ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
  109. ultralytics/cfg/models/v9/yolov9e.yaml +64 -0
  110. ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
  111. ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
  112. ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
  113. ultralytics/cfg/trackers/botsort.yaml +21 -0
  114. ultralytics/cfg/trackers/bytetrack.yaml +12 -0
  115. ultralytics/data/__init__.py +26 -0
  116. ultralytics/data/annotator.py +66 -0
  117. ultralytics/data/augment.py +2801 -0
  118. ultralytics/data/base.py +435 -0
  119. ultralytics/data/build.py +437 -0
  120. ultralytics/data/converter.py +855 -0
  121. ultralytics/data/dataset.py +834 -0
  122. ultralytics/data/loaders.py +704 -0
  123. ultralytics/data/scripts/download_weights.sh +18 -0
  124. ultralytics/data/scripts/get_coco.sh +61 -0
  125. ultralytics/data/scripts/get_coco128.sh +18 -0
  126. ultralytics/data/scripts/get_imagenet.sh +52 -0
  127. ultralytics/data/split.py +138 -0
  128. ultralytics/data/split_dota.py +344 -0
  129. ultralytics/data/utils.py +798 -0
  130. ultralytics/engine/__init__.py +1 -0
  131. ultralytics/engine/exporter.py +1580 -0
  132. ultralytics/engine/model.py +1125 -0
  133. ultralytics/engine/predictor.py +508 -0
  134. ultralytics/engine/results.py +1522 -0
  135. ultralytics/engine/trainer.py +977 -0
  136. ultralytics/engine/tuner.py +449 -0
  137. ultralytics/engine/validator.py +387 -0
  138. ultralytics/hub/__init__.py +166 -0
  139. ultralytics/hub/auth.py +151 -0
  140. ultralytics/hub/google/__init__.py +174 -0
  141. ultralytics/hub/session.py +422 -0
  142. ultralytics/hub/utils.py +162 -0
  143. ultralytics/models/__init__.py +9 -0
  144. ultralytics/models/fastsam/__init__.py +7 -0
  145. ultralytics/models/fastsam/model.py +79 -0
  146. ultralytics/models/fastsam/predict.py +169 -0
  147. ultralytics/models/fastsam/utils.py +23 -0
  148. ultralytics/models/fastsam/val.py +38 -0
  149. ultralytics/models/nas/__init__.py +7 -0
  150. ultralytics/models/nas/model.py +98 -0
  151. ultralytics/models/nas/predict.py +56 -0
  152. ultralytics/models/nas/val.py +38 -0
  153. ultralytics/models/rtdetr/__init__.py +7 -0
  154. ultralytics/models/rtdetr/model.py +63 -0
  155. ultralytics/models/rtdetr/predict.py +88 -0
  156. ultralytics/models/rtdetr/train.py +89 -0
  157. ultralytics/models/rtdetr/val.py +216 -0
  158. ultralytics/models/sam/__init__.py +25 -0
  159. ultralytics/models/sam/amg.py +275 -0
  160. ultralytics/models/sam/build.py +365 -0
  161. ultralytics/models/sam/build_sam3.py +377 -0
  162. ultralytics/models/sam/model.py +169 -0
  163. ultralytics/models/sam/modules/__init__.py +1 -0
  164. ultralytics/models/sam/modules/blocks.py +1067 -0
  165. ultralytics/models/sam/modules/decoders.py +495 -0
  166. ultralytics/models/sam/modules/encoders.py +794 -0
  167. ultralytics/models/sam/modules/memory_attention.py +298 -0
  168. ultralytics/models/sam/modules/sam.py +1160 -0
  169. ultralytics/models/sam/modules/tiny_encoder.py +979 -0
  170. ultralytics/models/sam/modules/transformer.py +344 -0
  171. ultralytics/models/sam/modules/utils.py +512 -0
  172. ultralytics/models/sam/predict.py +3940 -0
  173. ultralytics/models/sam/sam3/__init__.py +3 -0
  174. ultralytics/models/sam/sam3/decoder.py +546 -0
  175. ultralytics/models/sam/sam3/encoder.py +529 -0
  176. ultralytics/models/sam/sam3/geometry_encoders.py +415 -0
  177. ultralytics/models/sam/sam3/maskformer_segmentation.py +286 -0
  178. ultralytics/models/sam/sam3/model_misc.py +199 -0
  179. ultralytics/models/sam/sam3/necks.py +129 -0
  180. ultralytics/models/sam/sam3/sam3_image.py +339 -0
  181. ultralytics/models/sam/sam3/text_encoder_ve.py +307 -0
  182. ultralytics/models/sam/sam3/vitdet.py +547 -0
  183. ultralytics/models/sam/sam3/vl_combiner.py +160 -0
  184. ultralytics/models/utils/__init__.py +1 -0
  185. ultralytics/models/utils/loss.py +466 -0
  186. ultralytics/models/utils/ops.py +315 -0
  187. ultralytics/models/yolo/__init__.py +7 -0
  188. ultralytics/models/yolo/classify/__init__.py +7 -0
  189. ultralytics/models/yolo/classify/predict.py +90 -0
  190. ultralytics/models/yolo/classify/train.py +202 -0
  191. ultralytics/models/yolo/classify/val.py +216 -0
  192. ultralytics/models/yolo/detect/__init__.py +7 -0
  193. ultralytics/models/yolo/detect/predict.py +122 -0
  194. ultralytics/models/yolo/detect/train.py +227 -0
  195. ultralytics/models/yolo/detect/val.py +507 -0
  196. ultralytics/models/yolo/model.py +430 -0
  197. ultralytics/models/yolo/obb/__init__.py +7 -0
  198. ultralytics/models/yolo/obb/predict.py +56 -0
  199. ultralytics/models/yolo/obb/train.py +79 -0
  200. ultralytics/models/yolo/obb/val.py +302 -0
  201. ultralytics/models/yolo/pose/__init__.py +7 -0
  202. ultralytics/models/yolo/pose/predict.py +65 -0
  203. ultralytics/models/yolo/pose/train.py +110 -0
  204. ultralytics/models/yolo/pose/val.py +248 -0
  205. ultralytics/models/yolo/segment/__init__.py +7 -0
  206. ultralytics/models/yolo/segment/predict.py +109 -0
  207. ultralytics/models/yolo/segment/train.py +69 -0
  208. ultralytics/models/yolo/segment/val.py +307 -0
  209. ultralytics/models/yolo/world/__init__.py +5 -0
  210. ultralytics/models/yolo/world/train.py +173 -0
  211. ultralytics/models/yolo/world/train_world.py +178 -0
  212. ultralytics/models/yolo/yoloe/__init__.py +22 -0
  213. ultralytics/models/yolo/yoloe/predict.py +162 -0
  214. ultralytics/models/yolo/yoloe/train.py +287 -0
  215. ultralytics/models/yolo/yoloe/train_seg.py +122 -0
  216. ultralytics/models/yolo/yoloe/val.py +206 -0
  217. ultralytics/nn/__init__.py +27 -0
  218. ultralytics/nn/autobackend.py +964 -0
  219. ultralytics/nn/modules/__init__.py +182 -0
  220. ultralytics/nn/modules/activation.py +54 -0
  221. ultralytics/nn/modules/block.py +1947 -0
  222. ultralytics/nn/modules/conv.py +669 -0
  223. ultralytics/nn/modules/head.py +1183 -0
  224. ultralytics/nn/modules/transformer.py +793 -0
  225. ultralytics/nn/modules/utils.py +159 -0
  226. ultralytics/nn/tasks.py +1768 -0
  227. ultralytics/nn/text_model.py +356 -0
  228. ultralytics/py.typed +1 -0
  229. ultralytics/solutions/__init__.py +41 -0
  230. ultralytics/solutions/ai_gym.py +108 -0
  231. ultralytics/solutions/analytics.py +264 -0
  232. ultralytics/solutions/config.py +107 -0
  233. ultralytics/solutions/distance_calculation.py +123 -0
  234. ultralytics/solutions/heatmap.py +125 -0
  235. ultralytics/solutions/instance_segmentation.py +86 -0
  236. ultralytics/solutions/object_blurrer.py +89 -0
  237. ultralytics/solutions/object_counter.py +190 -0
  238. ultralytics/solutions/object_cropper.py +87 -0
  239. ultralytics/solutions/parking_management.py +280 -0
  240. ultralytics/solutions/queue_management.py +93 -0
  241. ultralytics/solutions/region_counter.py +133 -0
  242. ultralytics/solutions/security_alarm.py +151 -0
  243. ultralytics/solutions/similarity_search.py +219 -0
  244. ultralytics/solutions/solutions.py +828 -0
  245. ultralytics/solutions/speed_estimation.py +114 -0
  246. ultralytics/solutions/streamlit_inference.py +260 -0
  247. ultralytics/solutions/templates/similarity-search.html +156 -0
  248. ultralytics/solutions/trackzone.py +88 -0
  249. ultralytics/solutions/vision_eye.py +67 -0
  250. ultralytics/trackers/__init__.py +7 -0
  251. ultralytics/trackers/basetrack.py +115 -0
  252. ultralytics/trackers/bot_sort.py +257 -0
  253. ultralytics/trackers/byte_tracker.py +469 -0
  254. ultralytics/trackers/track.py +116 -0
  255. ultralytics/trackers/utils/__init__.py +1 -0
  256. ultralytics/trackers/utils/gmc.py +339 -0
  257. ultralytics/trackers/utils/kalman_filter.py +482 -0
  258. ultralytics/trackers/utils/matching.py +154 -0
  259. ultralytics/utils/__init__.py +1450 -0
  260. ultralytics/utils/autobatch.py +118 -0
  261. ultralytics/utils/autodevice.py +205 -0
  262. ultralytics/utils/benchmarks.py +728 -0
  263. ultralytics/utils/callbacks/__init__.py +5 -0
  264. ultralytics/utils/callbacks/base.py +233 -0
  265. ultralytics/utils/callbacks/clearml.py +146 -0
  266. ultralytics/utils/callbacks/comet.py +625 -0
  267. ultralytics/utils/callbacks/dvc.py +197 -0
  268. ultralytics/utils/callbacks/hub.py +110 -0
  269. ultralytics/utils/callbacks/mlflow.py +134 -0
  270. ultralytics/utils/callbacks/neptune.py +126 -0
  271. ultralytics/utils/callbacks/platform.py +453 -0
  272. ultralytics/utils/callbacks/raytune.py +42 -0
  273. ultralytics/utils/callbacks/tensorboard.py +123 -0
  274. ultralytics/utils/callbacks/wb.py +188 -0
  275. ultralytics/utils/checks.py +1020 -0
  276. ultralytics/utils/cpu.py +85 -0
  277. ultralytics/utils/dist.py +123 -0
  278. ultralytics/utils/downloads.py +529 -0
  279. ultralytics/utils/errors.py +35 -0
  280. ultralytics/utils/events.py +113 -0
  281. ultralytics/utils/export/__init__.py +7 -0
  282. ultralytics/utils/export/engine.py +237 -0
  283. ultralytics/utils/export/imx.py +325 -0
  284. ultralytics/utils/export/tensorflow.py +231 -0
  285. ultralytics/utils/files.py +219 -0
  286. ultralytics/utils/git.py +137 -0
  287. ultralytics/utils/instance.py +484 -0
  288. ultralytics/utils/logger.py +506 -0
  289. ultralytics/utils/loss.py +849 -0
  290. ultralytics/utils/metrics.py +1563 -0
  291. ultralytics/utils/nms.py +337 -0
  292. ultralytics/utils/ops.py +664 -0
  293. ultralytics/utils/patches.py +201 -0
  294. ultralytics/utils/plotting.py +1047 -0
  295. ultralytics/utils/tal.py +404 -0
  296. ultralytics/utils/torch_utils.py +984 -0
  297. ultralytics/utils/tqdm.py +443 -0
  298. ultralytics/utils/triton.py +112 -0
  299. ultralytics/utils/tuner.py +168 -0
@@ -0,0 +1,1125 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import numpy as np
10
+ import torch
11
+ from PIL import Image
12
+
13
+ from ultralytics.cfg import TASK2DATA, get_cfg, get_save_dir
14
+ from ultralytics.engine.results import Results
15
+ from ultralytics.nn.tasks import guess_model_task, load_checkpoint, yaml_model_load
16
+ from ultralytics.utils import (
17
+ ARGV,
18
+ ASSETS,
19
+ DEFAULT_CFG_DICT,
20
+ LOGGER,
21
+ RANK,
22
+ SETTINGS,
23
+ YAML,
24
+ callbacks,
25
+ checks,
26
+ )
27
+
28
+
29
+ class Model(torch.nn.Module):
30
+ """A base class for implementing YOLO models, unifying APIs across different model types.
31
+
32
+ This class provides a common interface for various operations related to YOLO models, such as training, validation,
33
+ prediction, exporting, and benchmarking. It handles different types of models, including those loaded from local
34
+ files, Ultralytics HUB, or Triton Server.
35
+
36
+ Attributes:
37
+ callbacks (dict): A dictionary of callback functions for various events during model operations.
38
+ predictor (BasePredictor): The predictor object used for making predictions.
39
+ model (torch.nn.Module): The underlying PyTorch model.
40
+ trainer (BaseTrainer): The trainer object used for training the model.
41
+ ckpt (dict): The checkpoint data if the model is loaded from a *.pt file.
42
+ cfg (str): The configuration of the model if loaded from a *.yaml file.
43
+ ckpt_path (str): The path to the checkpoint file.
44
+ overrides (dict): A dictionary of overrides for model configuration.
45
+ metrics (dict): The latest training/validation metrics.
46
+ session (HUBTrainingSession): The Ultralytics HUB session, if applicable.
47
+ task (str): The type of task the model is intended for.
48
+ model_name (str): The name of the model.
49
+
50
+ Methods:
51
+ __call__: Alias for the predict method, enabling the model instance to be callable.
52
+ _new: Initialize a new model based on a configuration file.
53
+ _load: Load a model from a checkpoint file.
54
+ _check_is_pytorch_model: Ensure that the model is a PyTorch model.
55
+ reset_weights: Reset the model's weights to their initial state.
56
+ load: Load model weights from a specified file.
57
+ save: Save the current state of the model to a file.
58
+ info: Log or return information about the model.
59
+ fuse: Fuse Conv2d and BatchNorm2d layers for optimized inference.
60
+ predict: Perform object detection predictions.
61
+ track: Perform object tracking.
62
+ val: Validate the model on a dataset.
63
+ benchmark: Benchmark the model on various export formats.
64
+ export: Export the model to different formats.
65
+ train: Train the model on a dataset.
66
+ tune: Perform hyperparameter tuning.
67
+ _apply: Apply a function to the model's tensors.
68
+ add_callback: Add a callback function for an event.
69
+ clear_callback: Clear all callbacks for an event.
70
+ reset_callbacks: Reset all callbacks to their default functions.
71
+
72
+ Examples:
73
+ >>> from ultralytics import YOLO
74
+ >>> model = YOLO("yolo11n.pt")
75
+ >>> results = model.predict("image.jpg")
76
+ >>> model.train(data="coco8.yaml", epochs=3)
77
+ >>> metrics = model.val()
78
+ >>> model.export(format="onnx")
79
+ """
80
+
81
+ def __init__(
82
+ self,
83
+ model: str | Path | Model = "yolo11n.pt",
84
+ task: str | None = None,
85
+ verbose: bool = False,
86
+ ) -> None:
87
+ """Initialize a new instance of the YOLO model class.
88
+
89
+ This constructor sets up the model based on the provided model path or name. It handles various types of model
90
+ sources, including local files, Ultralytics HUB models, and Triton Server models. The method initializes several
91
+ important attributes of the model and prepares it for operations like training, prediction, or export.
92
+
93
+ Args:
94
+ model (str | Path | Model): Path or name of the model to load or create. Can be a local file path, a model
95
+ name from Ultralytics HUB, a Triton Server model, or an already initialized Model instance.
96
+ task (str, optional): The specific task for the model. If None, it will be inferred from the config.
97
+ verbose (bool): If True, enables verbose output during the model's initialization and subsequent operations.
98
+
99
+ Raises:
100
+ FileNotFoundError: If the specified model file does not exist or is inaccessible.
101
+ ValueError: If the model file or configuration is invalid or unsupported.
102
+ ImportError: If required dependencies for specific model types (like HUB SDK) are not installed.
103
+ """
104
+ if isinstance(model, Model):
105
+ self.__dict__ = model.__dict__ # accepts an already initialized Model
106
+ return
107
+ super().__init__()
108
+ self.callbacks = callbacks.get_default_callbacks()
109
+ self.predictor = None # reuse predictor
110
+ self.model = None # model object
111
+ self.trainer = None # trainer object
112
+ self.ckpt = {} # if loaded from *.pt
113
+ self.cfg = None # if loaded from *.yaml
114
+ self.ckpt_path = None
115
+ self.overrides = {} # overrides for trainer object
116
+ self.metrics = None # validation/training metrics
117
+ self.session = None # HUB session
118
+ self.task = task # task type
119
+ self.model_name = None # model name
120
+ model = str(model).strip()
121
+
122
+ # Check if Ultralytics HUB model from https://hub.ultralytics.com
123
+ if self.is_hub_model(model):
124
+ from ultralytics.hub import HUBTrainingSession
125
+
126
+ # Fetch model from HUB
127
+ checks.check_requirements("hub-sdk>=0.0.12")
128
+ session = HUBTrainingSession.create_session(model)
129
+ model = session.model_file
130
+ if session.train_args: # training sent from HUB
131
+ self.session = session
132
+
133
+ # Check if Triton Server model
134
+ elif self.is_triton_model(model):
135
+ self.model_name = self.model = model
136
+ self.overrides["task"] = task or "detect" # set `task=detect` if not explicitly set
137
+ return
138
+
139
+ # Load or create new YOLO model
140
+ __import__("os").environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8" # to avoid deterministic warnings
141
+ if str(model).endswith((".yaml", ".yml")):
142
+ self._new(model, task=task, verbose=verbose)
143
+ else:
144
+ self._load(model, task=task)
145
+
146
+ # Delete super().training for accessing self.model.training
147
+ del self.training
148
+
149
+ def __call__(
150
+ self,
151
+ source: str | Path | int | Image.Image | list | tuple | np.ndarray | torch.Tensor = None,
152
+ stream: bool = False,
153
+ **kwargs: Any,
154
+ ) -> list:
155
+ """Alias for the predict method, enabling the model instance to be callable for predictions.
156
+
157
+ This method simplifies the process of making predictions by allowing the model instance to be called directly
158
+ with the required arguments.
159
+
160
+ Args:
161
+ source (str | Path | int | PIL.Image | np.ndarray | torch.Tensor | list | tuple): The source of the image(s)
162
+ to make predictions on. Can be a file path, URL, PIL image, numpy array, PyTorch tensor, or a list/tuple
163
+ of these.
164
+ stream (bool): If True, treat the input source as a continuous stream for predictions.
165
+ **kwargs (Any): Additional keyword arguments to configure the prediction process.
166
+
167
+ Returns:
168
+ (list[ultralytics.engine.results.Results]): A list of prediction results, each encapsulated in a Results
169
+ object.
170
+
171
+ Examples:
172
+ >>> model = YOLO("yolo11n.pt")
173
+ >>> results = model("https://ultralytics.com/images/bus.jpg")
174
+ >>> for r in results:
175
+ ... print(f"Detected {len(r)} objects in image")
176
+ """
177
+ return self.predict(source, stream, **kwargs)
178
+
179
+ @staticmethod
180
+ def is_triton_model(model: str) -> bool:
181
+ """Check if the given model string is a Triton Server URL.
182
+
183
+ This static method determines whether the provided model string represents a valid Triton Server URL by parsing
184
+ its components using urllib.parse.urlsplit().
185
+
186
+ Args:
187
+ model (str): The model string to be checked.
188
+
189
+ Returns:
190
+ (bool): True if the model string is a valid Triton Server URL, False otherwise.
191
+
192
+ Examples:
193
+ >>> Model.is_triton_model("http://localhost:8000/v2/models/yolo11n")
194
+ True
195
+ >>> Model.is_triton_model("yolo11n.pt")
196
+ False
197
+ """
198
+ from urllib.parse import urlsplit
199
+
200
+ url = urlsplit(model)
201
+ return url.netloc and url.path and url.scheme in {"http", "grpc"}
202
+
203
+ @staticmethod
204
+ def is_hub_model(model: str) -> bool:
205
+ """Check if the provided model is an Ultralytics HUB model.
206
+
207
+ This static method determines whether the given model string represents a valid Ultralytics HUB model
208
+ identifier.
209
+
210
+ Args:
211
+ model (str): The model string to check.
212
+
213
+ Returns:
214
+ (bool): True if the model is a valid Ultralytics HUB model, False otherwise.
215
+
216
+ Examples:
217
+ >>> Model.is_hub_model("https://hub.ultralytics.com/models/MODEL")
218
+ True
219
+ >>> Model.is_hub_model("yolo11n.pt")
220
+ False
221
+ """
222
+ from ultralytics.hub import HUB_WEB_ROOT
223
+
224
+ return model.startswith(f"{HUB_WEB_ROOT}/models/")
225
+
226
+ def _new(self, cfg: str, task=None, model=None, verbose=False) -> None:
227
+ """Initialize a new model and infer the task type from model definitions.
228
+
229
+ Creates a new model instance based on the provided configuration file. Loads the model configuration, infers the
230
+ task type if not specified, and initializes the model using the appropriate class from the task map.
231
+
232
+ Args:
233
+ cfg (str): Path to the model configuration file in YAML format.
234
+ task (str, optional): The specific task for the model. If None, it will be inferred from the config.
235
+ model (torch.nn.Module, optional): A custom model instance. If provided, it will be used instead of creating
236
+ a new one.
237
+ verbose (bool): If True, displays model information during loading.
238
+
239
+ Raises:
240
+ ValueError: If the configuration file is invalid or the task cannot be inferred.
241
+ ImportError: If the required dependencies for the specified task are not installed.
242
+
243
+ Examples:
244
+ >>> model = Model()
245
+ >>> model._new("yolo11n.yaml", task="detect", verbose=True)
246
+ """
247
+ cfg_dict = yaml_model_load(cfg)
248
+ self.cfg = cfg
249
+ self.task = task or guess_model_task(cfg_dict)
250
+ self.model = (model or self._smart_load("model"))(cfg_dict, verbose=verbose and RANK == -1) # build model
251
+ self.overrides["model"] = self.cfg
252
+ self.overrides["task"] = self.task
253
+
254
+ # Below added to allow export from YAMLs
255
+ self.model.args = {**DEFAULT_CFG_DICT, **self.overrides} # combine default and model args (prefer model args)
256
+ self.model.task = self.task
257
+ self.model_name = cfg
258
+
259
+ def _load(self, weights: str, task=None) -> None:
260
+ """Load a model from a checkpoint file or initialize it from a weights file.
261
+
262
+ This method handles loading models from either .pt checkpoint files or other weight file formats. It sets up the
263
+ model, task, and related attributes based on the loaded weights.
264
+
265
+ Args:
266
+ weights (str): Path to the model weights file to be loaded.
267
+ task (str, optional): The task associated with the model. If None, it will be inferred from the model.
268
+
269
+ Raises:
270
+ FileNotFoundError: If the specified weights file does not exist or is inaccessible.
271
+ ValueError: If the weights file format is unsupported or invalid.
272
+
273
+ Examples:
274
+ >>> model = Model()
275
+ >>> model._load("yolo11n.pt")
276
+ >>> model._load("path/to/weights.pth", task="detect")
277
+ """
278
+ if weights.lower().startswith(("https://", "http://", "rtsp://", "rtmp://", "tcp://", "ul://")):
279
+ weights = checks.check_file(weights, download_dir=SETTINGS["weights_dir"]) # download and return local file
280
+ weights = checks.check_model_file_from_stem(weights) # add suffix, i.e. yolo11n -> yolo11n.pt
281
+
282
+ if str(weights).rpartition(".")[-1] == "pt":
283
+ self.model, self.ckpt = load_checkpoint(weights)
284
+ self.task = self.model.task
285
+ self.overrides = self.model.args = self._reset_ckpt_args(self.model.args)
286
+ self.ckpt_path = self.model.pt_path
287
+ else:
288
+ weights = checks.check_file(weights) # runs in all cases, not redundant with above call
289
+ self.model, self.ckpt = weights, None
290
+ self.task = task or guess_model_task(weights)
291
+ self.ckpt_path = weights
292
+ self.overrides["model"] = weights
293
+ self.overrides["task"] = self.task
294
+ self.model_name = weights
295
+
296
+ def _check_is_pytorch_model(self) -> None:
297
+ """Check if the model is a PyTorch model and raise TypeError if it's not.
298
+
299
+ This method verifies that the model is either a PyTorch module or a .pt file. It's used to ensure that certain
300
+ operations that require a PyTorch model are only performed on compatible model types.
301
+
302
+ Raises:
303
+ TypeError: If the model is not a PyTorch module or a .pt file. The error message provides detailed
304
+ information about supported model formats and operations.
305
+
306
+ Examples:
307
+ >>> model = Model("yolo11n.pt")
308
+ >>> model._check_is_pytorch_model() # No error raised
309
+ >>> model = Model("yolo11n.onnx")
310
+ >>> model._check_is_pytorch_model() # Raises TypeError
311
+ """
312
+ pt_str = isinstance(self.model, (str, Path)) and str(self.model).rpartition(".")[-1] == "pt"
313
+ pt_module = isinstance(self.model, torch.nn.Module)
314
+ if not (pt_module or pt_str):
315
+ raise TypeError(
316
+ f"model='{self.model}' should be a *.pt PyTorch model to run this method, but is a different format. "
317
+ f"PyTorch models can train, val, predict and export, i.e. 'model.train(data=...)', but exported "
318
+ f"formats like ONNX, TensorRT etc. only support 'predict' and 'val' modes, "
319
+ f"i.e. 'yolo predict model=yolo11n.onnx'.\nTo run CUDA or MPS inference please pass the device "
320
+ f"argument directly in your inference command, i.e. 'model.predict(source=..., device=0)'"
321
+ )
322
+
323
+ def reset_weights(self) -> Model:
324
+ """Reset the model's weights to their initial state.
325
+
326
+ This method iterates through all modules in the model and resets their parameters if they have a
327
+ 'reset_parameters' method. It also ensures that all parameters have 'requires_grad' set to True, enabling them
328
+ to be updated during training.
329
+
330
+ Returns:
331
+ (Model): The instance of the class with reset weights.
332
+
333
+ Raises:
334
+ AssertionError: If the model is not a PyTorch model.
335
+
336
+ Examples:
337
+ >>> model = Model("yolo11n.pt")
338
+ >>> model.reset_weights()
339
+ """
340
+ self._check_is_pytorch_model()
341
+ for m in self.model.modules():
342
+ if hasattr(m, "reset_parameters"):
343
+ m.reset_parameters()
344
+ for p in self.model.parameters():
345
+ p.requires_grad = True
346
+ return self
347
+
348
+ def load(self, weights: str | Path = "yolo11n.pt") -> Model:
349
+ """Load parameters from the specified weights file into the model.
350
+
351
+ This method supports loading weights from a file or directly from a weights object. It matches parameters by
352
+ name and shape and transfers them to the model.
353
+
354
+ Args:
355
+ weights (str | Path): Path to the weights file or a weights object.
356
+
357
+ Returns:
358
+ (Model): The instance of the class with loaded weights.
359
+
360
+ Raises:
361
+ AssertionError: If the model is not a PyTorch model.
362
+
363
+ Examples:
364
+ >>> model = Model()
365
+ >>> model.load("yolo11n.pt")
366
+ >>> model.load(Path("path/to/weights.pt"))
367
+ """
368
+ self._check_is_pytorch_model()
369
+ if isinstance(weights, (str, Path)):
370
+ self.overrides["pretrained"] = weights # remember the weights for DDP training
371
+ weights, self.ckpt = load_checkpoint(weights)
372
+ self.model.load(weights)
373
+ return self
374
+
375
+ def save(self, filename: str | Path = "saved_model.pt") -> None:
376
+ """Save the current model state to a file.
377
+
378
+ This method exports the model's checkpoint (ckpt) to the specified filename. It includes metadata such as the
379
+ date, Ultralytics version, license information, and a link to the documentation.
380
+
381
+ Args:
382
+ filename (str | Path): The name of the file to save the model to.
383
+
384
+ Raises:
385
+ AssertionError: If the model is not a PyTorch model.
386
+
387
+ Examples:
388
+ >>> model = Model("yolo11n.pt")
389
+ >>> model.save("my_model.pt")
390
+ """
391
+ self._check_is_pytorch_model()
392
+ from copy import deepcopy
393
+ from datetime import datetime
394
+
395
+ from ultralytics import __version__
396
+
397
+ updates = {
398
+ "model": deepcopy(self.model).half() if isinstance(self.model, torch.nn.Module) else self.model,
399
+ "date": datetime.now().isoformat(),
400
+ "version": __version__,
401
+ "license": "AGPL-3.0 License (https://ultralytics.com/license)",
402
+ "docs": "https://docs.ultralytics.com",
403
+ }
404
+ torch.save({**self.ckpt, **updates}, filename)
405
+
406
+ def info(self, detailed: bool = False, verbose: bool = True, imgsz: int | list[int, int] = 640):
407
+ """Display model information.
408
+
409
+ This method provides an overview or detailed information about the model, depending on the arguments
410
+ passed. It can control the verbosity of the output and return the information as a list.
411
+
412
+ Args:
413
+ detailed (bool): If True, shows detailed information about the model layers and parameters.
414
+ verbose (bool): If True, prints the information. If False, returns the information as a list.
415
+ imgsz (int | list[int, int]): Input image size used for FLOPs calculation.
416
+
417
+ Returns:
418
+ (list[str]): A list of strings containing various types of information about the model, including model
419
+ summary, layer details, and parameter counts. Empty if verbose is True.
420
+
421
+ Examples:
422
+ >>> model = Model("yolo11n.pt")
423
+ >>> model.info() # Prints model summary
424
+ >>> info_list = model.info(detailed=True, verbose=False) # Returns detailed info as a list
425
+ """
426
+ self._check_is_pytorch_model()
427
+ return self.model.info(detailed=detailed, verbose=verbose, imgsz=imgsz)
428
+
429
+ def fuse(self) -> None:
430
+ """Fuse Conv2d and BatchNorm2d layers in the model for optimized inference.
431
+
432
+ This method iterates through the model's modules and fuses consecutive Conv2d and BatchNorm2d layers into a
433
+ single layer. This fusion can significantly improve inference speed by reducing the number of operations and
434
+ memory accesses required during forward passes.
435
+
436
+ The fusion process typically involves folding the BatchNorm2d parameters (mean, variance, weight, and
437
+ bias) into the preceding Conv2d layer's weights and biases. This results in a single Conv2d layer that
438
+ performs both convolution and normalization in one step.
439
+
440
+ Examples:
441
+ >>> model = Model("yolo11n.pt")
442
+ >>> model.fuse()
443
+ >>> # Model is now fused and ready for optimized inference
444
+ """
445
+ self._check_is_pytorch_model()
446
+ self.model.fuse()
447
+
448
+ def embed(
449
+ self,
450
+ source: str | Path | int | list | tuple | np.ndarray | torch.Tensor = None,
451
+ stream: bool = False,
452
+ **kwargs: Any,
453
+ ) -> list:
454
+ """Generate image embeddings based on the provided source.
455
+
456
+ This method is a wrapper around the 'predict()' method, focusing on generating embeddings from an image
457
+ source. It allows customization of the embedding process through various keyword arguments.
458
+
459
+ Args:
460
+ source (str | Path | int | list | tuple | np.ndarray | torch.Tensor): The source of the image for generating
461
+ embeddings. Can be a file path, URL, PIL image, numpy array, etc.
462
+ stream (bool): If True, predictions are streamed.
463
+ **kwargs (Any): Additional keyword arguments for configuring the embedding process.
464
+
465
+ Returns:
466
+ (list[torch.Tensor]): A list containing the image embeddings.
467
+
468
+ Examples:
469
+ >>> model = YOLO("yolo11n.pt")
470
+ >>> image = "https://ultralytics.com/images/bus.jpg"
471
+ >>> embeddings = model.embed(image)
472
+ >>> print(embeddings[0].shape)
473
+ """
474
+ if not kwargs.get("embed"):
475
+ kwargs["embed"] = [len(self.model.model) - 2] # embed second-to-last layer if no indices passed
476
+ return self.predict(source, stream, **kwargs)
477
+
478
+ def predict(
479
+ self,
480
+ source: str | Path | int | Image.Image | list | tuple | np.ndarray | torch.Tensor = None,
481
+ stream: bool = False,
482
+ predictor=None,
483
+ **kwargs: Any,
484
+ ) -> list[Results]:
485
+ """Perform predictions on the given image source using the YOLO model.
486
+
487
+ This method facilitates the prediction process, allowing various configurations through keyword arguments. It
488
+ supports predictions with custom predictors or the default predictor method. The method handles different types
489
+ of image sources and can operate in a streaming mode.
490
+
491
+ Args:
492
+ source (str | Path | int | PIL.Image | np.ndarray | torch.Tensor | list | tuple): The source of the image(s)
493
+ to make predictions on. Accepts various types including file paths, URLs, PIL images, numpy arrays, and
494
+ torch tensors.
495
+ stream (bool): If True, treats the input source as a continuous stream for predictions.
496
+ predictor (BasePredictor, optional): An instance of a custom predictor class for making predictions. If
497
+ None, the method uses a default predictor.
498
+ **kwargs (Any): Additional keyword arguments for configuring the prediction process.
499
+
500
+ Returns:
501
+ (list[ultralytics.engine.results.Results]): A list of prediction results, each encapsulated in a Results
502
+ object.
503
+
504
+ Examples:
505
+ >>> model = YOLO("yolo11n.pt")
506
+ >>> results = model.predict(source="path/to/image.jpg", conf=0.25)
507
+ >>> for r in results:
508
+ ... print(r.boxes.data) # print detection bounding boxes
509
+
510
+ Notes:
511
+ - If 'source' is not provided, it defaults to the ASSETS constant with a warning.
512
+ - The method sets up a new predictor if not already present and updates its arguments with each call.
513
+ - For SAM-type models, 'prompts' can be passed as a keyword argument.
514
+ """
515
+ if source is None:
516
+ source = "https://ultralytics.com/images/boats.jpg" if self.task == "obb" else ASSETS
517
+ LOGGER.warning(f"'source' is missing. Using 'source={source}'.")
518
+
519
+ is_cli = (ARGV[0].endswith("yolo") or ARGV[0].endswith("ultralytics")) and any(
520
+ x in ARGV for x in ("predict", "track", "mode=predict", "mode=track")
521
+ )
522
+
523
+ custom = {"conf": 0.25, "batch": 1, "save": is_cli, "mode": "predict", "rect": True} # method defaults
524
+ args = {**self.overrides, **custom, **kwargs} # highest priority args on the right
525
+ prompts = args.pop("prompts", None) # for SAM-type models
526
+
527
+ if not self.predictor or self.predictor.args.device != args.get("device", self.predictor.args.device):
528
+ self.predictor = (predictor or self._smart_load("predictor"))(overrides=args, _callbacks=self.callbacks)
529
+ self.predictor.setup_model(model=self.model, verbose=is_cli)
530
+ else: # only update args if predictor is already setup
531
+ self.predictor.args = get_cfg(self.predictor.args, args)
532
+ if "project" in args or "name" in args:
533
+ self.predictor.save_dir = get_save_dir(self.predictor.args)
534
+ if prompts and hasattr(self.predictor, "set_prompts"): # for SAM-type models
535
+ self.predictor.set_prompts(prompts)
536
+ return self.predictor.predict_cli(source=source) if is_cli else self.predictor(source=source, stream=stream)
537
+
538
+ def track(
539
+ self,
540
+ source: str | Path | int | list | tuple | np.ndarray | torch.Tensor = None,
541
+ stream: bool = False,
542
+ persist: bool = False,
543
+ **kwargs: Any,
544
+ ) -> list[Results]:
545
+ """Conduct object tracking on the specified input source using the registered trackers.
546
+
547
+ This method performs object tracking using the model's predictors and optionally registered trackers. It handles
548
+ various input sources such as file paths or video streams, and supports customization through keyword arguments.
549
+ The method registers trackers if not already present and can persist them between calls.
550
+
551
+ Args:
552
+ source (str | Path | int | list | tuple | np.ndarray | torch.Tensor, optional): Input source for object
553
+ tracking. Can be a file path, URL, or video stream.
554
+ stream (bool): If True, treats the input source as a continuous video stream.
555
+ persist (bool): If True, persists trackers between different calls to this method.
556
+ **kwargs (Any): Additional keyword arguments for configuring the tracking process.
557
+
558
+ Returns:
559
+ (list[ultralytics.engine.results.Results]): A list of tracking results, each a Results object.
560
+
561
+ Examples:
562
+ >>> model = YOLO("yolo11n.pt")
563
+ >>> results = model.track(source="path/to/video.mp4", show=True)
564
+ >>> for r in results:
565
+ ... print(r.boxes.id) # print tracking IDs
566
+
567
+ Notes:
568
+ - This method sets a default confidence threshold of 0.1 for ByteTrack-based tracking.
569
+ - The tracking mode is explicitly set in the keyword arguments.
570
+ - Batch size is set to 1 for tracking in videos.
571
+ """
572
+ if not hasattr(self.predictor, "trackers"):
573
+ from ultralytics.trackers import register_tracker
574
+
575
+ register_tracker(self, persist)
576
+ kwargs["conf"] = kwargs.get("conf") or 0.1 # ByteTrack-based method needs low confidence predictions as input
577
+ kwargs["batch"] = kwargs.get("batch") or 1 # batch-size 1 for tracking in videos
578
+ kwargs["mode"] = "track"
579
+ return self.predict(source=source, stream=stream, **kwargs)
580
+
581
+ def val(
582
+ self,
583
+ validator=None,
584
+ **kwargs: Any,
585
+ ):
586
+ """Validate the model using a specified dataset and validation configuration.
587
+
588
+ This method facilitates the model validation process, allowing for customization through various settings. It
589
+ supports validation with a custom validator or the default validation approach. The method combines default
590
+ configurations, method-specific defaults, and user-provided arguments to configure the validation process.
591
+
592
+ Args:
593
+ validator (ultralytics.engine.validator.BaseValidator, optional): An instance of a custom validator class
594
+ for validating the model.
595
+ **kwargs (Any): Arbitrary keyword arguments for customizing the validation process.
596
+
597
+ Returns:
598
+ (ultralytics.utils.metrics.DetMetrics): Validation metrics obtained from the validation process.
599
+
600
+ Raises:
601
+ AssertionError: If the model is not a PyTorch model.
602
+
603
+ Examples:
604
+ >>> model = YOLO("yolo11n.pt")
605
+ >>> results = model.val(data="coco8.yaml", imgsz=640)
606
+ >>> print(results.box.map) # Print mAP50-95
607
+ """
608
+ custom = {"rect": True} # method defaults
609
+ args = {**self.overrides, **custom, **kwargs, "mode": "val"} # highest priority args on the right
610
+
611
+ validator = (validator or self._smart_load("validator"))(args=args, _callbacks=self.callbacks)
612
+ validator(model=self.model)
613
+ self.metrics = validator.metrics
614
+ return validator.metrics
615
+
616
+ def benchmark(self, data=None, format="", verbose=False, **kwargs: Any):
617
+ """Benchmark the model across various export formats to evaluate performance.
618
+
619
+ This method assesses the model's performance in different export formats, such as ONNX, TorchScript, etc. It
620
+ uses the 'benchmark' function from the ultralytics.utils.benchmarks module. The benchmarking is configured using
621
+ a combination of default configuration values, model-specific arguments, method-specific defaults, and any
622
+ additional user-provided keyword arguments.
623
+
624
+ Args:
625
+ data (str): Path to the dataset for benchmarking.
626
+ verbose (bool): Whether to print detailed benchmark information.
627
+ format (str): Export format name for specific benchmarking.
628
+ **kwargs (Any): Arbitrary keyword arguments to customize the benchmarking process. Common options include:
629
+ - imgsz (int | list[int]): Image size for benchmarking.
630
+ - half (bool): Whether to use half-precision (FP16) mode.
631
+ - int8 (bool): Whether to use int8 precision mode.
632
+ - device (str): Device to run the benchmark on (e.g., 'cpu', 'cuda').
633
+
634
+ Returns:
635
+ (dict): A dictionary containing the results of the benchmarking process, including metrics for different
636
+ export formats.
637
+
638
+ Raises:
639
+ AssertionError: If the model is not a PyTorch model.
640
+
641
+ Examples:
642
+ >>> model = YOLO("yolo11n.pt")
643
+ >>> results = model.benchmark(data="coco8.yaml", imgsz=640, half=True)
644
+ >>> print(results)
645
+ """
646
+ self._check_is_pytorch_model()
647
+ from ultralytics.utils.benchmarks import benchmark
648
+
649
+ from .exporter import export_formats
650
+
651
+ custom = {"verbose": False} # method defaults
652
+ args = {**DEFAULT_CFG_DICT, **self.model.args, **custom, **kwargs, "mode": "benchmark"}
653
+ fmts = export_formats()
654
+ export_args = set(dict(zip(fmts["Argument"], fmts["Arguments"])).get(format, [])) - {"batch"}
655
+ export_kwargs = {k: v for k, v in args.items() if k in export_args}
656
+ return benchmark(
657
+ model=self,
658
+ data=data, # if no 'data' argument passed set data=None for default datasets
659
+ imgsz=args["imgsz"],
660
+ device=args["device"],
661
+ verbose=verbose,
662
+ format=format,
663
+ **export_kwargs,
664
+ )
665
+
666
+ def export(
667
+ self,
668
+ **kwargs: Any,
669
+ ) -> str:
670
+ """Export the model to a different format suitable for deployment.
671
+
672
+ This method facilitates the export of the model to various formats (e.g., ONNX, TorchScript) for deployment
673
+ purposes. It uses the 'Exporter' class for the export process, combining model-specific overrides, method
674
+ defaults, and any additional arguments provided.
675
+
676
+ Args:
677
+ **kwargs (Any): Arbitrary keyword arguments for export configuration. Common options include:
678
+ - format (str): Export format (e.g., 'onnx', 'engine', 'coreml').
679
+ - half (bool): Export model in half-precision.
680
+ - int8 (bool): Export model in int8 precision.
681
+ - device (str): Device to run the export on.
682
+ - workspace (int): Maximum memory workspace size for TensorRT engines.
683
+ - nms (bool): Add Non-Maximum Suppression (NMS) module to model.
684
+ - simplify (bool): Simplify ONNX model.
685
+
686
+ Returns:
687
+ (str): The path to the exported model file.
688
+
689
+ Raises:
690
+ AssertionError: If the model is not a PyTorch model.
691
+ ValueError: If an unsupported export format is specified.
692
+ RuntimeError: If the export process fails due to errors.
693
+
694
+ Examples:
695
+ >>> model = YOLO("yolo11n.pt")
696
+ >>> model.export(format="onnx", dynamic=True, simplify=True)
697
+ 'path/to/exported/model.onnx'
698
+ """
699
+ self._check_is_pytorch_model()
700
+ from .exporter import Exporter
701
+
702
+ custom = {
703
+ "imgsz": self.model.args["imgsz"],
704
+ "batch": 1,
705
+ "data": None,
706
+ "device": None, # reset to avoid multi-GPU errors
707
+ "verbose": False,
708
+ } # method defaults
709
+ args = {**self.overrides, **custom, **kwargs, "mode": "export"} # highest priority args on the right
710
+ return Exporter(overrides=args, _callbacks=self.callbacks)(model=self.model)
711
+
712
+ def train(
713
+ self,
714
+ trainer=None,
715
+ **kwargs: Any,
716
+ ):
717
+ """Train the model using the specified dataset and training configuration.
718
+
719
+ This method facilitates model training with a range of customizable settings. It supports training with a custom
720
+ trainer or the default training approach. The method handles scenarios such as resuming training from a
721
+ checkpoint, integrating with Ultralytics HUB, and updating model and configuration after training.
722
+
723
+ When using Ultralytics HUB, if the session has a loaded model, the method prioritizes HUB training arguments and
724
+ warns if local arguments are provided. It checks for pip updates and combines default configurations,
725
+ method-specific defaults, and user-provided arguments to configure the training process.
726
+
727
+ Args:
728
+ trainer (BaseTrainer, optional): Custom trainer instance for model training. If None, uses default.
729
+ **kwargs (Any): Arbitrary keyword arguments for training configuration. Common options include:
730
+ - data (str): Path to dataset configuration file.
731
+ - epochs (int): Number of training epochs.
732
+ - batch (int): Batch size for training.
733
+ - imgsz (int): Input image size.
734
+ - device (str): Device to run training on (e.g., 'cuda', 'cpu').
735
+ - workers (int): Number of worker threads for data loading.
736
+ - optimizer (str): Optimizer to use for training.
737
+ - lr0 (float): Initial learning rate.
738
+ - patience (int): Epochs to wait for no observable improvement for early stopping of training.
739
+ - augmentations (list[Callable]): List of augmentation functions to apply during training.
740
+
741
+ Returns:
742
+ (dict | None): Training metrics if available and training is successful; otherwise, None.
743
+
744
+ Examples:
745
+ >>> model = YOLO("yolo11n.pt")
746
+ >>> results = model.train(data="coco8.yaml", epochs=3)
747
+ """
748
+ self._check_is_pytorch_model()
749
+ if hasattr(self.session, "model") and self.session.model.id: # Ultralytics HUB session with loaded model
750
+ if any(kwargs):
751
+ LOGGER.warning("using HUB training arguments, ignoring local training arguments.")
752
+ kwargs = self.session.train_args # overwrite kwargs
753
+
754
+ checks.check_pip_update_available()
755
+
756
+ if isinstance(kwargs.get("pretrained", None), (str, Path)):
757
+ self.load(kwargs["pretrained"]) # load pretrained weights if provided
758
+ overrides = YAML.load(checks.check_yaml(kwargs["cfg"])) if kwargs.get("cfg") else self.overrides
759
+ custom = {
760
+ # NOTE: handle the case when 'cfg' includes 'data'.
761
+ "data": overrides.get("data") or DEFAULT_CFG_DICT["data"] or TASK2DATA[self.task],
762
+ "model": self.overrides["model"],
763
+ "task": self.task,
764
+ } # method defaults
765
+ args = {**overrides, **custom, **kwargs, "mode": "train", "session": self.session} # prioritizes rightmost args
766
+ if args.get("resume"):
767
+ args["resume"] = self.ckpt_path
768
+
769
+ self.trainer = (trainer or self._smart_load("trainer"))(overrides=args, _callbacks=self.callbacks)
770
+ if not args.get("resume"): # manually set model only if not resuming
771
+ self.trainer.model = self.trainer.get_model(weights=self.model if self.ckpt else None, cfg=self.model.yaml)
772
+ self.model = self.trainer.model
773
+
774
+ self.trainer.train()
775
+ # Update model and cfg after training
776
+ if RANK in {-1, 0}:
777
+ ckpt = self.trainer.best if self.trainer.best.exists() else self.trainer.last
778
+ self.model, self.ckpt = load_checkpoint(ckpt)
779
+ self.overrides = self._reset_ckpt_args(self.model.args)
780
+ self.metrics = getattr(self.trainer.validator, "metrics", None) # TODO: no metrics returned by DDP
781
+ return self.metrics
782
+
783
+ def tune(
784
+ self,
785
+ use_ray=False,
786
+ iterations=10,
787
+ *args: Any,
788
+ **kwargs: Any,
789
+ ):
790
+ """Conduct hyperparameter tuning for the model, with an option to use Ray Tune.
791
+
792
+ This method supports two modes of hyperparameter tuning: using Ray Tune or a custom tuning method. When Ray Tune
793
+ is enabled, it leverages the 'run_ray_tune' function from the ultralytics.utils.tuner module. Otherwise, it uses
794
+ the internal 'Tuner' class for tuning. The method combines default, overridden, and custom arguments to
795
+ configure the tuning process.
796
+
797
+ Args:
798
+ use_ray (bool): Whether to use Ray Tune for hyperparameter tuning. If False, uses internal tuning method.
799
+ iterations (int): Number of tuning iterations to perform.
800
+ *args (Any): Additional positional arguments to pass to the tuner.
801
+ **kwargs (Any): Additional keyword arguments for tuning configuration. These are combined with model
802
+ overrides and defaults to configure the tuning process.
803
+
804
+ Returns:
805
+ (dict): Results of the hyperparameter search, including best parameters and performance metrics.
806
+
807
+ Raises:
808
+ TypeError: If the model is not a PyTorch model.
809
+
810
+ Examples:
811
+ >>> model = YOLO("yolo11n.pt")
812
+ >>> results = model.tune(data="coco8.yaml", iterations=5)
813
+ >>> print(results)
814
+
815
+ # Use Ray Tune for more advanced hyperparameter search
816
+ >>> results = model.tune(use_ray=True, iterations=20, data="coco8.yaml")
817
+ """
818
+ self._check_is_pytorch_model()
819
+ if use_ray:
820
+ from ultralytics.utils.tuner import run_ray_tune
821
+
822
+ return run_ray_tune(self, max_samples=iterations, *args, **kwargs)
823
+ else:
824
+ from .tuner import Tuner
825
+
826
+ custom = {} # method defaults
827
+ args = {**self.overrides, **custom, **kwargs, "mode": "train"} # highest priority args on the right
828
+ return Tuner(args=args, _callbacks=self.callbacks)(model=self, iterations=iterations)
829
+
830
+ def _apply(self, fn) -> Model:
831
+ """Apply a function to model tensors that are not parameters or registered buffers.
832
+
833
+ This method extends the functionality of the parent class's _apply method by additionally resetting the
834
+ predictor and updating the device in the model's overrides. It's typically used for operations like moving the
835
+ model to a different device or changing its precision.
836
+
837
+ Args:
838
+ fn (Callable): A function to be applied to the model's tensors. This is typically a method like to(), cpu(),
839
+ cuda(), half(), or float().
840
+
841
+ Returns:
842
+ (Model): The model instance with the function applied and updated attributes.
843
+
844
+ Raises:
845
+ AssertionError: If the model is not a PyTorch model.
846
+
847
+ Examples:
848
+ >>> model = Model("yolo11n.pt")
849
+ >>> model = model._apply(lambda t: t.cuda()) # Move model to GPU
850
+ """
851
+ self._check_is_pytorch_model()
852
+ self = super()._apply(fn)
853
+ self.predictor = None # reset predictor as device may have changed
854
+ self.overrides["device"] = self.device # was str(self.device) i.e. device(type='cuda', index=0) -> 'cuda:0'
855
+ return self
856
+
857
+ @property
858
+ def names(self) -> dict[int, str]:
859
+ """Retrieve the class names associated with the loaded model.
860
+
861
+ This property returns the class names if they are defined in the model. It checks the class names for validity
862
+ using the 'check_class_names' function from the ultralytics.nn.autobackend module. If the predictor is not
863
+ initialized, it sets it up before retrieving the names.
864
+
865
+ Returns:
866
+ (dict[int, str]): A dictionary of class names associated with the model, where keys are class indices and
867
+ values are the corresponding class names.
868
+
869
+ Raises:
870
+ AttributeError: If the model or predictor does not have a 'names' attribute.
871
+
872
+ Examples:
873
+ >>> model = YOLO("yolo11n.pt")
874
+ >>> print(model.names)
875
+ {0: 'person', 1: 'bicycle', 2: 'car', ...}
876
+ """
877
+ from ultralytics.nn.autobackend import check_class_names
878
+
879
+ if hasattr(self.model, "names"):
880
+ return check_class_names(self.model.names)
881
+ if not self.predictor: # export formats will not have predictor defined until predict() is called
882
+ predictor = self._smart_load("predictor")(overrides=self.overrides, _callbacks=self.callbacks)
883
+ predictor.setup_model(model=self.model, verbose=False) # do not mess with self.predictor.model args
884
+ return predictor.model.names
885
+ return self.predictor.model.names
886
+
887
+ @property
888
+ def device(self) -> torch.device:
889
+ """Get the device on which the model's parameters are allocated.
890
+
891
+ This property determines the device (CPU or GPU) where the model's parameters are currently stored. It is
892
+ applicable only to models that are instances of torch.nn.Module.
893
+
894
+ Returns:
895
+ (torch.device): The device (CPU/GPU) of the model.
896
+
897
+ Raises:
898
+ AttributeError: If the model is not a torch.nn.Module instance.
899
+
900
+ Examples:
901
+ >>> model = YOLO("yolo11n.pt")
902
+ >>> print(model.device)
903
+ device(type='cuda', index=0) # if CUDA is available
904
+ >>> model = model.to("cpu")
905
+ >>> print(model.device)
906
+ device(type='cpu')
907
+ """
908
+ return next(self.model.parameters()).device if isinstance(self.model, torch.nn.Module) else None
909
+
910
+ @property
911
+ def transforms(self):
912
+ """Retrieve the transformations applied to the input data of the loaded model.
913
+
914
+ This property returns the transformations if they are defined in the model. The transforms typically include
915
+ preprocessing steps like resizing, normalization, and data augmentation that are applied to input data before it
916
+ is fed into the model.
917
+
918
+ Returns:
919
+ (object | None): The transform object of the model if available, otherwise None.
920
+
921
+ Examples:
922
+ >>> model = YOLO("yolo11n.pt")
923
+ >>> transforms = model.transforms
924
+ >>> if transforms:
925
+ ... print(f"Model transforms: {transforms}")
926
+ ... else:
927
+ ... print("No transforms defined for this model.")
928
+ """
929
+ return self.model.transforms if hasattr(self.model, "transforms") else None
930
+
931
+ def add_callback(self, event: str, func) -> None:
932
+ """Add a callback function for a specified event.
933
+
934
+ This method allows registering custom callback functions that are triggered on specific events during model
935
+ operations such as training or inference. Callbacks provide a way to extend and customize the behavior of the
936
+ model at various stages of its lifecycle.
937
+
938
+ Args:
939
+ event (str): The name of the event to attach the callback to. Must be a valid event name recognized by the
940
+ Ultralytics framework.
941
+ func (Callable): The callback function to be registered. This function will be called when the specified
942
+ event occurs.
943
+
944
+ Raises:
945
+ ValueError: If the event name is not recognized or is invalid.
946
+
947
+ Examples:
948
+ >>> def on_train_start(trainer):
949
+ ... print("Training is starting!")
950
+ >>> model = YOLO("yolo11n.pt")
951
+ >>> model.add_callback("on_train_start", on_train_start)
952
+ >>> model.train(data="coco8.yaml", epochs=1)
953
+ """
954
+ self.callbacks[event].append(func)
955
+
956
+ def clear_callback(self, event: str) -> None:
957
+ """Clear all callback functions registered for a specified event.
958
+
959
+ This method removes all custom and default callback functions associated with the given event. It resets the
960
+ callback list for the specified event to an empty list, effectively removing all registered callbacks for that
961
+ event.
962
+
963
+ Args:
964
+ event (str): The name of the event for which to clear the callbacks. This should be a valid event name
965
+ recognized by the Ultralytics callback system.
966
+
967
+ Examples:
968
+ >>> model = YOLO("yolo11n.pt")
969
+ >>> model.add_callback("on_train_start", lambda: print("Training started"))
970
+ >>> model.clear_callback("on_train_start")
971
+ >>> # All callbacks for 'on_train_start' are now removed
972
+
973
+ Notes:
974
+ - This method affects both custom callbacks added by the user and default callbacks
975
+ provided by the Ultralytics framework.
976
+ - After calling this method, no callbacks will be executed for the specified event
977
+ until new ones are added.
978
+ - Use with caution as it removes all callbacks, including essential ones that might
979
+ be required for proper functioning of certain operations.
980
+ """
981
+ self.callbacks[event] = []
982
+
983
+ def reset_callbacks(self) -> None:
984
+ """Reset all callbacks to their default functions.
985
+
986
+ This method reinstates the default callback functions for all events, removing any custom callbacks that were
987
+ previously added. It iterates through all default callback events and replaces the current callbacks with the
988
+ default ones.
989
+
990
+ The default callbacks are defined in the 'callbacks.default_callbacks' dictionary, which contains predefined
991
+ functions for various events in the model's lifecycle, such as on_train_start, on_epoch_end, etc.
992
+
993
+ This method is useful when you want to revert to the original set of callbacks after making custom
994
+ modifications, ensuring consistent behavior across different runs or experiments.
995
+
996
+ Examples:
997
+ >>> model = YOLO("yolo11n.pt")
998
+ >>> model.add_callback("on_train_start", custom_function)
999
+ >>> model.reset_callbacks()
1000
+ # All callbacks are now reset to their default functions
1001
+ """
1002
+ for event in callbacks.default_callbacks.keys():
1003
+ self.callbacks[event] = [callbacks.default_callbacks[event][0]]
1004
+
1005
+ @staticmethod
1006
+ def _reset_ckpt_args(args: dict[str, Any]) -> dict[str, Any]:
1007
+ """Reset specific arguments when loading a PyTorch model checkpoint.
1008
+
1009
+ This method filters the input arguments dictionary to retain only a specific set of keys that are considered
1010
+ important for model loading. It's used to ensure that only relevant arguments are preserved when loading a model
1011
+ from a checkpoint, discarding any unnecessary or potentially conflicting settings.
1012
+
1013
+ Args:
1014
+ args (dict): A dictionary containing various model arguments and settings.
1015
+
1016
+ Returns:
1017
+ (dict): A new dictionary containing only the specified include keys from the input arguments.
1018
+
1019
+ Examples:
1020
+ >>> original_args = {"imgsz": 640, "data": "coco.yaml", "task": "detect", "batch": 16, "epochs": 100}
1021
+ >>> reset_args = Model._reset_ckpt_args(original_args)
1022
+ >>> print(reset_args)
1023
+ {'imgsz': 640, 'data': 'coco.yaml', 'task': 'detect'}
1024
+ """
1025
+ include = {"imgsz", "data", "task", "single_cls"} # only remember these arguments when loading a PyTorch model
1026
+ return {k: v for k, v in args.items() if k in include}
1027
+
1028
+ # def __getattr__(self, attr):
1029
+ # """Raises error if object has no requested attribute."""
1030
+ # name = self.__class__.__name__
1031
+ # raise AttributeError(f"'{name}' object has no attribute '{attr}'. See valid attributes below.\n{self.__doc__}")
1032
+
1033
+ def _smart_load(self, key: str):
1034
+ """Intelligently load the appropriate module based on the model task.
1035
+
1036
+ This method dynamically selects and returns the correct module (model, trainer, validator, or predictor) based
1037
+ on the current task of the model and the provided key. It uses the task_map dictionary to determine the
1038
+ appropriate module to load for the specific task.
1039
+
1040
+ Args:
1041
+ key (str): The type of module to load. Must be one of 'model', 'trainer', 'validator', or 'predictor'.
1042
+
1043
+ Returns:
1044
+ (object): The loaded module class corresponding to the specified key and current task.
1045
+
1046
+ Raises:
1047
+ NotImplementedError: If the specified key is not supported for the current task.
1048
+
1049
+ Examples:
1050
+ >>> model = Model(task="detect")
1051
+ >>> predictor_class = model._smart_load("predictor")
1052
+ >>> trainer_class = model._smart_load("trainer")
1053
+ """
1054
+ try:
1055
+ return self.task_map[self.task][key]
1056
+ except Exception as e:
1057
+ name = self.__class__.__name__
1058
+ mode = inspect.stack()[1][3] # get the function name.
1059
+ raise NotImplementedError(f"'{name}' model does not support '{mode}' mode for '{self.task}' task.") from e
1060
+
1061
+ @property
1062
+ def task_map(self) -> dict:
1063
+ """Provide a mapping from model tasks to corresponding classes for different modes.
1064
+
1065
+ This property method returns a dictionary that maps each supported task (e.g., detect, segment, classify) to a
1066
+ nested dictionary. The nested dictionary contains mappings for different operational modes (model, trainer,
1067
+ validator, predictor) to their respective class implementations.
1068
+
1069
+ The mapping allows for dynamic loading of appropriate classes based on the model's task and the desired
1070
+ operational mode. This facilitates a flexible and extensible architecture for handling various tasks and modes
1071
+ within the Ultralytics framework.
1072
+
1073
+ Returns:
1074
+ (dict[str, dict[str, Any]]): A dictionary mapping task names to nested dictionaries. Each nested dictionary
1075
+ contains mappings for 'model', 'trainer', 'validator', and 'predictor' keys to their respective class
1076
+ implementations for that task.
1077
+
1078
+ Examples:
1079
+ >>> model = Model("yolo11n.pt")
1080
+ >>> task_map = model.task_map
1081
+ >>> detect_predictor = task_map["detect"]["predictor"]
1082
+ >>> segment_trainer = task_map["segment"]["trainer"]
1083
+ """
1084
+ raise NotImplementedError("Please provide task map for your model!")
1085
+
1086
+ def eval(self):
1087
+ """Sets the model to evaluation mode.
1088
+
1089
+ This method changes the model's mode to evaluation, which affects layers like dropout and batch normalization
1090
+ that behave differently during training and evaluation. In evaluation mode, these layers use running statistics
1091
+ rather than computing batch statistics, and dropout layers are disabled.
1092
+
1093
+ Returns:
1094
+ (Model): The model instance with evaluation mode set.
1095
+
1096
+ Examples:
1097
+ >>> model = YOLO("yolo11n.pt")
1098
+ >>> model.eval()
1099
+ >>> # Model is now in evaluation mode for inference
1100
+ """
1101
+ self.model.eval()
1102
+ return self
1103
+
1104
+ def __getattr__(self, name):
1105
+ """Enable accessing model attributes directly through the Model class.
1106
+
1107
+ This method provides a way to access attributes of the underlying model directly through the Model class
1108
+ instance. It first checks if the requested attribute is 'model', in which case it returns the model from
1109
+ the module dictionary. Otherwise, it delegates the attribute lookup to the underlying model.
1110
+
1111
+ Args:
1112
+ name (str): The name of the attribute to retrieve.
1113
+
1114
+ Returns:
1115
+ (Any): The requested attribute value.
1116
+
1117
+ Raises:
1118
+ AttributeError: If the requested attribute does not exist in the model.
1119
+
1120
+ Examples:
1121
+ >>> model = YOLO("yolo11n.pt")
1122
+ >>> print(model.stride) # Access model.stride attribute
1123
+ >>> print(model.names) # Access model.names attribute
1124
+ """
1125
+ return self._modules["model"] if name == "model" else getattr(self.model, name)