Reference for ultralytics/engine/model.py
Note
This file is available at https://github.com/ultralytics/ultralytics/blob/main/ultralytics/engine/model.py. If you spot a problem please help fix it by contributing a Pull Request 🛠️. Thank you 🙏!
ultralytics.engine.model.Model
Bases: Module
A base class for implementing YOLO models, unifying APIs across different model types.
This class provides a common interface for various operations related to YOLO models, such as training, validation, prediction, exporting, and benchmarking. It handles different types of models, including those loaded from local files, Ultralytics HUB, or Triton Server. The class is designed to be flexible and extendable for different tasks and model configurations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model |
Union[str, Path]
|
Path or name of the model to load or create. This can be a local file path, a model name from Ultralytics HUB, or a Triton Server model. Defaults to 'yolov8n.pt'. |
'yolov8n.pt'
|
task |
Any
|
The task type associated with the YOLO model. This can be used to specify the model's application domain, such as object detection, segmentation, etc. Defaults to None. |
None
|
verbose |
bool
|
If True, enables verbose output during the model's operations. Defaults to False. |
False
|
Attributes:
Name | Type | Description |
---|---|---|
callbacks |
dict
|
A dictionary of callback functions for various events during model operations. |
predictor |
BasePredictor
|
The predictor object used for making predictions. |
model |
Module
|
The underlying PyTorch model. |
trainer |
BaseTrainer
|
The trainer object used for training the model. |
ckpt |
dict
|
The checkpoint data if the model is loaded from a *.pt file. |
cfg |
str
|
The configuration of the model if loaded from a *.yaml file. |
ckpt_path |
str
|
The path to the checkpoint file. |
overrides |
dict
|
A dictionary of overrides for model configuration. |
metrics |
dict
|
The latest training/validation metrics. |
session |
HUBTrainingSession
|
The Ultralytics HUB session, if applicable. |
task |
str
|
The type of task the model is intended for. |
model_name |
str
|
The name of the model. |
Methods:
Name | Description |
---|---|
__call__ |
Alias for the predict method, enabling the model instance to be callable. |
_new |
Initializes a new model based on a configuration file. |
_load |
Loads a model from a checkpoint file. |
_check_is_pytorch_model |
Ensures that the model is a PyTorch model. |
reset_weights |
Resets the model's weights to their initial state. |
load |
Loads model weights from a specified file. |
save |
Saves the current state of the model to a file. |
info |
Logs or returns information about the model. |
fuse |
Fuses Conv2d and BatchNorm2d layers for optimized inference. |
predict |
Performs object detection predictions. |
track |
Performs object tracking. |
val |
Validates the model on a dataset. |
benchmark |
Benchmarks the model on various export formats. |
export |
Exports the model to different formats. |
train |
Trains the model on a dataset. |
tune |
Performs hyperparameter tuning. |
_apply |
Applies a function to the model's tensors. |
add_callback |
Adds a callback function for an event. |
clear_callback |
Clears all callbacks for an event. |
reset_callbacks |
Resets all callbacks to their default functions. |
_get_hub_session |
Retrieves or creates an Ultralytics HUB session. |
is_triton_model |
Checks if a model is a Triton Server model. |
is_hub_model |
Checks if a model is an Ultralytics HUB model. |
_reset_ckpt_args |
Resets checkpoint arguments when loading a PyTorch model. |
_smart_load |
Loads the appropriate module based on the model task. |
task_map |
Provides a mapping from model tasks to corresponding classes. |
Raises:
Type | Description |
---|---|
FileNotFoundError
|
If the specified model file does not exist or is inaccessible. |
ValueError
|
If the model file or configuration is invalid or unsupported. |
ImportError
|
If required dependencies for specific model types (like HUB SDK) are not installed. |
TypeError
|
If the model is not a PyTorch model when required. |
AttributeError
|
If required attributes or methods are not implemented or available. |
NotImplementedError
|
If a specific model task or mode is not supported. |
Source code in ultralytics/engine/model.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 |
|
device: torch.device
property
Retrieves the device on which the model's parameters are allocated.
This property is used to determine whether the model's parameters are on CPU or GPU. It only applies to models that are instances of nn.Module.
Returns:
Type | Description |
---|---|
device | None
|
The device (CPU/GPU) of the model if it is a PyTorch model, otherwise None. |
names: list
property
Retrieves the class names associated with the loaded model.
This property returns the class names if they are defined in the model. It checks the class names for validity using the 'check_class_names' function from the ultralytics.nn.autobackend module.
Returns:
Type | Description |
---|---|
list | None
|
The class names of the model if available, otherwise None. |
task_map: dict
property
Map head to model, trainer, validator, and predictor classes.
Returns:
Name | Type | Description |
---|---|---|
task_map |
dict
|
The map of model task to mode classes. |
transforms
property
Retrieves the transformations applied to the input data of the loaded model.
This property returns the transformations if they are defined in the model.
Returns:
Type | Description |
---|---|
object | None
|
The transform object of the model if available, otherwise None. |
__call__(source=None, stream=False, **kwargs)
An alias for the predict method, enabling the model instance to be callable.
This method simplifies the process of making predictions by allowing the model instance to be called directly with the required arguments for prediction.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
source |
str | Path | int | Image | ndarray
|
The source of the image for making predictions. Accepts various types, including file paths, URLs, PIL images, and numpy arrays. Defaults to None. |
None
|
stream |
bool
|
If True, treats the input source as a continuous stream for predictions. Defaults to False. |
False
|
**kwargs |
any
|
Additional keyword arguments for configuring the prediction process. |
{}
|
Returns:
Type | Description |
---|---|
List[Results]
|
A list of prediction results, encapsulated in the Results class. |
Source code in ultralytics/engine/model.py
__init__(model='yolov8n.pt', task=None, verbose=False)
Initializes a new instance of the YOLO model class.
This constructor sets up the model based on the provided model path or name. It handles various types of model sources, including local files, Ultralytics HUB models, and Triton Server models. The method initializes several important attributes of the model and prepares it for operations like training, prediction, or export.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model |
Union[str, Path]
|
The path or model file to load or create. This can be a local file path, a model name from Ultralytics HUB, or a Triton Server model. Defaults to 'yolov8n.pt'. |
'yolov8n.pt'
|
task |
Any
|
The task type associated with the YOLO model, specifying its application domain. Defaults to None. |
None
|
verbose |
bool
|
If True, enables verbose output during the model's initialization and subsequent operations. Defaults to False. |
False
|
Raises:
Type | Description |
---|---|
FileNotFoundError
|
If the specified model file does not exist or is inaccessible. |
ValueError
|
If the model file or configuration is invalid or unsupported. |
ImportError
|
If required dependencies for specific model types (like HUB SDK) are not installed. |
Source code in ultralytics/engine/model.py
add_callback(event, func)
Adds a callback function for a specified event.
This method allows the user to register a custom callback function that is triggered on a specific event during model training or inference.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event |
str
|
The name of the event to attach the callback to. |
required |
func |
callable
|
The callback function to be registered. |
required |
Raises:
Type | Description |
---|---|
ValueError
|
If the event name is not recognized. |
Source code in ultralytics/engine/model.py
benchmark(**kwargs)
Benchmarks the model across various export formats to evaluate performance.
This method assesses the model's performance in different export formats, such as ONNX, TorchScript, etc. It uses the 'benchmark' function from the ultralytics.utils.benchmarks module. The benchmarking is configured using a combination of default configuration values, model-specific arguments, method-specific defaults, and any additional user-provided keyword arguments.
The method supports various arguments that allow customization of the benchmarking process, such as dataset choice, image size, precision modes, device selection, and verbosity. For a comprehensive list of all configurable options, users should refer to the 'configuration' section in the documentation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
**kwargs |
any
|
Arbitrary keyword arguments to customize the benchmarking process. These are combined with default configurations, model-specific arguments, and method defaults. |
{}
|
Returns:
Type | Description |
---|---|
dict
|
A dictionary containing the results of the benchmarking process. |
Raises:
Type | Description |
---|---|
AssertionError
|
If the model is not a PyTorch model. |
Source code in ultralytics/engine/model.py
clear_callback(event)
Clears all callback functions registered for a specified event.
This method removes all custom and default callback functions associated with the given event.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event |
str
|
The name of the event for which to clear the callbacks. |
required |
Raises:
Type | Description |
---|---|
ValueError
|
If the event name is not recognized. |
Source code in ultralytics/engine/model.py
embed(source=None, stream=False, **kwargs)
Generates image embeddings based on the provided source.
This method is a wrapper around the 'predict()' method, focusing on generating embeddings from an image source. It allows customization of the embedding process through various keyword arguments.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
source |
str | int | Image | ndarray
|
The source of the image for generating embeddings. The source can be a file path, URL, PIL image, numpy array, etc. Defaults to None. |
None
|
stream |
bool
|
If True, predictions are streamed. Defaults to False. |
False
|
**kwargs |
any
|
Additional keyword arguments for configuring the embedding process. |
{}
|
Returns:
Type | Description |
---|---|
List[Tensor]
|
A list containing the image embeddings. |
Raises:
Type | Description |
---|---|
AssertionError
|
If the model is not a PyTorch model. |
Source code in ultralytics/engine/model.py
export(**kwargs)
Exports the model to a different format suitable for deployment.
This method facilitates the export of the model to various formats (e.g., ONNX, TorchScript) for deployment purposes. It uses the 'Exporter' class for the export process, combining model-specific overrides, method defaults, and any additional arguments provided. The combined arguments are used to configure export settings.
The method supports a wide range of arguments to customize the export process. For a comprehensive list of all possible arguments, refer to the 'configuration' section in the documentation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
**kwargs |
any
|
Arbitrary keyword arguments to customize the export process. These are combined with the model's overrides and method defaults. |
{}
|
Returns:
Type | Description |
---|---|
object
|
The exported model in the specified format, or an object related to the export process. |
Raises:
Type | Description |
---|---|
AssertionError
|
If the model is not a PyTorch model. |
Source code in ultralytics/engine/model.py
fuse()
Fuses Conv2d and BatchNorm2d layers in the model.
This method optimizes the model by fusing Conv2d and BatchNorm2d layers, which can improve inference speed.
Raises:
Type | Description |
---|---|
AssertionError
|
If the model is not a PyTorch model. |
Source code in ultralytics/engine/model.py
info(detailed=False, verbose=True)
Logs or returns model information.
This method provides an overview or detailed information about the model, depending on the arguments passed. It can control the verbosity of the output.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
detailed |
bool
|
If True, shows detailed information about the model. Defaults to False. |
False
|
verbose |
bool
|
If True, prints the information. If False, returns the information. Defaults to True. |
True
|
Returns:
Type | Description |
---|---|
list
|
Various types of information about the model, depending on the 'detailed' and 'verbose' parameters. |
Raises:
Type | Description |
---|---|
AssertionError
|
If the model is not a PyTorch model. |
Source code in ultralytics/engine/model.py
is_hub_model(model)
staticmethod
Check if the provided model is a HUB model.
Source code in ultralytics/engine/model.py
is_triton_model(model)
staticmethod
Is model a Triton Server URL string, i.e.
Source code in ultralytics/engine/model.py
load(weights='yolov8n.pt')
Loads parameters from the specified weights file into the model.
This method supports loading weights from a file or directly from a weights object. It matches parameters by name and shape and transfers them to the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
weights |
str | Path
|
Path to the weights file or a weights object. Defaults to 'yolov8n.pt'. |
'yolov8n.pt'
|
Returns:
Name | Type | Description |
---|---|---|
self |
Model
|
The instance of the class with loaded weights. |
Raises:
Type | Description |
---|---|
AssertionError
|
If the model is not a PyTorch model. |
Source code in ultralytics/engine/model.py
predict(source=None, stream=False, predictor=None, **kwargs)
Performs predictions on the given image source using the YOLO model.
This method facilitates the prediction process, allowing various configurations through keyword arguments. It supports predictions with custom predictors or the default predictor method. The method handles different types of image sources and can operate in a streaming mode. It also provides support for SAM-type models through 'prompts'.
The method sets up a new predictor if not already present and updates its arguments with each call. It also issues a warning and uses default assets if the 'source' is not provided. The method determines if it is being called from the command line interface and adjusts its behavior accordingly, including setting defaults for confidence threshold and saving behavior.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
source |
str | int | Image | ndarray
|
The source of the image for making predictions. Accepts various types, including file paths, URLs, PIL images, and numpy arrays. Defaults to ASSETS. |
None
|
stream |
bool
|
Treats the input source as a continuous stream for predictions. Defaults to False. |
False
|
predictor |
BasePredictor
|
An instance of a custom predictor class for making predictions. If None, the method uses a default predictor. Defaults to None. |
None
|
**kwargs |
any
|
Additional keyword arguments for configuring the prediction process. These arguments allow for further customization of the prediction behavior. |
{}
|
Returns:
Type | Description |
---|---|
List[Results]
|
A list of prediction results, encapsulated in the Results class. |
Raises:
Type | Description |
---|---|
AttributeError
|
If the predictor is not properly set up. |
Source code in ultralytics/engine/model.py
reset_callbacks()
Resets all callbacks to their default functions.
This method reinstates the default callback functions for all events, removing any custom callbacks that were added previously.
Source code in ultralytics/engine/model.py
reset_weights()
Resets the model parameters to randomly initialized values, effectively discarding all training information.
This method iterates through all modules in the model and resets their parameters if they have a 'reset_parameters' method. It also ensures that all parameters have 'requires_grad' set to True, enabling them to be updated during training.
Returns:
Name | Type | Description |
---|---|---|
self |
Model
|
The instance of the class with reset weights. |
Raises:
Type | Description |
---|---|
AssertionError
|
If the model is not a PyTorch model. |
Source code in ultralytics/engine/model.py
save(filename='saved_model.pt', use_dill=True)
Saves the current model state to a file.
This method exports the model's checkpoint (ckpt) to the specified filename.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filename |
str | Path
|
The name of the file to save the model to. Defaults to 'saved_model.pt'. |
'saved_model.pt'
|
use_dill |
bool
|
Whether to try using dill for serialization if available. Defaults to True. |
True
|
Raises:
Type | Description |
---|---|
AssertionError
|
If the model is not a PyTorch model. |
Source code in ultralytics/engine/model.py
track(source=None, stream=False, persist=False, **kwargs)
Conducts object tracking on the specified input source using the registered trackers.
This method performs object tracking using the model's predictors and optionally registered trackers. It is capable of handling different types of input sources such as file paths or video streams. The method supports customization of the tracking process through various keyword arguments. It registers trackers if they are not already present and optionally persists them based on the 'persist' flag.
The method sets a default confidence threshold specifically for ByteTrack-based tracking, which requires low confidence predictions as input. The tracking mode is explicitly set in the keyword arguments.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
source |
str
|
The input source for object tracking. It can be a file path, URL, or video stream. |
None
|
stream |
bool
|
Treats the input source as a continuous video stream. Defaults to False. |
False
|
persist |
bool
|
Persists the trackers between different calls to this method. Defaults to False. |
False
|
**kwargs |
any
|
Additional keyword arguments for configuring the tracking process. These arguments allow for further customization of the tracking behavior. |
{}
|
Returns:
Type | Description |
---|---|
List[Results]
|
A list of tracking results, encapsulated in the Results class. |
Raises:
Type | Description |
---|---|
AttributeError
|
If the predictor does not have registered trackers. |
Source code in ultralytics/engine/model.py
train(trainer=None, **kwargs)
Trains the model using the specified dataset and training configuration.
This method facilitates model training with a range of customizable settings and configurations. It supports training with a custom trainer or the default training approach defined in the method. The method handles different scenarios, such as resuming training from a checkpoint, integrating with Ultralytics HUB, and updating model and configuration after training.
When using Ultralytics HUB, if the session already has a loaded model, the method prioritizes HUB training arguments and issues a warning if local arguments are provided. It checks for pip updates and combines default configurations, method-specific defaults, and user-provided arguments to configure the training process. After training, it updates the model and its configurations, and optionally attaches metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
trainer |
BaseTrainer
|
An instance of a custom trainer class for training the model. If None, the method uses a default trainer. Defaults to None. |
None
|
**kwargs |
any
|
Arbitrary keyword arguments representing the training configuration. These arguments are used to customize various aspects of the training process. |
{}
|
Returns:
Type | Description |
---|---|
dict | None
|
Training metrics if available and training is successful; otherwise, None. |
Raises:
Type | Description |
---|---|
AssertionError
|
If the model is not a PyTorch model. |
PermissionError
|
If there is a permission issue with the HUB session. |
ModuleNotFoundError
|
If the HUB SDK is not installed. |
Source code in ultralytics/engine/model.py
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 |
|
tune(use_ray=False, iterations=10, *args, **kwargs)
Conducts hyperparameter tuning for the model, with an option to use Ray Tune.
This method supports two modes of hyperparameter tuning: using Ray Tune or a custom tuning method. When Ray Tune is enabled, it leverages the 'run_ray_tune' function from the ultralytics.utils.tuner module. Otherwise, it uses the internal 'Tuner' class for tuning. The method combines default, overridden, and custom arguments to configure the tuning process.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
use_ray |
bool
|
If True, uses Ray Tune for hyperparameter tuning. Defaults to False. |
False
|
iterations |
int
|
The number of tuning iterations to perform. Defaults to 10. |
10
|
*args |
list
|
Variable length argument list for additional arguments. |
()
|
**kwargs |
any
|
Arbitrary keyword arguments. These are combined with the model's overrides and defaults. |
{}
|
Returns:
Type | Description |
---|---|
dict
|
A dictionary containing the results of the hyperparameter search. |
Raises:
Type | Description |
---|---|
AssertionError
|
If the model is not a PyTorch model. |
Source code in ultralytics/engine/model.py
val(validator=None, **kwargs)
Validates the model using a specified dataset and validation configuration.
This method facilitates the model validation process, allowing for a range of customization through various settings and configurations. It supports validation with a custom validator or the default validation approach. The method combines default configurations, method-specific defaults, and user-provided arguments to configure the validation process. After validation, it updates the model's metrics with the results obtained from the validator.
The method supports various arguments that allow customization of the validation process. For a comprehensive list of all configurable options, users should refer to the 'configuration' section in the documentation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
validator |
BaseValidator
|
An instance of a custom validator class for validating the model. If None, the method uses a default validator. Defaults to None. |
None
|
**kwargs |
any
|
Arbitrary keyword arguments representing the validation configuration. These arguments are used to customize various aspects of the validation process. |
{}
|
Returns:
Type | Description |
---|---|
dict
|
Validation metrics obtained from the validation process. |
Raises:
Type | Description |
---|---|
AssertionError
|
If the model is not a PyTorch model. |