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