ultralytics 8.1.6__py3-none-any.whl → 8.1.12__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.

Potentially problematic release.


This version of ultralytics might be problematic. Click here for more details.

Files changed (43) hide show
  1. ultralytics/__init__.py +1 -1
  2. ultralytics/cfg/__init__.py +1 -1
  3. ultralytics/data/converter.py +5 -2
  4. ultralytics/data/dataset.py +9 -4
  5. ultralytics/data/explorer/explorer.py +5 -2
  6. ultralytics/engine/exporter.py +17 -3
  7. ultralytics/engine/model.py +355 -81
  8. ultralytics/engine/results.py +94 -43
  9. ultralytics/engine/trainer.py +7 -3
  10. ultralytics/hub/__init__.py +6 -3
  11. ultralytics/hub/auth.py +2 -2
  12. ultralytics/hub/session.py +2 -2
  13. ultralytics/models/sam/amg.py +4 -2
  14. ultralytics/models/sam/modules/decoders.py +1 -1
  15. ultralytics/models/sam/modules/tiny_encoder.py +1 -1
  16. ultralytics/models/yolo/segment/predict.py +1 -1
  17. ultralytics/models/yolo/segment/val.py +6 -2
  18. ultralytics/nn/autobackend.py +6 -6
  19. ultralytics/nn/modules/head.py +11 -10
  20. ultralytics/nn/tasks.py +11 -2
  21. ultralytics/solutions/distance_calculation.py +5 -17
  22. ultralytics/solutions/heatmap.py +2 -1
  23. ultralytics/solutions/object_counter.py +1 -2
  24. ultralytics/solutions/speed_estimation.py +1 -1
  25. ultralytics/trackers/utils/gmc.py +10 -12
  26. ultralytics/utils/__init__.py +78 -7
  27. ultralytics/utils/benchmarks.py +1 -2
  28. ultralytics/utils/callbacks/mlflow.py +6 -2
  29. ultralytics/utils/checks.py +2 -2
  30. ultralytics/utils/loss.py +7 -2
  31. ultralytics/utils/metrics.py +4 -4
  32. ultralytics/utils/ops.py +0 -1
  33. ultralytics/utils/plotting.py +63 -5
  34. ultralytics/utils/tal.py +2 -2
  35. ultralytics/utils/torch_utils.py +2 -2
  36. ultralytics/utils/triton.py +1 -1
  37. ultralytics/utils/tuner.py +1 -1
  38. {ultralytics-8.1.6.dist-info → ultralytics-8.1.12.dist-info}/METADATA +4 -4
  39. {ultralytics-8.1.6.dist-info → ultralytics-8.1.12.dist-info}/RECORD +43 -43
  40. {ultralytics-8.1.6.dist-info → ultralytics-8.1.12.dist-info}/LICENSE +0 -0
  41. {ultralytics-8.1.6.dist-info → ultralytics-8.1.12.dist-info}/WHEEL +0 -0
  42. {ultralytics-8.1.6.dist-info → ultralytics-8.1.12.dist-info}/entry_points.txt +0 -0
  43. {ultralytics-8.1.6.dist-info → ultralytics-8.1.12.dist-info}/top_level.txt +0 -0
@@ -6,60 +6,98 @@ from pathlib import Path
6
6
  from typing import Union
7
7
 
8
8
  from ultralytics.cfg import TASK2DATA, get_cfg, get_save_dir
9
+ from ultralytics.hub.utils import HUB_WEB_ROOT
9
10
  from ultralytics.nn.tasks import attempt_load_one_weight, guess_model_task, nn, yaml_model_load
10
11
  from ultralytics.utils import ASSETS, DEFAULT_CFG_DICT, LOGGER, RANK, SETTINGS, callbacks, checks, emojis, yaml_load
11
- from ultralytics.hub.utils import HUB_WEB_ROOT
12
12
 
13
13
 
14
14
  class Model(nn.Module):
15
15
  """
16
- A base class to unify APIs for all models.
16
+ A base class for implementing YOLO models, unifying APIs across different model types.
17
+
18
+ This class provides a common interface for various operations related to YOLO models, such as training,
19
+ validation, prediction, exporting, and benchmarking. It handles different types of models, including those
20
+ loaded from local files, Ultralytics HUB, or Triton Server. The class is designed to be flexible and
21
+ extendable for different tasks and model configurations.
17
22
 
18
23
  Args:
19
- model (str, Path): Path to the model file to load or create.
20
- task (Any, optional): Task type for the YOLO model. Defaults to None.
24
+ model (Union[str, Path], optional): Path or name of the model to load or create. This can be a local file
25
+ path, a model name from Ultralytics HUB, or a Triton Server model. Defaults to 'yolov8n.pt'.
26
+ task (Any, optional): The task type associated with the YOLO model. This can be used to specify the model's
27
+ application domain, such as object detection, segmentation, etc. Defaults to None.
28
+ verbose (bool, optional): If True, enables verbose output during the model's operations. Defaults to False.
21
29
 
22
30
  Attributes:
23
- predictor (Any): The predictor object.
24
- model (Any): The model object.
25
- trainer (Any): The trainer object.
26
- task (str): The type of model task.
27
- ckpt (Any): The checkpoint object if the model loaded from *.pt file.
28
- cfg (str): The model configuration if loaded from *.yaml file.
29
- ckpt_path (str): The checkpoint file path.
30
- overrides (dict): Overrides for the trainer object.
31
- metrics (Any): The data for metrics.
31
+ callbacks (dict): A dictionary of callback functions for various events during model operations.
32
+ predictor (BasePredictor): The predictor object used for making predictions.
33
+ model (nn.Module): The underlying PyTorch model.
34
+ trainer (BaseTrainer): The trainer object used for training the model.
35
+ ckpt (dict): The checkpoint data if the model is loaded from a *.pt file.
36
+ cfg (str): The configuration of the model if loaded from a *.yaml file.
37
+ ckpt_path (str): The path to the checkpoint file.
38
+ overrides (dict): A dictionary of overrides for model configuration.
39
+ metrics (dict): The latest training/validation metrics.
40
+ session (HUBTrainingSession): The Ultralytics HUB session, if applicable.
41
+ task (str): The type of task the model is intended for.
42
+ model_name (str): The name of the model.
32
43
 
33
44
  Methods:
34
- __call__(source=None, stream=False, **kwargs):
35
- Alias for the predict method.
36
- _new(cfg:str, verbose:bool=True) -> None:
37
- Initializes a new model and infers the task type from the model definitions.
38
- _load(weights:str, task:str='') -> None:
39
- Initializes a new model and infers the task type from the model head.
40
- _check_is_pytorch_model() -> None:
41
- Raises TypeError if the model is not a PyTorch model.
42
- reset() -> None:
43
- Resets the model modules.
44
- info(verbose:bool=False) -> None:
45
- Logs the model info.
46
- fuse() -> None:
47
- Fuses the model for faster inference.
48
- predict(source=None, stream=False, **kwargs) -> List[ultralytics.engine.results.Results]:
49
- Performs prediction using the YOLO model.
50
-
51
- Returns:
52
- list(ultralytics.engine.results.Results): The prediction results.
45
+ __call__: Alias for the predict method, enabling the model instance to be callable.
46
+ _new: Initializes a new model based on a configuration file.
47
+ _load: Loads a model from a checkpoint file.
48
+ _check_is_pytorch_model: Ensures that the model is a PyTorch model.
49
+ reset_weights: Resets the model's weights to their initial state.
50
+ load: Loads model weights from a specified file.
51
+ save: Saves the current state of the model to a file.
52
+ info: Logs or returns information about the model.
53
+ fuse: Fuses Conv2d and BatchNorm2d layers for optimized inference.
54
+ predict: Performs object detection predictions.
55
+ track: Performs object tracking.
56
+ val: Validates the model on a dataset.
57
+ benchmark: Benchmarks the model on various export formats.
58
+ export: Exports the model to different formats.
59
+ train: Trains the model on a dataset.
60
+ tune: Performs hyperparameter tuning.
61
+ _apply: Applies a function to the model's tensors.
62
+ add_callback: Adds a callback function for an event.
63
+ clear_callback: Clears all callbacks for an event.
64
+ reset_callbacks: Resets all callbacks to their default functions.
65
+ _get_hub_session: Retrieves or creates an Ultralytics HUB session.
66
+ is_triton_model: Checks if a model is a Triton Server model.
67
+ is_hub_model: Checks if a model is an Ultralytics HUB model.
68
+ _reset_ckpt_args: Resets checkpoint arguments when loading a PyTorch model.
69
+ _smart_load: Loads the appropriate module based on the model task.
70
+ task_map: Provides a mapping from model tasks to corresponding classes.
71
+
72
+ Raises:
73
+ FileNotFoundError: If the specified model file does not exist or is inaccessible.
74
+ ValueError: If the model file or configuration is invalid or unsupported.
75
+ ImportError: If required dependencies for specific model types (like HUB SDK) are not installed.
76
+ TypeError: If the model is not a PyTorch model when required.
77
+ AttributeError: If required attributes or methods are not implemented or available.
78
+ NotImplementedError: If a specific model task or mode is not supported.
53
79
  """
54
80
 
55
81
  def __init__(self, model: Union[str, Path] = "yolov8n.pt", task=None, verbose=False) -> None:
56
82
  """
57
- Initializes the YOLO model.
83
+ Initializes a new instance of the YOLO model class.
84
+
85
+ This constructor sets up the model based on the provided model path or name. It handles various types of model
86
+ sources, including local files, Ultralytics HUB models, and Triton Server models. The method initializes several
87
+ important attributes of the model and prepares it for operations like training, prediction, or export.
58
88
 
59
89
  Args:
60
- model (Union[str, Path], optional): Path or name of the model to load or create. Defaults to 'yolov8n.pt'.
61
- task (Any, optional): Task type for the YOLO model. Defaults to None.
62
- verbose (bool, optional): Whether to enable verbose mode.
90
+ model (Union[str, Path], optional): The path or model file to load or create. This can be a local
91
+ file path, a model name from Ultralytics HUB, or a Triton Server model. Defaults to 'yolov8n.pt'.
92
+ task (Any, optional): The task type associated with the YOLO model, specifying its application domain.
93
+ Defaults to None.
94
+ verbose (bool, optional): If True, enables verbose output during the model's initialization and subsequent
95
+ operations. Defaults to False.
96
+
97
+ Raises:
98
+ FileNotFoundError: If the specified model file does not exist or is inaccessible.
99
+ ValueError: If the model file or configuration is invalid or unsupported.
100
+ ImportError: If required dependencies for specific model types (like HUB SDK) are not installed.
63
101
  """
64
102
  super().__init__()
65
103
  self.callbacks = callbacks.get_default_callbacks()
@@ -98,7 +136,22 @@ class Model(nn.Module):
98
136
  self.model_name = model
99
137
 
100
138
  def __call__(self, source=None, stream=False, **kwargs):
101
- """Calls the predict() method with given arguments to perform object detection."""
139
+ """
140
+ An alias for the predict method, enabling the model instance to be callable.
141
+
142
+ This method simplifies the process of making predictions by allowing the model instance to be called directly
143
+ with the required arguments for prediction.
144
+
145
+ Args:
146
+ source (str | int | PIL.Image | np.ndarray, optional): The source of the image for making predictions.
147
+ Accepts various types, including file paths, URLs, PIL images, and numpy arrays. Defaults to None.
148
+ stream (bool, optional): If True, treats the input source as a continuous stream for predictions.
149
+ Defaults to False.
150
+ **kwargs (dict): Additional keyword arguments for configuring the prediction process.
151
+
152
+ Returns:
153
+ (List[ultralytics.engine.results.Results]): A list of prediction results, encapsulated in the Results class.
154
+ """
102
155
  return self.predict(source, stream, **kwargs)
103
156
 
104
157
  @staticmethod
@@ -185,7 +238,19 @@ class Model(nn.Module):
185
238
  )
186
239
 
187
240
  def reset_weights(self):
188
- """Resets the model modules parameters to randomly initialized values, losing all training information."""
241
+ """
242
+ Resets the model parameters to randomly initialized values, effectively discarding all training information.
243
+
244
+ This method iterates through all modules in the model and resets their parameters if they have a
245
+ 'reset_parameters' method. It also ensures that all parameters have 'requires_grad' set to True, enabling them
246
+ to be updated during training.
247
+
248
+ Returns:
249
+ self (ultralytics.engine.model.Model): The instance of the class with reset weights.
250
+
251
+ Raises:
252
+ AssertionError: If the model is not a PyTorch model.
253
+ """
189
254
  self._check_is_pytorch_model()
190
255
  for m in self.model.modules():
191
256
  if hasattr(m, "reset_parameters"):
@@ -195,42 +260,94 @@ class Model(nn.Module):
195
260
  return self
196
261
 
197
262
  def load(self, weights="yolov8n.pt"):
198
- """Transfers parameters with matching names and shapes from 'weights' to model."""
263
+ """
264
+ Loads parameters from the specified weights file into the model.
265
+
266
+ This method supports loading weights from a file or directly from a weights object. It matches parameters by
267
+ name and shape and transfers them to the model.
268
+
269
+ Args:
270
+ weights (str | Path): Path to the weights file or a weights object. Defaults to 'yolov8n.pt'.
271
+
272
+ Returns:
273
+ self (ultralytics.engine.model.Model): The instance of the class with loaded weights.
274
+
275
+ Raises:
276
+ AssertionError: If the model is not a PyTorch model.
277
+ """
199
278
  self._check_is_pytorch_model()
200
279
  if isinstance(weights, (str, Path)):
201
280
  weights, self.ckpt = attempt_load_one_weight(weights)
202
281
  self.model.load(weights)
203
282
  return self
204
283
 
284
+ def save(self, filename="model.pt"):
285
+ """
286
+ Saves the current model state to a file.
287
+
288
+ This method exports the model's checkpoint (ckpt) to the specified filename.
289
+
290
+ Args:
291
+ filename (str): The name of the file to save the model to. Defaults to 'model.pt'.
292
+
293
+ Raises:
294
+ AssertionError: If the model is not a PyTorch model.
295
+ """
296
+ self._check_is_pytorch_model()
297
+ import torch
298
+
299
+ torch.save(self.ckpt, filename)
300
+
205
301
  def info(self, detailed=False, verbose=True):
206
302
  """
207
- Logs model info.
303
+ Logs or returns model information.
304
+
305
+ This method provides an overview or detailed information about the model, depending on the arguments passed.
306
+ It can control the verbosity of the output.
208
307
 
209
308
  Args:
210
- detailed (bool): Show detailed information about model.
211
- verbose (bool): Controls verbosity.
309
+ detailed (bool): If True, shows detailed information about the model. Defaults to False.
310
+ verbose (bool): If True, prints the information. If False, returns the information. Defaults to True.
311
+
312
+ Returns:
313
+ (list): Various types of information about the model, depending on the 'detailed' and 'verbose' parameters.
314
+
315
+ Raises:
316
+ AssertionError: If the model is not a PyTorch model.
212
317
  """
213
318
  self._check_is_pytorch_model()
214
319
  return self.model.info(detailed=detailed, verbose=verbose)
215
320
 
216
321
  def fuse(self):
217
- """Fuse PyTorch Conv2d and BatchNorm2d layers."""
322
+ """
323
+ Fuses Conv2d and BatchNorm2d layers in the model.
324
+
325
+ This method optimizes the model by fusing Conv2d and BatchNorm2d layers, which can improve inference speed.
326
+
327
+ Raises:
328
+ AssertionError: If the model is not a PyTorch model.
329
+ """
218
330
  self._check_is_pytorch_model()
219
331
  self.model.fuse()
220
332
 
221
333
  def embed(self, source=None, stream=False, **kwargs):
222
334
  """
223
- Calls the predict() method and returns image embeddings.
335
+ Generates image embeddings based on the provided source.
336
+
337
+ This method is a wrapper around the 'predict()' method, focusing on generating embeddings from an image source.
338
+ It allows customization of the embedding process through various keyword arguments.
224
339
 
225
340
  Args:
226
- source (str | int | PIL | np.ndarray): The source of the image to make predictions on.
227
- Accepts all source types accepted by the YOLO model.
228
- stream (bool): Whether to stream the predictions or not. Defaults to False.
229
- **kwargs : Additional keyword arguments passed to the predictor.
230
- Check the 'configuration' section in the documentation for all available options.
341
+ source (str | int | PIL.Image | np.ndarray): The source of the image for generating embeddings.
342
+ The source can be a file path, URL, PIL image, numpy array, etc. Defaults to None.
343
+ stream (bool): If True, predictions are streamed. Defaults to False.
344
+ **kwargs (dict): Additional keyword arguments for configuring the embedding process.
231
345
 
232
346
  Returns:
233
- (List[torch.Tensor]): A list of image embeddings.
347
+ (List[torch.Tensor]): A list containing the image embeddings.
348
+
349
+ Raises:
350
+ AssertionError: If the model is not a PyTorch model.
234
351
  """
235
352
  if not kwargs.get("embed"):
236
353
  kwargs["embed"] = [len(self.model.model) - 2] # embed second-to-last layer if no indices passed
@@ -238,18 +355,32 @@ class Model(nn.Module):
238
355
 
239
356
  def predict(self, source=None, stream=False, predictor=None, **kwargs):
240
357
  """
241
- Perform prediction using the YOLO model.
358
+ Performs predictions on the given image source using the YOLO model.
359
+
360
+ This method facilitates the prediction process, allowing various configurations through keyword arguments.
361
+ It supports predictions with custom predictors or the default predictor method. The method handles different
362
+ types of image sources and can operate in a streaming mode. It also provides support for SAM-type models
363
+ through 'prompts'.
364
+
365
+ The method sets up a new predictor if not already present and updates its arguments with each call.
366
+ It also issues a warning and uses default assets if the 'source' is not provided. The method determines if it
367
+ is being called from the command line interface and adjusts its behavior accordingly, including setting defaults
368
+ for confidence threshold and saving behavior.
242
369
 
243
370
  Args:
244
- source (str | int | PIL | np.ndarray): The source of the image to make predictions on.
245
- Accepts all source types accepted by the YOLO model.
246
- stream (bool): Whether to stream the predictions or not. Defaults to False.
247
- predictor (BasePredictor): Customized predictor.
248
- **kwargs : Additional keyword arguments passed to the predictor.
249
- Check the 'configuration' section in the documentation for all available options.
371
+ source (str | int | PIL.Image | np.ndarray, optional): The source of the image for making predictions.
372
+ Accepts various types, including file paths, URLs, PIL images, and numpy arrays. Defaults to ASSETS.
373
+ stream (bool, optional): Treats the input source as a continuous stream for predictions. Defaults to False.
374
+ predictor (BasePredictor, optional): An instance of a custom predictor class for making predictions.
375
+ If None, the method uses a default predictor. Defaults to None.
376
+ **kwargs (dict): Additional keyword arguments for configuring the prediction process. These arguments allow
377
+ for further customization of the prediction behavior.
250
378
 
251
379
  Returns:
252
- (List[ultralytics.engine.results.Results]): The prediction results.
380
+ (List[ultralytics.engine.results.Results]): A list of prediction results, encapsulated in the Results class.
381
+
382
+ Raises:
383
+ AttributeError: If the predictor is not properly set up.
253
384
  """
254
385
  if source is None:
255
386
  source = ASSETS
@@ -276,16 +407,28 @@ class Model(nn.Module):
276
407
 
277
408
  def track(self, source=None, stream=False, persist=False, **kwargs):
278
409
  """
279
- Perform object tracking on the input source using the registered trackers.
410
+ Conducts object tracking on the specified input source using the registered trackers.
411
+
412
+ This method performs object tracking using the model's predictors and optionally registered trackers. It is
413
+ capable of handling different types of input sources such as file paths or video streams. The method supports
414
+ customization of the tracking process through various keyword arguments. It registers trackers if they are not
415
+ already present and optionally persists them based on the 'persist' flag.
416
+
417
+ The method sets a default confidence threshold specifically for ByteTrack-based tracking, which requires low
418
+ confidence predictions as input. The tracking mode is explicitly set in the keyword arguments.
280
419
 
281
420
  Args:
282
- source (str, optional): The input source for object tracking. Can be a file path or a video stream.
283
- stream (bool, optional): Whether the input source is a video stream. Defaults to False.
284
- persist (bool, optional): Whether to persist the trackers if they already exist. Defaults to False.
285
- **kwargs (optional): Additional keyword arguments for the tracking process.
421
+ source (str, optional): The input source for object tracking. It can be a file path, URL, or video stream.
422
+ stream (bool, optional): Treats the input source as a continuous video stream. Defaults to False.
423
+ persist (bool, optional): Persists the trackers between different calls to this method. Defaults to False.
424
+ **kwargs (dict): Additional keyword arguments for configuring the tracking process. These arguments allow
425
+ for further customization of the tracking behavior.
286
426
 
287
427
  Returns:
288
- (List[ultralytics.engine.results.Results]): The tracking results.
428
+ (List[ultralytics.engine.results.Results]): A list of tracking results, encapsulated in the Results class.
429
+
430
+ Raises:
431
+ AttributeError: If the predictor does not have registered trackers.
289
432
  """
290
433
  if not hasattr(self.predictor, "trackers"):
291
434
  from ultralytics.trackers import register_tracker
@@ -297,11 +440,28 @@ class Model(nn.Module):
297
440
 
298
441
  def val(self, validator=None, **kwargs):
299
442
  """
300
- Validate a model on a given dataset.
443
+ Validates the model using a specified dataset and validation configuration.
444
+
445
+ This method facilitates the model validation process, allowing for a range of customization through various
446
+ settings and configurations. It supports validation with a custom validator or the default validation approach.
447
+ The method combines default configurations, method-specific defaults, and user-provided arguments to configure
448
+ the validation process. After validation, it updates the model's metrics with the results obtained from the
449
+ validator.
450
+
451
+ The method supports various arguments that allow customization of the validation process. For a comprehensive
452
+ list of all configurable options, users should refer to the 'configuration' section in the documentation.
301
453
 
302
454
  Args:
303
- validator (BaseValidator): Customized validator.
304
- **kwargs : Any other args accepted by the validators. To see all args check 'configuration' section in docs
455
+ validator (BaseValidator, optional): An instance of a custom validator class for validating the model. If
456
+ None, the method uses a default validator. Defaults to None.
457
+ **kwargs (dict): Arbitrary keyword arguments representing the validation configuration. These arguments are
458
+ used to customize various aspects of the validation process.
459
+
460
+ Returns:
461
+ (dict): Validation metrics obtained from the validation process.
462
+
463
+ Raises:
464
+ AssertionError: If the model is not a PyTorch model.
305
465
  """
306
466
  custom = {"rect": True} # method defaults
307
467
  args = {**self.overrides, **custom, **kwargs, "mode": "val"} # highest priority args on the right
@@ -313,10 +473,26 @@ class Model(nn.Module):
313
473
 
314
474
  def benchmark(self, **kwargs):
315
475
  """
316
- Benchmark a model on all export formats.
476
+ Benchmarks the model across various export formats to evaluate performance.
477
+
478
+ This method assesses the model's performance in different export formats, such as ONNX, TorchScript, etc.
479
+ It uses the 'benchmark' function from the ultralytics.utils.benchmarks module. The benchmarking is configured
480
+ using a combination of default configuration values, model-specific arguments, method-specific defaults, and
481
+ any additional user-provided keyword arguments.
482
+
483
+ The method supports various arguments that allow customization of the benchmarking process, such as dataset
484
+ choice, image size, precision modes, device selection, and verbosity. For a comprehensive list of all
485
+ configurable options, users should refer to the 'configuration' section in the documentation.
317
486
 
318
487
  Args:
319
- **kwargs : Any other args accepted by the validators. To see all args check 'configuration' section in docs
488
+ **kwargs (dict): Arbitrary keyword arguments to customize the benchmarking process. These are combined with
489
+ default configurations, model-specific arguments, and method defaults.
490
+
491
+ Returns:
492
+ (dict): A dictionary containing the results of the benchmarking process.
493
+
494
+ Raises:
495
+ AssertionError: If the model is not a PyTorch model.
320
496
  """
321
497
  self._check_is_pytorch_model()
322
498
  from ultralytics.utils.benchmarks import benchmark
@@ -335,10 +511,24 @@ class Model(nn.Module):
335
511
 
336
512
  def export(self, **kwargs):
337
513
  """
338
- Export model.
514
+ Exports the model to a different format suitable for deployment.
515
+
516
+ This method facilitates the export of the model to various formats (e.g., ONNX, TorchScript) for deployment
517
+ purposes. It uses the 'Exporter' class for the export process, combining model-specific overrides, method
518
+ defaults, and any additional arguments provided. The combined arguments are used to configure export settings.
519
+
520
+ The method supports a wide range of arguments to customize the export process. For a comprehensive list of all
521
+ possible arguments, refer to the 'configuration' section in the documentation.
339
522
 
340
523
  Args:
341
- **kwargs : Any other args accepted by the Exporter. To see all args check 'configuration' section in docs.
524
+ **kwargs (dict): Arbitrary keyword arguments to customize the export process. These are combined with the
525
+ model's overrides and method defaults.
526
+
527
+ Returns:
528
+ (object): The exported model in the specified format, or an object related to the export process.
529
+
530
+ Raises:
531
+ AssertionError: If the model is not a PyTorch model.
342
532
  """
343
533
  self._check_is_pytorch_model()
344
534
  from .exporter import Exporter
@@ -349,11 +539,31 @@ class Model(nn.Module):
349
539
 
350
540
  def train(self, trainer=None, **kwargs):
351
541
  """
352
- Trains the model on a given dataset.
542
+ Trains the model using the specified dataset and training configuration.
543
+
544
+ This method facilitates model training with a range of customizable settings and configurations. It supports
545
+ training with a custom trainer or the default training approach defined in the method. The method handles
546
+ different scenarios, such as resuming training from a checkpoint, integrating with Ultralytics HUB, and
547
+ updating model and configuration after training.
548
+
549
+ When using Ultralytics HUB, if the session already has a loaded model, the method prioritizes HUB training
550
+ arguments and issues a warning if local arguments are provided. It checks for pip updates and combines default
551
+ configurations, method-specific defaults, and user-provided arguments to configure the training process. After
552
+ training, it updates the model and its configurations, and optionally attaches metrics.
353
553
 
354
554
  Args:
355
- trainer (BaseTrainer, optional): Customized trainer.
356
- **kwargs (Any): Any number of arguments representing the training configuration.
555
+ trainer (BaseTrainer, optional): An instance of a custom trainer class for training the model. If None, the
556
+ method uses a default trainer. Defaults to None.
557
+ **kwargs (dict): Arbitrary keyword arguments representing the training configuration. These arguments are
558
+ used to customize various aspects of the training process.
559
+
560
+ Returns:
561
+ (dict | None): Training metrics if available and training is successful; otherwise, None.
562
+
563
+ Raises:
564
+ AssertionError: If the model is not a PyTorch model.
565
+ PermissionError: If there is a permission issue with the HUB session.
566
+ ModuleNotFoundError: If the HUB SDK is not installed.
357
567
  """
358
568
  self._check_is_pytorch_model()
359
569
  if hasattr(self.session, "model") and self.session.model.id: # Ultralytics HUB session with loaded model
@@ -399,10 +609,24 @@ class Model(nn.Module):
399
609
 
400
610
  def tune(self, use_ray=False, iterations=10, *args, **kwargs):
401
611
  """
402
- Runs hyperparameter tuning, optionally using Ray Tune. See ultralytics.utils.tuner.run_ray_tune for Args.
612
+ Conducts hyperparameter tuning for the model, with an option to use Ray Tune.
613
+
614
+ This method supports two modes of hyperparameter tuning: using Ray Tune or a custom tuning method.
615
+ When Ray Tune is enabled, it leverages the 'run_ray_tune' function from the ultralytics.utils.tuner module.
616
+ Otherwise, it uses the internal 'Tuner' class for tuning. The method combines default, overridden, and
617
+ custom arguments to configure the tuning process.
618
+
619
+ Args:
620
+ use_ray (bool): If True, uses Ray Tune for hyperparameter tuning. Defaults to False.
621
+ iterations (int): The number of tuning iterations to perform. Defaults to 10.
622
+ *args (list): Variable length argument list for additional arguments.
623
+ **kwargs (dict): Arbitrary keyword arguments. These are combined with the model's overrides and defaults.
403
624
 
404
625
  Returns:
405
626
  (dict): A dictionary containing the results of the hyperparameter search.
627
+
628
+ Raises:
629
+ AssertionError: If the model is not a PyTorch model.
406
630
  """
407
631
  self._check_is_pytorch_model()
408
632
  if use_ray:
@@ -426,31 +650,81 @@ class Model(nn.Module):
426
650
 
427
651
  @property
428
652
  def names(self):
429
- """Returns class names of the loaded model."""
653
+ """
654
+ Retrieves the class names associated with the loaded model.
655
+
656
+ This property returns the class names if they are defined in the model. It checks the class names for validity
657
+ using the 'check_class_names' function from the ultralytics.nn.autobackend module.
658
+
659
+ Returns:
660
+ (list | None): The class names of the model if available, otherwise None.
661
+ """
430
662
  from ultralytics.nn.autobackend import check_class_names
431
663
 
432
664
  return check_class_names(self.model.names) if hasattr(self.model, "names") else None
433
665
 
434
666
  @property
435
667
  def device(self):
436
- """Returns device if PyTorch model."""
668
+ """
669
+ Retrieves the device on which the model's parameters are allocated.
670
+
671
+ This property is used to determine whether the model's parameters are on CPU or GPU. It only applies to models
672
+ that are instances of nn.Module.
673
+
674
+ Returns:
675
+ (torch.device | None): The device (CPU/GPU) of the model if it is a PyTorch model, otherwise None.
676
+ """
437
677
  return next(self.model.parameters()).device if isinstance(self.model, nn.Module) else None
438
678
 
439
679
  @property
440
680
  def transforms(self):
441
- """Returns transform of the loaded model."""
681
+ """
682
+ Retrieves the transformations applied to the input data of the loaded model.
683
+
684
+ This property returns the transformations if they are defined in the model.
685
+
686
+ Returns:
687
+ (object | None): The transform object of the model if available, otherwise None.
688
+ """
442
689
  return self.model.transforms if hasattr(self.model, "transforms") else None
443
690
 
444
691
  def add_callback(self, event: str, func):
445
- """Add a callback."""
692
+ """
693
+ Adds a callback function for a specified event.
694
+
695
+ This method allows the user to register a custom callback function that is triggered on a specific event during
696
+ model training or inference.
697
+
698
+ Args:
699
+ event (str): The name of the event to attach the callback to.
700
+ func (callable): The callback function to be registered.
701
+
702
+ Raises:
703
+ ValueError: If the event name is not recognized.
704
+ """
446
705
  self.callbacks[event].append(func)
447
706
 
448
707
  def clear_callback(self, event: str):
449
- """Clear all event callbacks."""
708
+ """
709
+ Clears all callback functions registered for a specified event.
710
+
711
+ This method removes all custom and default callback functions associated with the given event.
712
+
713
+ Args:
714
+ event (str): The name of the event for which to clear the callbacks.
715
+
716
+ Raises:
717
+ ValueError: If the event name is not recognized.
718
+ """
450
719
  self.callbacks[event] = []
451
720
 
452
721
  def reset_callbacks(self):
453
- """Reset all registered callbacks."""
722
+ """
723
+ Resets all callbacks to their default functions.
724
+
725
+ This method reinstates the default callback functions for all events, removing any custom callbacks that were
726
+ added previously.
727
+ """
454
728
  for event in callbacks.default_callbacks.keys():
455
729
  self.callbacks[event] = [callbacks.default_callbacks[event][0]]
456
730