dgenerate-ultralytics-headless 8.3.196__py3-none-any.whl → 8.3.248__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 (243) hide show
  1. {dgenerate_ultralytics_headless-8.3.196.dist-info → dgenerate_ultralytics_headless-8.3.248.dist-info}/METADATA +33 -34
  2. dgenerate_ultralytics_headless-8.3.248.dist-info/RECORD +298 -0
  3. tests/__init__.py +5 -7
  4. tests/conftest.py +8 -15
  5. tests/test_cli.py +8 -10
  6. tests/test_cuda.py +9 -10
  7. tests/test_engine.py +29 -2
  8. tests/test_exports.py +69 -21
  9. tests/test_integrations.py +8 -11
  10. tests/test_python.py +109 -71
  11. tests/test_solutions.py +170 -159
  12. ultralytics/__init__.py +27 -9
  13. ultralytics/cfg/__init__.py +57 -64
  14. ultralytics/cfg/datasets/Argoverse.yaml +7 -6
  15. ultralytics/cfg/datasets/DOTAv1.5.yaml +1 -1
  16. ultralytics/cfg/datasets/DOTAv1.yaml +1 -1
  17. ultralytics/cfg/datasets/ImageNet.yaml +1 -1
  18. ultralytics/cfg/datasets/Objects365.yaml +19 -15
  19. ultralytics/cfg/datasets/SKU-110K.yaml +1 -1
  20. ultralytics/cfg/datasets/VOC.yaml +19 -21
  21. ultralytics/cfg/datasets/VisDrone.yaml +5 -5
  22. ultralytics/cfg/datasets/african-wildlife.yaml +1 -1
  23. ultralytics/cfg/datasets/coco-pose.yaml +24 -2
  24. ultralytics/cfg/datasets/coco.yaml +2 -2
  25. ultralytics/cfg/datasets/coco128-seg.yaml +1 -1
  26. ultralytics/cfg/datasets/coco8-pose.yaml +21 -0
  27. ultralytics/cfg/datasets/construction-ppe.yaml +32 -0
  28. ultralytics/cfg/datasets/dog-pose.yaml +28 -0
  29. ultralytics/cfg/datasets/dota8-multispectral.yaml +1 -1
  30. ultralytics/cfg/datasets/dota8.yaml +2 -2
  31. ultralytics/cfg/datasets/hand-keypoints.yaml +26 -2
  32. ultralytics/cfg/datasets/kitti.yaml +27 -0
  33. ultralytics/cfg/datasets/lvis.yaml +7 -7
  34. ultralytics/cfg/datasets/open-images-v7.yaml +1 -1
  35. ultralytics/cfg/datasets/tiger-pose.yaml +16 -0
  36. ultralytics/cfg/datasets/xView.yaml +16 -16
  37. ultralytics/cfg/default.yaml +96 -94
  38. ultralytics/cfg/models/11/yolo11-pose.yaml +1 -1
  39. ultralytics/cfg/models/11/yoloe-11-seg.yaml +2 -2
  40. ultralytics/cfg/models/11/yoloe-11.yaml +2 -2
  41. ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +1 -1
  42. ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +1 -1
  43. ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +1 -1
  44. ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +1 -1
  45. ultralytics/cfg/models/v10/yolov10b.yaml +2 -2
  46. ultralytics/cfg/models/v10/yolov10l.yaml +2 -2
  47. ultralytics/cfg/models/v10/yolov10m.yaml +2 -2
  48. ultralytics/cfg/models/v10/yolov10n.yaml +2 -2
  49. ultralytics/cfg/models/v10/yolov10s.yaml +2 -2
  50. ultralytics/cfg/models/v10/yolov10x.yaml +2 -2
  51. ultralytics/cfg/models/v3/yolov3-tiny.yaml +1 -1
  52. ultralytics/cfg/models/v6/yolov6.yaml +1 -1
  53. ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +9 -6
  54. ultralytics/cfg/models/v8/yoloe-v8.yaml +9 -6
  55. ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +1 -1
  56. ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +1 -1
  57. ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +2 -2
  58. ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +2 -2
  59. ultralytics/cfg/models/v8/yolov8-ghost.yaml +2 -2
  60. ultralytics/cfg/models/v8/yolov8-obb.yaml +1 -1
  61. ultralytics/cfg/models/v8/yolov8-p2.yaml +1 -1
  62. ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +1 -1
  63. ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +1 -1
  64. ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +1 -1
  65. ultralytics/cfg/models/v8/yolov8-world.yaml +1 -1
  66. ultralytics/cfg/models/v8/yolov8-worldv2.yaml +6 -6
  67. ultralytics/cfg/models/v9/yolov9s.yaml +1 -1
  68. ultralytics/cfg/trackers/botsort.yaml +16 -17
  69. ultralytics/cfg/trackers/bytetrack.yaml +9 -11
  70. ultralytics/data/__init__.py +4 -4
  71. ultralytics/data/annotator.py +3 -4
  72. ultralytics/data/augment.py +286 -476
  73. ultralytics/data/base.py +18 -26
  74. ultralytics/data/build.py +151 -26
  75. ultralytics/data/converter.py +38 -50
  76. ultralytics/data/dataset.py +47 -75
  77. ultralytics/data/loaders.py +42 -49
  78. ultralytics/data/split.py +5 -6
  79. ultralytics/data/split_dota.py +8 -15
  80. ultralytics/data/utils.py +41 -45
  81. ultralytics/engine/exporter.py +462 -462
  82. ultralytics/engine/model.py +150 -191
  83. ultralytics/engine/predictor.py +30 -40
  84. ultralytics/engine/results.py +177 -311
  85. ultralytics/engine/trainer.py +193 -120
  86. ultralytics/engine/tuner.py +77 -63
  87. ultralytics/engine/validator.py +39 -22
  88. ultralytics/hub/__init__.py +16 -19
  89. ultralytics/hub/auth.py +6 -12
  90. ultralytics/hub/google/__init__.py +7 -10
  91. ultralytics/hub/session.py +15 -25
  92. ultralytics/hub/utils.py +5 -8
  93. ultralytics/models/__init__.py +1 -1
  94. ultralytics/models/fastsam/__init__.py +1 -1
  95. ultralytics/models/fastsam/model.py +8 -10
  96. ultralytics/models/fastsam/predict.py +19 -30
  97. ultralytics/models/fastsam/utils.py +1 -2
  98. ultralytics/models/fastsam/val.py +5 -7
  99. ultralytics/models/nas/__init__.py +1 -1
  100. ultralytics/models/nas/model.py +5 -8
  101. ultralytics/models/nas/predict.py +7 -9
  102. ultralytics/models/nas/val.py +1 -2
  103. ultralytics/models/rtdetr/__init__.py +1 -1
  104. ultralytics/models/rtdetr/model.py +7 -8
  105. ultralytics/models/rtdetr/predict.py +15 -19
  106. ultralytics/models/rtdetr/train.py +10 -13
  107. ultralytics/models/rtdetr/val.py +21 -23
  108. ultralytics/models/sam/__init__.py +15 -2
  109. ultralytics/models/sam/amg.py +14 -20
  110. ultralytics/models/sam/build.py +26 -19
  111. ultralytics/models/sam/build_sam3.py +377 -0
  112. ultralytics/models/sam/model.py +29 -32
  113. ultralytics/models/sam/modules/blocks.py +83 -144
  114. ultralytics/models/sam/modules/decoders.py +22 -40
  115. ultralytics/models/sam/modules/encoders.py +44 -101
  116. ultralytics/models/sam/modules/memory_attention.py +16 -30
  117. ultralytics/models/sam/modules/sam.py +206 -79
  118. ultralytics/models/sam/modules/tiny_encoder.py +64 -83
  119. ultralytics/models/sam/modules/transformer.py +18 -28
  120. ultralytics/models/sam/modules/utils.py +174 -50
  121. ultralytics/models/sam/predict.py +2268 -366
  122. ultralytics/models/sam/sam3/__init__.py +3 -0
  123. ultralytics/models/sam/sam3/decoder.py +546 -0
  124. ultralytics/models/sam/sam3/encoder.py +529 -0
  125. ultralytics/models/sam/sam3/geometry_encoders.py +415 -0
  126. ultralytics/models/sam/sam3/maskformer_segmentation.py +286 -0
  127. ultralytics/models/sam/sam3/model_misc.py +199 -0
  128. ultralytics/models/sam/sam3/necks.py +129 -0
  129. ultralytics/models/sam/sam3/sam3_image.py +339 -0
  130. ultralytics/models/sam/sam3/text_encoder_ve.py +307 -0
  131. ultralytics/models/sam/sam3/vitdet.py +547 -0
  132. ultralytics/models/sam/sam3/vl_combiner.py +160 -0
  133. ultralytics/models/utils/loss.py +14 -26
  134. ultralytics/models/utils/ops.py +13 -17
  135. ultralytics/models/yolo/__init__.py +1 -1
  136. ultralytics/models/yolo/classify/predict.py +9 -12
  137. ultralytics/models/yolo/classify/train.py +15 -41
  138. ultralytics/models/yolo/classify/val.py +34 -32
  139. ultralytics/models/yolo/detect/predict.py +8 -11
  140. ultralytics/models/yolo/detect/train.py +13 -32
  141. ultralytics/models/yolo/detect/val.py +75 -63
  142. ultralytics/models/yolo/model.py +37 -53
  143. ultralytics/models/yolo/obb/predict.py +5 -14
  144. ultralytics/models/yolo/obb/train.py +11 -14
  145. ultralytics/models/yolo/obb/val.py +42 -39
  146. ultralytics/models/yolo/pose/__init__.py +1 -1
  147. ultralytics/models/yolo/pose/predict.py +7 -22
  148. ultralytics/models/yolo/pose/train.py +10 -22
  149. ultralytics/models/yolo/pose/val.py +40 -59
  150. ultralytics/models/yolo/segment/predict.py +16 -20
  151. ultralytics/models/yolo/segment/train.py +3 -12
  152. ultralytics/models/yolo/segment/val.py +106 -56
  153. ultralytics/models/yolo/world/train.py +12 -16
  154. ultralytics/models/yolo/world/train_world.py +11 -34
  155. ultralytics/models/yolo/yoloe/__init__.py +7 -7
  156. ultralytics/models/yolo/yoloe/predict.py +16 -23
  157. ultralytics/models/yolo/yoloe/train.py +31 -56
  158. ultralytics/models/yolo/yoloe/train_seg.py +5 -10
  159. ultralytics/models/yolo/yoloe/val.py +16 -21
  160. ultralytics/nn/__init__.py +7 -7
  161. ultralytics/nn/autobackend.py +152 -80
  162. ultralytics/nn/modules/__init__.py +60 -60
  163. ultralytics/nn/modules/activation.py +4 -6
  164. ultralytics/nn/modules/block.py +133 -217
  165. ultralytics/nn/modules/conv.py +52 -97
  166. ultralytics/nn/modules/head.py +64 -116
  167. ultralytics/nn/modules/transformer.py +79 -89
  168. ultralytics/nn/modules/utils.py +16 -21
  169. ultralytics/nn/tasks.py +111 -156
  170. ultralytics/nn/text_model.py +40 -67
  171. ultralytics/solutions/__init__.py +12 -12
  172. ultralytics/solutions/ai_gym.py +11 -17
  173. ultralytics/solutions/analytics.py +15 -16
  174. ultralytics/solutions/config.py +5 -6
  175. ultralytics/solutions/distance_calculation.py +10 -13
  176. ultralytics/solutions/heatmap.py +7 -13
  177. ultralytics/solutions/instance_segmentation.py +5 -8
  178. ultralytics/solutions/object_blurrer.py +7 -10
  179. ultralytics/solutions/object_counter.py +12 -19
  180. ultralytics/solutions/object_cropper.py +8 -14
  181. ultralytics/solutions/parking_management.py +33 -31
  182. ultralytics/solutions/queue_management.py +10 -12
  183. ultralytics/solutions/region_counter.py +9 -12
  184. ultralytics/solutions/security_alarm.py +15 -20
  185. ultralytics/solutions/similarity_search.py +13 -17
  186. ultralytics/solutions/solutions.py +75 -74
  187. ultralytics/solutions/speed_estimation.py +7 -10
  188. ultralytics/solutions/streamlit_inference.py +4 -7
  189. ultralytics/solutions/templates/similarity-search.html +7 -18
  190. ultralytics/solutions/trackzone.py +7 -10
  191. ultralytics/solutions/vision_eye.py +5 -8
  192. ultralytics/trackers/__init__.py +1 -1
  193. ultralytics/trackers/basetrack.py +3 -5
  194. ultralytics/trackers/bot_sort.py +10 -27
  195. ultralytics/trackers/byte_tracker.py +14 -30
  196. ultralytics/trackers/track.py +3 -6
  197. ultralytics/trackers/utils/gmc.py +11 -22
  198. ultralytics/trackers/utils/kalman_filter.py +37 -48
  199. ultralytics/trackers/utils/matching.py +12 -15
  200. ultralytics/utils/__init__.py +116 -116
  201. ultralytics/utils/autobatch.py +2 -4
  202. ultralytics/utils/autodevice.py +17 -18
  203. ultralytics/utils/benchmarks.py +70 -70
  204. ultralytics/utils/callbacks/base.py +8 -10
  205. ultralytics/utils/callbacks/clearml.py +5 -13
  206. ultralytics/utils/callbacks/comet.py +32 -46
  207. ultralytics/utils/callbacks/dvc.py +13 -18
  208. ultralytics/utils/callbacks/mlflow.py +4 -5
  209. ultralytics/utils/callbacks/neptune.py +7 -15
  210. ultralytics/utils/callbacks/platform.py +314 -38
  211. ultralytics/utils/callbacks/raytune.py +3 -4
  212. ultralytics/utils/callbacks/tensorboard.py +23 -31
  213. ultralytics/utils/callbacks/wb.py +10 -13
  214. ultralytics/utils/checks.py +151 -87
  215. ultralytics/utils/cpu.py +3 -8
  216. ultralytics/utils/dist.py +19 -15
  217. ultralytics/utils/downloads.py +29 -41
  218. ultralytics/utils/errors.py +6 -14
  219. ultralytics/utils/events.py +2 -4
  220. ultralytics/utils/export/__init__.py +7 -0
  221. ultralytics/utils/{export.py → export/engine.py} +16 -16
  222. ultralytics/utils/export/imx.py +325 -0
  223. ultralytics/utils/export/tensorflow.py +231 -0
  224. ultralytics/utils/files.py +24 -28
  225. ultralytics/utils/git.py +9 -11
  226. ultralytics/utils/instance.py +30 -51
  227. ultralytics/utils/logger.py +212 -114
  228. ultralytics/utils/loss.py +15 -24
  229. ultralytics/utils/metrics.py +131 -160
  230. ultralytics/utils/nms.py +21 -30
  231. ultralytics/utils/ops.py +107 -165
  232. ultralytics/utils/patches.py +33 -21
  233. ultralytics/utils/plotting.py +122 -119
  234. ultralytics/utils/tal.py +28 -44
  235. ultralytics/utils/torch_utils.py +70 -187
  236. ultralytics/utils/tqdm.py +20 -20
  237. ultralytics/utils/triton.py +13 -19
  238. ultralytics/utils/tuner.py +17 -5
  239. dgenerate_ultralytics_headless-8.3.196.dist-info/RECORD +0 -281
  240. {dgenerate_ultralytics_headless-8.3.196.dist-info → dgenerate_ultralytics_headless-8.3.248.dist-info}/WHEEL +0 -0
  241. {dgenerate_ultralytics_headless-8.3.196.dist-info → dgenerate_ultralytics_headless-8.3.248.dist-info}/entry_points.txt +0 -0
  242. {dgenerate_ultralytics_headless-8.3.196.dist-info → dgenerate_ultralytics_headless-8.3.248.dist-info}/licenses/LICENSE +0 -0
  243. {dgenerate_ultralytics_headless-8.3.196.dist-info → dgenerate_ultralytics_headless-8.3.248.dist-info}/top_level.txt +0 -0
@@ -27,12 +27,11 @@ from ultralytics.utils import (
27
27
 
28
28
 
29
29
  class Model(torch.nn.Module):
30
- """
31
- A base class for implementing YOLO models, unifying APIs across different model types.
30
+ """A base class for implementing YOLO models, unifying APIs across different model types.
32
31
 
33
- This class provides a common interface for various operations related to YOLO models, such as training,
34
- validation, prediction, exporting, and benchmarking. It handles different types of models, including those
35
- loaded from local files, Ultralytics HUB, or Triton Server.
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.
36
35
 
37
36
  Attributes:
38
37
  callbacks (dict): A dictionary of callback functions for various events during model operations.
@@ -82,33 +81,25 @@ class Model(torch.nn.Module):
82
81
  def __init__(
83
82
  self,
84
83
  model: str | Path | Model = "yolo11n.pt",
85
- task: str = None,
84
+ task: str | None = None,
86
85
  verbose: bool = False,
87
86
  ) -> None:
88
- """
89
- Initialize a new instance of the YOLO model class.
87
+ """Initialize a new instance of the YOLO model class.
90
88
 
91
- This constructor sets up the model based on the provided model path or name. It handles various types of
92
- model sources, including local files, Ultralytics HUB models, and Triton Server models. The method
93
- initializes several important attributes of the model and prepares it for operations like training,
94
- prediction, or export.
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.
95
92
 
96
93
  Args:
97
- model (str | Path | Model): Path or name of the model to load or create. Can be a local file path, a
98
- model name from Ultralytics HUB, a Triton Server model, or an already initialized Model instance.
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.
99
96
  task (str, optional): The specific task for the model. If None, it will be inferred from the config.
100
- verbose (bool): If True, enables verbose output during the model's initialization and subsequent
101
- operations.
97
+ verbose (bool): If True, enables verbose output during the model's initialization and subsequent operations.
102
98
 
103
99
  Raises:
104
100
  FileNotFoundError: If the specified model file does not exist or is inaccessible.
105
101
  ValueError: If the model file or configuration is invalid or unsupported.
106
102
  ImportError: If required dependencies for specific model types (like HUB SDK) are not installed.
107
-
108
- Examples:
109
- >>> model = Model("yolo11n.pt")
110
- >>> model = Model("path/to/model.yaml", task="detect")
111
- >>> model = Model("hub_model", verbose=True)
112
103
  """
113
104
  if isinstance(model, Model):
114
105
  self.__dict__ = model.__dict__ # accepts an already initialized Model
@@ -161,22 +152,21 @@ class Model(torch.nn.Module):
161
152
  stream: bool = False,
162
153
  **kwargs: Any,
163
154
  ) -> list:
164
- """
165
- Alias for the predict method, enabling the model instance to be callable for predictions.
155
+ """Alias for the predict method, enabling the model instance to be callable for predictions.
166
156
 
167
- This method simplifies the process of making predictions by allowing the model instance to be called
168
- directly with the required arguments.
157
+ This method simplifies the process of making predictions by allowing the model instance to be called directly
158
+ with the required arguments.
169
159
 
170
160
  Args:
171
- source (str | Path | int | PIL.Image | np.ndarray | torch.Tensor | list | tuple): The source of
172
- the image(s) to make predictions on. Can be a file path, URL, PIL image, numpy array, PyTorch
173
- tensor, or a list/tuple of these.
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.
174
164
  stream (bool): If True, treat the input source as a continuous stream for predictions.
175
165
  **kwargs (Any): Additional keyword arguments to configure the prediction process.
176
166
 
177
167
  Returns:
178
- (list[ultralytics.engine.results.Results]): A list of prediction results, each encapsulated in a
179
- Results object.
168
+ (list[ultralytics.engine.results.Results]): A list of prediction results, each encapsulated in a Results
169
+ object.
180
170
 
181
171
  Examples:
182
172
  >>> model = YOLO("yolo11n.pt")
@@ -188,11 +178,10 @@ class Model(torch.nn.Module):
188
178
 
189
179
  @staticmethod
190
180
  def is_triton_model(model: str) -> bool:
191
- """
192
- Check if the given model string is a Triton Server URL.
181
+ """Check if the given model string is a Triton Server URL.
193
182
 
194
- This static method determines whether the provided model string represents a valid Triton Server URL by
195
- parsing its components using urllib.parse.urlsplit().
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().
196
185
 
197
186
  Args:
198
187
  model (str): The model string to be checked.
@@ -213,8 +202,7 @@ class Model(torch.nn.Module):
213
202
 
214
203
  @staticmethod
215
204
  def is_hub_model(model: str) -> bool:
216
- """
217
- Check if the provided model is an Ultralytics HUB model.
205
+ """Check if the provided model is an Ultralytics HUB model.
218
206
 
219
207
  This static method determines whether the given model string represents a valid Ultralytics HUB model
220
208
  identifier.
@@ -236,17 +224,16 @@ class Model(torch.nn.Module):
236
224
  return model.startswith(f"{HUB_WEB_ROOT}/models/")
237
225
 
238
226
  def _new(self, cfg: str, task=None, model=None, verbose=False) -> None:
239
- """
240
- Initialize a new model and infer the task type from model definitions.
227
+ """Initialize a new model and infer the task type from model definitions.
241
228
 
242
- Creates a new model instance based on the provided configuration file. Loads the model configuration, infers
243
- the task type if not specified, and initializes the model using the appropriate class from the task map.
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.
244
231
 
245
232
  Args:
246
233
  cfg (str): Path to the model configuration file in YAML format.
247
234
  task (str, optional): The specific task for the model. If None, it will be inferred from the config.
248
- model (torch.nn.Module, optional): A custom model instance. If provided, it will be used instead of
249
- creating a new one.
235
+ model (torch.nn.Module, optional): A custom model instance. If provided, it will be used instead of creating
236
+ a new one.
250
237
  verbose (bool): If True, displays model information during loading.
251
238
 
252
239
  Raises:
@@ -270,11 +257,10 @@ class Model(torch.nn.Module):
270
257
  self.model_name = cfg
271
258
 
272
259
  def _load(self, weights: str, task=None) -> None:
273
- """
274
- Load a model from a checkpoint file or initialize it from a weights file.
260
+ """Load a model from a checkpoint file or initialize it from a weights file.
275
261
 
276
- This method handles loading models from either .pt checkpoint files or other weight file formats. It sets
277
- up the model, task, and related attributes based on the loaded weights.
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.
278
264
 
279
265
  Args:
280
266
  weights (str): Path to the model weights file to be loaded.
@@ -308,11 +294,10 @@ class Model(torch.nn.Module):
308
294
  self.model_name = weights
309
295
 
310
296
  def _check_is_pytorch_model(self) -> None:
311
- """
312
- Check if the model is a PyTorch model and raise TypeError if it's not.
297
+ """Check if the model is a PyTorch model and raise TypeError if it's not.
313
298
 
314
- This method verifies that the model is either a PyTorch module or a .pt file. It's used to ensure that
315
- certain operations that require a PyTorch model are only performed on compatible model types.
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.
316
301
 
317
302
  Raises:
318
303
  TypeError: If the model is not a PyTorch module or a .pt file. The error message provides detailed
@@ -336,12 +321,11 @@ class Model(torch.nn.Module):
336
321
  )
337
322
 
338
323
  def reset_weights(self) -> Model:
339
- """
340
- Reset the model's weights to their initial state.
324
+ """Reset the model's weights to their initial state.
341
325
 
342
326
  This method iterates through all modules in the model and resets their parameters if they have a
343
- 'reset_parameters' method. It also ensures that all parameters have 'requires_grad' set to True,
344
- enabling them to be updated during training.
327
+ 'reset_parameters' method. It also ensures that all parameters have 'requires_grad' set to True, enabling them
328
+ to be updated during training.
345
329
 
346
330
  Returns:
347
331
  (Model): The instance of the class with reset weights.
@@ -362,8 +346,7 @@ class Model(torch.nn.Module):
362
346
  return self
363
347
 
364
348
  def load(self, weights: str | Path = "yolo11n.pt") -> Model:
365
- """
366
- Load parameters from the specified weights file into the model.
349
+ """Load parameters from the specified weights file into the model.
367
350
 
368
351
  This method supports loading weights from a file or directly from a weights object. It matches parameters by
369
352
  name and shape and transfers them to the model.
@@ -390,11 +373,10 @@ class Model(torch.nn.Module):
390
373
  return self
391
374
 
392
375
  def save(self, filename: str | Path = "saved_model.pt") -> None:
393
- """
394
- Save the current model state to a file.
376
+ """Save the current model state to a file.
395
377
 
396
- This method exports the model's checkpoint (ckpt) to the specified filename. It includes metadata such as
397
- the date, Ultralytics version, license information, and a link to the documentation.
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.
398
380
 
399
381
  Args:
400
382
  filename (str | Path): The name of the file to save the model to.
@@ -422,8 +404,7 @@ class Model(torch.nn.Module):
422
404
  torch.save({**self.ckpt, **updates}, filename)
423
405
 
424
406
  def info(self, detailed: bool = False, verbose: bool = True):
425
- """
426
- Display model information.
407
+ """Display model information.
427
408
 
428
409
  This method provides an overview or detailed information about the model, depending on the arguments
429
410
  passed. It can control the verbosity of the output and return the information as a list.
@@ -433,8 +414,8 @@ class Model(torch.nn.Module):
433
414
  verbose (bool): If True, prints the information. If False, returns the information as a list.
434
415
 
435
416
  Returns:
436
- (list[str]): A list of strings containing various types of information about the model, including
437
- model summary, layer details, and parameter counts. Empty if verbose is True.
417
+ (list[str]): A list of strings containing various types of information about the model, including model
418
+ summary, layer details, and parameter counts. Empty if verbose is True.
438
419
 
439
420
  Examples:
440
421
  >>> model = Model("yolo11n.pt")
@@ -445,12 +426,11 @@ class Model(torch.nn.Module):
445
426
  return self.model.info(detailed=detailed, verbose=verbose)
446
427
 
447
428
  def fuse(self) -> None:
448
- """
449
- Fuse Conv2d and BatchNorm2d layers in the model for optimized inference.
429
+ """Fuse Conv2d and BatchNorm2d layers in the model for optimized inference.
450
430
 
451
- This method iterates through the model's modules and fuses consecutive Conv2d and BatchNorm2d layers
452
- into a single layer. This fusion can significantly improve inference speed by reducing the number of
453
- operations and memory accesses required during forward passes.
431
+ This method iterates through the model's modules and fuses consecutive Conv2d and BatchNorm2d layers into a
432
+ single layer. This fusion can significantly improve inference speed by reducing the number of operations and
433
+ memory accesses required during forward passes.
454
434
 
455
435
  The fusion process typically involves folding the BatchNorm2d parameters (mean, variance, weight, and
456
436
  bias) into the preceding Conv2d layer's weights and biases. This results in a single Conv2d layer that
@@ -470,15 +450,14 @@ class Model(torch.nn.Module):
470
450
  stream: bool = False,
471
451
  **kwargs: Any,
472
452
  ) -> list:
473
- """
474
- Generate image embeddings based on the provided source.
453
+ """Generate image embeddings based on the provided source.
475
454
 
476
455
  This method is a wrapper around the 'predict()' method, focusing on generating embeddings from an image
477
456
  source. It allows customization of the embedding process through various keyword arguments.
478
457
 
479
458
  Args:
480
- source (str | Path | int | list | tuple | np.ndarray | torch.Tensor): The source of the image for
481
- generating embeddings. Can be a file path, URL, PIL image, numpy array, etc.
459
+ source (str | Path | int | list | tuple | np.ndarray | torch.Tensor): The source of the image for generating
460
+ embeddings. Can be a file path, URL, PIL image, numpy array, etc.
482
461
  stream (bool): If True, predictions are streamed.
483
462
  **kwargs (Any): Additional keyword arguments for configuring the embedding process.
484
463
 
@@ -502,25 +481,24 @@ class Model(torch.nn.Module):
502
481
  predictor=None,
503
482
  **kwargs: Any,
504
483
  ) -> list[Results]:
505
- """
506
- Perform predictions on the given image source using the YOLO model.
484
+ """Perform predictions on the given image source using the YOLO model.
507
485
 
508
- This method facilitates the prediction process, allowing various configurations through keyword arguments.
509
- It supports predictions with custom predictors or the default predictor method. The method handles different
510
- types of image sources and can operate in a streaming mode.
486
+ This method facilitates the prediction process, allowing various configurations through keyword arguments. It
487
+ supports predictions with custom predictors or the default predictor method. The method handles different types
488
+ of image sources and can operate in a streaming mode.
511
489
 
512
490
  Args:
513
- source (str | Path | int | PIL.Image | np.ndarray | torch.Tensor | list | tuple): The source
514
- of the image(s) to make predictions on. Accepts various types including file paths, URLs, PIL
515
- images, numpy arrays, and torch tensors.
491
+ source (str | Path | int | PIL.Image | np.ndarray | torch.Tensor | list | tuple): The source of the image(s)
492
+ to make predictions on. Accepts various types including file paths, URLs, PIL images, numpy arrays, and
493
+ torch tensors.
516
494
  stream (bool): If True, treats the input source as a continuous stream for predictions.
517
- predictor (BasePredictor, optional): An instance of a custom predictor class for making predictions.
518
- If None, the method uses a default predictor.
495
+ predictor (BasePredictor, optional): An instance of a custom predictor class for making predictions. If
496
+ None, the method uses a default predictor.
519
497
  **kwargs (Any): Additional keyword arguments for configuring the prediction process.
520
498
 
521
499
  Returns:
522
- (list[ultralytics.engine.results.Results]): A list of prediction results, each encapsulated in a
523
- Results object.
500
+ (list[ultralytics.engine.results.Results]): A list of prediction results, each encapsulated in a Results
501
+ object.
524
502
 
525
503
  Examples:
526
504
  >>> model = YOLO("yolo11n.pt")
@@ -545,7 +523,7 @@ class Model(torch.nn.Module):
545
523
  args = {**self.overrides, **custom, **kwargs} # highest priority args on the right
546
524
  prompts = args.pop("prompts", None) # for SAM-type models
547
525
 
548
- if not self.predictor:
526
+ if not self.predictor or self.predictor.args.device != args.get("device", self.predictor.args.device):
549
527
  self.predictor = (predictor or self._smart_load("predictor"))(overrides=args, _callbacks=self.callbacks)
550
528
  self.predictor.setup_model(model=self.model, verbose=is_cli)
551
529
  else: # only update args if predictor is already setup
@@ -563,8 +541,7 @@ class Model(torch.nn.Module):
563
541
  persist: bool = False,
564
542
  **kwargs: Any,
565
543
  ) -> list[Results]:
566
- """
567
- Conduct object tracking on the specified input source using the registered trackers.
544
+ """Conduct object tracking on the specified input source using the registered trackers.
568
545
 
569
546
  This method performs object tracking using the model's predictors and optionally registered trackers. It handles
570
547
  various input sources such as file paths or video streams, and supports customization through keyword arguments.
@@ -605,8 +582,7 @@ class Model(torch.nn.Module):
605
582
  validator=None,
606
583
  **kwargs: Any,
607
584
  ):
608
- """
609
- Validate the model using a specified dataset and validation configuration.
585
+ """Validate the model using a specified dataset and validation configuration.
610
586
 
611
587
  This method facilitates the model validation process, allowing for customization through various settings. It
612
588
  supports validation with a custom validator or the default validation approach. The method combines default
@@ -637,13 +613,12 @@ class Model(torch.nn.Module):
637
613
  return validator.metrics
638
614
 
639
615
  def benchmark(self, data=None, format="", verbose=False, **kwargs: Any):
640
- """
641
- Benchmark the model across various export formats to evaluate performance.
616
+ """Benchmark the model across various export formats to evaluate performance.
642
617
 
643
- This method assesses the model's performance in different export formats, such as ONNX, TorchScript, etc.
644
- It uses the 'benchmark' function from the ultralytics.utils.benchmarks module. The benchmarking is
645
- configured using a combination of default configuration values, model-specific arguments, method-specific
646
- defaults, and any additional user-provided keyword arguments.
618
+ This method assesses the model's performance in different export formats, such as ONNX, TorchScript, etc. It
619
+ uses the 'benchmark' function from the ultralytics.utils.benchmarks module. The benchmarking is configured using
620
+ a combination of default configuration values, model-specific arguments, method-specific defaults, and any
621
+ additional user-provided keyword arguments.
647
622
 
648
623
  Args:
649
624
  data (str): Path to the dataset for benchmarking.
@@ -656,8 +631,8 @@ class Model(torch.nn.Module):
656
631
  - device (str): Device to run the benchmark on (e.g., 'cpu', 'cuda').
657
632
 
658
633
  Returns:
659
- (dict): A dictionary containing the results of the benchmarking process, including metrics for
660
- different export formats.
634
+ (dict): A dictionary containing the results of the benchmarking process, including metrics for different
635
+ export formats.
661
636
 
662
637
  Raises:
663
638
  AssertionError: If the model is not a PyTorch model.
@@ -691,23 +666,21 @@ class Model(torch.nn.Module):
691
666
  self,
692
667
  **kwargs: Any,
693
668
  ) -> str:
694
- """
695
- Export the model to a different format suitable for deployment.
669
+ """Export the model to a different format suitable for deployment.
696
670
 
697
671
  This method facilitates the export of the model to various formats (e.g., ONNX, TorchScript) for deployment
698
672
  purposes. It uses the 'Exporter' class for the export process, combining model-specific overrides, method
699
673
  defaults, and any additional arguments provided.
700
674
 
701
675
  Args:
702
- **kwargs (Any): Arbitrary keyword arguments to customize the export process. These are combined with
703
- the model's overrides and method defaults. Common arguments include:
704
- format (str): Export format (e.g., 'onnx', 'engine', 'coreml').
705
- half (bool): Export model in half-precision.
706
- int8 (bool): Export model in int8 precision.
707
- device (str): Device to run the export on.
708
- workspace (int): Maximum memory workspace size for TensorRT engines.
709
- nms (bool): Add Non-Maximum Suppression (NMS) module to model.
710
- simplify (bool): Simplify ONNX model.
676
+ **kwargs (Any): Arbitrary keyword arguments for export configuration. Common options include:
677
+ - format (str): Export format (e.g., 'onnx', 'engine', 'coreml').
678
+ - half (bool): Export model in half-precision.
679
+ - int8 (bool): Export model in int8 precision.
680
+ - device (str): Device to run the export on.
681
+ - workspace (int): Maximum memory workspace size for TensorRT engines.
682
+ - nms (bool): Add Non-Maximum Suppression (NMS) module to model.
683
+ - simplify (bool): Simplify ONNX model.
711
684
 
712
685
  Returns:
713
686
  (str): The path to the exported model file.
@@ -740,29 +713,29 @@ class Model(torch.nn.Module):
740
713
  trainer=None,
741
714
  **kwargs: Any,
742
715
  ):
743
- """
744
- Train the model using the specified dataset and training configuration.
716
+ """Train the model using the specified dataset and training configuration.
745
717
 
746
- This method facilitates model training with a range of customizable settings. It supports training with a
747
- custom trainer or the default training approach. The method handles scenarios such as resuming training
748
- from a checkpoint, integrating with Ultralytics HUB, and updating model and configuration after training.
718
+ This method facilitates model training with a range of customizable settings. It supports training with a custom
719
+ trainer or the default training approach. The method handles scenarios such as resuming training from a
720
+ checkpoint, integrating with Ultralytics HUB, and updating model and configuration after training.
749
721
 
750
- When using Ultralytics HUB, if the session has a loaded model, the method prioritizes HUB training
751
- arguments and warns if local arguments are provided. It checks for pip updates and combines default
752
- configurations, method-specific defaults, and user-provided arguments to configure the training process.
722
+ When using Ultralytics HUB, if the session has a loaded model, the method prioritizes HUB training arguments and
723
+ warns if local arguments are provided. It checks for pip updates and combines default configurations,
724
+ method-specific defaults, and user-provided arguments to configure the training process.
753
725
 
754
726
  Args:
755
727
  trainer (BaseTrainer, optional): Custom trainer instance for model training. If None, uses default.
756
728
  **kwargs (Any): Arbitrary keyword arguments for training configuration. Common options include:
757
- data (str): Path to dataset configuration file.
758
- epochs (int): Number of training epochs.
759
- batch (int): Batch size for training.
760
- imgsz (int): Input image size.
761
- device (str): Device to run training on (e.g., 'cuda', 'cpu').
762
- workers (int): Number of worker threads for data loading.
763
- optimizer (str): Optimizer to use for training.
764
- lr0 (float): Initial learning rate.
765
- patience (int): Epochs to wait for no observable improvement for early stopping of training.
729
+ - data (str): Path to dataset configuration file.
730
+ - epochs (int): Number of training epochs.
731
+ - batch (int): Batch size for training.
732
+ - imgsz (int): Input image size.
733
+ - device (str): Device to run training on (e.g., 'cuda', 'cpu').
734
+ - workers (int): Number of worker threads for data loading.
735
+ - optimizer (str): Optimizer to use for training.
736
+ - lr0 (float): Initial learning rate.
737
+ - patience (int): Epochs to wait for no observable improvement for early stopping of training.
738
+ - augmentations (list[Callable]): List of augmentation functions to apply during training.
766
739
 
767
740
  Returns:
768
741
  (dict | None): Training metrics if available and training is successful; otherwise, None.
@@ -788,7 +761,7 @@ class Model(torch.nn.Module):
788
761
  "model": self.overrides["model"],
789
762
  "task": self.task,
790
763
  } # method defaults
791
- args = {**overrides, **custom, **kwargs, "mode": "train"} # highest priority args on the right
764
+ args = {**overrides, **custom, **kwargs, "mode": "train", "session": self.session} # prioritizes rightmost args
792
765
  if args.get("resume"):
793
766
  args["resume"] = self.ckpt_path
794
767
 
@@ -797,13 +770,12 @@ class Model(torch.nn.Module):
797
770
  self.trainer.model = self.trainer.get_model(weights=self.model if self.ckpt else None, cfg=self.model.yaml)
798
771
  self.model = self.trainer.model
799
772
 
800
- self.trainer.hub_session = self.session # attach optional HUB session
801
773
  self.trainer.train()
802
774
  # Update model and cfg after training
803
775
  if RANK in {-1, 0}:
804
776
  ckpt = self.trainer.best if self.trainer.best.exists() else self.trainer.last
805
777
  self.model, self.ckpt = load_checkpoint(ckpt)
806
- self.overrides = self.model.args
778
+ self.overrides = self._reset_ckpt_args(self.model.args)
807
779
  self.metrics = getattr(self.trainer.validator, "metrics", None) # TODO: no metrics returned by DDP
808
780
  return self.metrics
809
781
 
@@ -814,13 +786,12 @@ class Model(torch.nn.Module):
814
786
  *args: Any,
815
787
  **kwargs: Any,
816
788
  ):
817
- """
818
- Conduct hyperparameter tuning for the model, with an option to use Ray Tune.
789
+ """Conduct hyperparameter tuning for the model, with an option to use Ray Tune.
819
790
 
820
- This method supports two modes of hyperparameter tuning: using Ray Tune or a custom tuning method.
821
- When Ray Tune is enabled, it leverages the 'run_ray_tune' function from the ultralytics.utils.tuner module.
822
- Otherwise, it uses the internal 'Tuner' class for tuning. The method combines default, overridden, and
823
- custom arguments to configure the tuning process.
791
+ This method supports two modes of hyperparameter tuning: using Ray Tune or a custom tuning method. When Ray Tune
792
+ is enabled, it leverages the 'run_ray_tune' function from the ultralytics.utils.tuner module. Otherwise, it uses
793
+ the internal 'Tuner' class for tuning. The method combines default, overridden, and custom arguments to
794
+ configure the tuning process.
824
795
 
825
796
  Args:
826
797
  use_ray (bool): Whether to use Ray Tune for hyperparameter tuning. If False, uses internal tuning method.
@@ -856,16 +827,15 @@ class Model(torch.nn.Module):
856
827
  return Tuner(args=args, _callbacks=self.callbacks)(model=self, iterations=iterations)
857
828
 
858
829
  def _apply(self, fn) -> Model:
859
- """
860
- Apply a function to model tensors that are not parameters or registered buffers.
830
+ """Apply a function to model tensors that are not parameters or registered buffers.
861
831
 
862
832
  This method extends the functionality of the parent class's _apply method by additionally resetting the
863
- predictor and updating the device in the model's overrides. It's typically used for operations like
864
- moving the model to a different device or changing its precision.
833
+ predictor and updating the device in the model's overrides. It's typically used for operations like moving the
834
+ model to a different device or changing its precision.
865
835
 
866
836
  Args:
867
- fn (Callable): A function to be applied to the model's tensors. This is typically a method like
868
- to(), cpu(), cuda(), half(), or float().
837
+ fn (Callable): A function to be applied to the model's tensors. This is typically a method like to(), cpu(),
838
+ cuda(), half(), or float().
869
839
 
870
840
  Returns:
871
841
  (Model): The model instance with the function applied and updated attributes.
@@ -878,15 +848,14 @@ class Model(torch.nn.Module):
878
848
  >>> model = model._apply(lambda t: t.cuda()) # Move model to GPU
879
849
  """
880
850
  self._check_is_pytorch_model()
881
- self = super()._apply(fn) # noqa
851
+ self = super()._apply(fn)
882
852
  self.predictor = None # reset predictor as device may have changed
883
853
  self.overrides["device"] = self.device # was str(self.device) i.e. device(type='cuda', index=0) -> 'cuda:0'
884
854
  return self
885
855
 
886
856
  @property
887
857
  def names(self) -> dict[int, str]:
888
- """
889
- Retrieve the class names associated with the loaded model.
858
+ """Retrieve the class names associated with the loaded model.
890
859
 
891
860
  This property returns the class names if they are defined in the model. It checks the class names for validity
892
861
  using the 'check_class_names' function from the ultralytics.nn.autobackend module. If the predictor is not
@@ -916,8 +885,7 @@ class Model(torch.nn.Module):
916
885
 
917
886
  @property
918
887
  def device(self) -> torch.device:
919
- """
920
- Get the device on which the model's parameters are allocated.
888
+ """Get the device on which the model's parameters are allocated.
921
889
 
922
890
  This property determines the device (CPU or GPU) where the model's parameters are currently stored. It is
923
891
  applicable only to models that are instances of torch.nn.Module.
@@ -940,12 +908,11 @@ class Model(torch.nn.Module):
940
908
 
941
909
  @property
942
910
  def transforms(self):
943
- """
944
- Retrieve the transformations applied to the input data of the loaded model.
911
+ """Retrieve the transformations applied to the input data of the loaded model.
945
912
 
946
- This property returns the transformations if they are defined in the model. The transforms
947
- typically include preprocessing steps like resizing, normalization, and data augmentation
948
- that are applied to input data before it is fed into the model.
913
+ This property returns the transformations if they are defined in the model. The transforms typically include
914
+ preprocessing steps like resizing, normalization, and data augmentation that are applied to input data before it
915
+ is fed into the model.
949
916
 
950
917
  Returns:
951
918
  (object | None): The transform object of the model if available, otherwise None.
@@ -961,18 +928,17 @@ class Model(torch.nn.Module):
961
928
  return self.model.transforms if hasattr(self.model, "transforms") else None
962
929
 
963
930
  def add_callback(self, event: str, func) -> None:
964
- """
965
- Add a callback function for a specified event.
931
+ """Add a callback function for a specified event.
966
932
 
967
- This method allows registering custom callback functions that are triggered on specific events during
968
- model operations such as training or inference. Callbacks provide a way to extend and customize the
969
- behavior of the model at various stages of its lifecycle.
933
+ This method allows registering custom callback functions that are triggered on specific events during model
934
+ operations such as training or inference. Callbacks provide a way to extend and customize the behavior of the
935
+ model at various stages of its lifecycle.
970
936
 
971
937
  Args:
972
- event (str): The name of the event to attach the callback to. Must be a valid event name recognized
973
- by the Ultralytics framework.
974
- func (Callable): The callback function to be registered. This function will be called when the
975
- specified event occurs.
938
+ event (str): The name of the event to attach the callback to. Must be a valid event name recognized by the
939
+ Ultralytics framework.
940
+ func (Callable): The callback function to be registered. This function will be called when the specified
941
+ event occurs.
976
942
 
977
943
  Raises:
978
944
  ValueError: If the event name is not recognized or is invalid.
@@ -987,12 +953,11 @@ class Model(torch.nn.Module):
987
953
  self.callbacks[event].append(func)
988
954
 
989
955
  def clear_callback(self, event: str) -> None:
990
- """
991
- Clear all callback functions registered for a specified event.
956
+ """Clear all callback functions registered for a specified event.
992
957
 
993
- This method removes all custom and default callback functions associated with the given event.
994
- It resets the callback list for the specified event to an empty list, effectively removing all
995
- registered callbacks for that event.
958
+ This method removes all custom and default callback functions associated with the given event. It resets the
959
+ callback list for the specified event to an empty list, effectively removing all registered callbacks for that
960
+ event.
996
961
 
997
962
  Args:
998
963
  event (str): The name of the event for which to clear the callbacks. This should be a valid event name
@@ -1015,8 +980,7 @@ class Model(torch.nn.Module):
1015
980
  self.callbacks[event] = []
1016
981
 
1017
982
  def reset_callbacks(self) -> None:
1018
- """
1019
- Reset all callbacks to their default functions.
983
+ """Reset all callbacks to their default functions.
1020
984
 
1021
985
  This method reinstates the default callback functions for all events, removing any custom callbacks that were
1022
986
  previously added. It iterates through all default callback events and replaces the current callbacks with the
@@ -1039,12 +1003,11 @@ class Model(torch.nn.Module):
1039
1003
 
1040
1004
  @staticmethod
1041
1005
  def _reset_ckpt_args(args: dict[str, Any]) -> dict[str, Any]:
1042
- """
1043
- Reset specific arguments when loading a PyTorch model checkpoint.
1006
+ """Reset specific arguments when loading a PyTorch model checkpoint.
1044
1007
 
1045
- This method filters the input arguments dictionary to retain only a specific set of keys that are
1046
- considered important for model loading. It's used to ensure that only relevant arguments are preserved
1047
- when loading a model from a checkpoint, discarding any unnecessary or potentially conflicting settings.
1008
+ This method filters the input arguments dictionary to retain only a specific set of keys that are considered
1009
+ important for model loading. It's used to ensure that only relevant arguments are preserved when loading a model
1010
+ from a checkpoint, discarding any unnecessary or potentially conflicting settings.
1048
1011
 
1049
1012
  Args:
1050
1013
  args (dict): A dictionary containing various model arguments and settings.
@@ -1067,12 +1030,11 @@ class Model(torch.nn.Module):
1067
1030
  # raise AttributeError(f"'{name}' object has no attribute '{attr}'. See valid attributes below.\n{self.__doc__}")
1068
1031
 
1069
1032
  def _smart_load(self, key: str):
1070
- """
1071
- Intelligently load the appropriate module based on the model task.
1033
+ """Intelligently load the appropriate module based on the model task.
1072
1034
 
1073
- This method dynamically selects and returns the correct module (model, trainer, validator, or predictor)
1074
- based on the current task of the model and the provided key. It uses the task_map dictionary to determine
1075
- the appropriate module to load for the specific task.
1035
+ This method dynamically selects and returns the correct module (model, trainer, validator, or predictor) based
1036
+ on the current task of the model and the provided key. It uses the task_map dictionary to determine the
1037
+ appropriate module to load for the specific task.
1076
1038
 
1077
1039
  Args:
1078
1040
  key (str): The type of module to load. Must be one of 'model', 'trainer', 'validator', or 'predictor'.
@@ -1097,21 +1059,20 @@ class Model(torch.nn.Module):
1097
1059
 
1098
1060
  @property
1099
1061
  def task_map(self) -> dict:
1100
- """
1101
- Provide a mapping from model tasks to corresponding classes for different modes.
1062
+ """Provide a mapping from model tasks to corresponding classes for different modes.
1102
1063
 
1103
- This property method returns a dictionary that maps each supported task (e.g., detect, segment, classify)
1104
- to a nested dictionary. The nested dictionary contains mappings for different operational modes
1105
- (model, trainer, validator, predictor) to their respective class implementations.
1064
+ This property method returns a dictionary that maps each supported task (e.g., detect, segment, classify) to a
1065
+ nested dictionary. The nested dictionary contains mappings for different operational modes (model, trainer,
1066
+ validator, predictor) to their respective class implementations.
1106
1067
 
1107
- The mapping allows for dynamic loading of appropriate classes based on the model's task and the
1108
- desired operational mode. This facilitates a flexible and extensible architecture for handling
1109
- various tasks and modes within the Ultralytics framework.
1068
+ The mapping allows for dynamic loading of appropriate classes based on the model's task and the desired
1069
+ operational mode. This facilitates a flexible and extensible architecture for handling various tasks and modes
1070
+ within the Ultralytics framework.
1110
1071
 
1111
1072
  Returns:
1112
1073
  (dict[str, dict[str, Any]]): A dictionary mapping task names to nested dictionaries. Each nested dictionary
1113
- contains mappings for 'model', 'trainer', 'validator', and 'predictor' keys to their respective class
1114
- implementations for that task.
1074
+ contains mappings for 'model', 'trainer', 'validator', and 'predictor' keys to their respective class
1075
+ implementations for that task.
1115
1076
 
1116
1077
  Examples:
1117
1078
  >>> model = Model("yolo11n.pt")
@@ -1122,8 +1083,7 @@ class Model(torch.nn.Module):
1122
1083
  raise NotImplementedError("Please provide task map for your model!")
1123
1084
 
1124
1085
  def eval(self):
1125
- """
1126
- Sets the model to evaluation mode.
1086
+ """Sets the model to evaluation mode.
1127
1087
 
1128
1088
  This method changes the model's mode to evaluation, which affects layers like dropout and batch normalization
1129
1089
  that behave differently during training and evaluation. In evaluation mode, these layers use running statistics
@@ -1141,8 +1101,7 @@ class Model(torch.nn.Module):
1141
1101
  return self
1142
1102
 
1143
1103
  def __getattr__(self, name):
1144
- """
1145
- Enable accessing model attributes directly through the Model class.
1104
+ """Enable accessing model attributes directly through the Model class.
1146
1105
 
1147
1106
  This method provides a way to access attributes of the underlying model directly through the Model class
1148
1107
  instance. It first checks if the requested attribute is 'model', in which case it returns the model from