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.
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. |
Examples:
>>> from ultralytics import YOLO
>>> model = YOLO("yolov8n.pt")
>>> results = model.predict("image.jpg")
>>> model.train(data="coco128.yaml", epochs=3)
>>> metrics = model.val()
>>> model.export(format="onnx")
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]
|
Path or name of the model to load or create. Can be a local file path, a model name from Ultralytics HUB, or a Triton Server model. |
'yolov8n.pt'
|
task |
str | None
|
The task type associated with the YOLO model, specifying its application domain. |
None
|
verbose |
bool
|
If True, enables verbose output during the model's initialization and subsequent operations. |
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. |
Examples:
>>> model = Model("yolov8n.pt")
>>> model = Model("path/to/model.yaml", task="detect")
>>> model = Model("hub_model", verbose=True)
Source code in ultralytics/engine/model.py
device
property
Retrieves the device on which the model's parameters are allocated.
This property determines the device (CPU or GPU) where the model's parameters are currently stored. It is applicable only to models that are instances of nn.Module.
Returns:
Type | Description |
---|---|
device
|
The device (CPU/GPU) of the model. |
Raises:
Type | Description |
---|---|
AttributeError
|
If the model is not a PyTorch nn.Module instance. |
Examples:
names
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. If the predictor is not initialized, it sets it up before retrieving the names.
Returns:
Type | Description |
---|---|
Dict[int, str]
|
A dict of class names associated with the model. |
Raises:
Type | Description |
---|---|
AttributeError
|
If the model or predictor does not have a 'names' attribute. |
Examples:
task_map
property
Provides a mapping from model tasks to corresponding classes for different modes.
This property method returns a dictionary that maps each supported task (e.g., detect, segment, classify) to a nested dictionary. The nested dictionary contains mappings for different operational modes (model, trainer, validator, predictor) to their respective class implementations.
The mapping allows for dynamic loading of appropriate classes based on the model's task and the desired operational mode. This facilitates a flexible and extensible architecture for handling various tasks and modes within the Ultralytics framework.
Returns:
Type | Description |
---|---|
Dict[str, Dict[str, Any]]
|
A dictionary where keys are task names (str) and values are |
dict
|
nested dictionaries. Each nested dictionary has keys 'model', 'trainer', 'validator', and |
dict
|
'predictor', mapping to their respective class implementations. |
Examples:
>>> model = Model()
>>> task_map = model.task_map
>>> detect_class_map = task_map["detect"]
>>> segment_class_map = task_map["segment"]
Note
The actual implementation of this method may vary depending on the specific tasks and classes supported by the Ultralytics framework. The docstring provides a general description of the expected behavior and structure.
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. The transforms typically include preprocessing steps like resizing, normalization, and data augmentation that are applied to input data before it is fed into the model.
Returns:
Type | Description |
---|---|
object | None
|
The transform object of the model if available, otherwise None. |
Examples:
__call__
__call__(
source: Union[
str, Path, int, Image.Image, list, tuple, np.ndarray, torch.Tensor
] = None,
stream: bool = False,
**kwargs
) -> list
Alias for the predict method, enabling the model instance to be callable for predictions.
This method simplifies the process of making predictions by allowing the model instance to be called directly with the required arguments.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
source |
str | Path | int | Image | ndarray | Tensor | List | Tuple
|
The source of the image(s) to make predictions on. Can be a file path, URL, PIL image, numpy array, PyTorch tensor, or a list/tuple of these. |
None
|
stream |
bool
|
If True, treat the input source as a continuous stream for predictions. |
False
|
**kwargs |
Any
|
Additional keyword arguments to configure the prediction process. |
{}
|
Returns:
Type | Description |
---|---|
List[Results]
|
A list of prediction results, each encapsulated in a Results object. |
Examples:
>>> model = YOLO("yolov8n.pt")
>>> results = model("https://ultralytics.com/images/bus.jpg")
>>> for r in results:
... print(f"Detected {len(r)} objects in image")
Source code in ultralytics/engine/model.py
add_callback
Adds a callback function for a specified event.
This method allows registering custom callback functions that are triggered on specific events during model operations such as training or inference. Callbacks provide a way to extend and customize the behavior of the model at various stages of its lifecycle.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event |
str
|
The name of the event to attach the callback to. Must be a valid event name recognized by the Ultralytics framework. |
required |
func |
Callable
|
The callback function to be registered. This function will be called when the specified event occurs. |
required |
Raises:
Type | Description |
---|---|
ValueError
|
If the event name is not recognized or is invalid. |
Examples:
>>> def on_train_start(trainer):
... print("Training is starting!")
>>> model = YOLO("yolov8n.pt")
>>> model.add_callback("on_train_start", on_train_start)
>>> model.train(data="coco128.yaml", epochs=1)
Source code in ultralytics/engine/model.py
benchmark
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.
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. Common options include: - data (str): Path to the dataset for benchmarking. - imgsz (int | List[int]): Image size for benchmarking. - half (bool): Whether to use half-precision (FP16) mode. - int8 (bool): Whether to use int8 precision mode. - device (str): Device to run the benchmark on (e.g., 'cpu', 'cuda'). - verbose (bool): Whether to print detailed benchmark information. |
{}
|
Returns:
Type | Description |
---|---|
Dict
|
A dictionary containing the results of the benchmarking process, including metrics for different export formats. |
Raises:
Type | Description |
---|---|
AssertionError
|
If the model is not a PyTorch model. |
Examples:
>>> model = YOLO("yolov8n.pt")
>>> results = model.benchmark(data="coco8.yaml", imgsz=640, half=True)
>>> print(results)
Source code in ultralytics/engine/model.py
clear_callback
Clears all callback functions registered for a specified event.
This method removes all custom and default callback functions associated with the given event. It resets the callback list for the specified event to an empty list, effectively removing all registered callbacks for that event.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event |
str
|
The name of the event for which to clear the callbacks. This should be a valid event name recognized by the Ultralytics callback system. |
required |
Examples:
>>> model = YOLO("yolov8n.pt")
>>> model.add_callback("on_train_start", lambda: print("Training started"))
>>> model.clear_callback("on_train_start")
>>> # All callbacks for 'on_train_start' are now removed
Notes
- This method affects both custom callbacks added by the user and default callbacks provided by the Ultralytics framework.
- After calling this method, no callbacks will be executed for the specified event until new ones are added.
- Use with caution as it removes all callbacks, including essential ones that might be required for proper functioning of certain operations.
Source code in ultralytics/engine/model.py
embed
embed(
source: Union[str, Path, int, list, tuple, np.ndarray, torch.Tensor] = None,
stream: bool = False,
**kwargs
) -> list
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 | Path | int | List | Tuple | ndarray | Tensor
|
The source of the image for generating embeddings. Can be a file path, URL, PIL image, numpy array, etc. |
None
|
stream |
bool
|
If True, predictions are streamed. |
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. |
Examples:
>>> model = YOLO("yolov8n.pt")
>>> image = "https://ultralytics.com/images/bus.jpg"
>>> embeddings = model.embed(image)
>>> print(embeddings[0].shape)
Source code in ultralytics/engine/model.py
export
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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
**kwargs |
Dict
|
Arbitrary keyword arguments to customize the export process. These are combined with the model's overrides and method defaults. Common arguments include: format (str): Export format (e.g., 'onnx', 'engine', 'coreml'). half (bool): Export model in half-precision. int8 (bool): Export model in int8 precision. device (str): Device to run the export on. workspace (int): Maximum memory workspace size for TensorRT engines. nms (bool): Add Non-Maximum Suppression (NMS) module to model. simplify (bool): Simplify ONNX model. |
{}
|
Returns:
Type | Description |
---|---|
str
|
The path to the exported model file. |
Raises:
Type | Description |
---|---|
AssertionError
|
If the model is not a PyTorch model. |
ValueError
|
If an unsupported export format is specified. |
RuntimeError
|
If the export process fails due to errors. |
Examples:
>>> model = YOLO("yolov8n.pt")
>>> model.export(format="onnx", dynamic=True, simplify=True)
'path/to/exported/model.onnx'
Source code in ultralytics/engine/model.py
fuse
Fuses Conv2d and BatchNorm2d layers in the model for optimized inference.
This method iterates through the model's modules and fuses consecutive Conv2d and BatchNorm2d layers into a single layer. This fusion can significantly improve inference speed by reducing the number of operations and memory accesses required during forward passes.
The fusion process typically involves folding the BatchNorm2d parameters (mean, variance, weight, and bias) into the preceding Conv2d layer's weights and biases. This results in a single Conv2d layer that performs both convolution and normalization in one step.
Raises:
Type | Description |
---|---|
TypeError
|
If the model is not a PyTorch nn.Module. |
Examples:
>>> model = Model("yolov8n.pt")
>>> model.fuse()
>>> # Model is now fused and ready for optimized inference
Source code in ultralytics/engine/model.py
info
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 and return the information as a list.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
detailed |
bool
|
If True, shows detailed information about the model layers and parameters. |
False
|
verbose |
bool
|
If True, prints the information. If False, returns the information as a list. |
True
|
Returns:
Type | Description |
---|---|
List[str]
|
A list of strings containing various types of information about the model, including model summary, layer details, and parameter counts. Empty if verbose is True. |
Raises:
Type | Description |
---|---|
TypeError
|
If the model is not a PyTorch model. |
Examples:
>>> model = Model("yolov8n.pt")
>>> model.info() # Prints model summary
>>> info_list = model.info(detailed=True, verbose=False) # Returns detailed info as a list
Source code in ultralytics/engine/model.py
is_hub_model
staticmethod
Check if the provided model is an Ultralytics HUB model.
This static method determines whether the given model string represents a valid Ultralytics HUB model identifier.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model |
str
|
The model string to check. |
required |
Returns:
Type | Description |
---|---|
bool
|
True if the model is a valid Ultralytics HUB model, False otherwise. |
Examples:
>>> Model.is_hub_model("https://hub.ultralytics.com/models/MODEL")
True
>>> Model.is_hub_model("yolov8n.pt")
False
Source code in ultralytics/engine/model.py
is_triton_model
staticmethod
Checks if the given model string is a Triton Server URL.
This static method determines whether the provided model string represents a valid Triton Server URL by parsing its components using urllib.parse.urlsplit().
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model |
str
|
The model string to be checked. |
required |
Returns:
Type | Description |
---|---|
bool
|
True if the model string is a valid Triton Server URL, False otherwise. |
Examples:
>>> Model.is_triton_model("http://localhost:8000/v2/models/yolov8n")
True
>>> Model.is_triton_model("yolov8n.pt")
False
Source code in ultralytics/engine/model.py
load
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 |
Union[str, Path]
|
Path to the weights file or a weights object. |
'yolov8n.pt'
|
Returns:
Type | Description |
---|---|
Model
|
The instance of the class with loaded weights. |
Raises:
Type | Description |
---|---|
AssertionError
|
If the model is not a PyTorch model. |
Examples:
Source code in ultralytics/engine/model.py
predict
predict(
source: Union[
str, Path, int, Image.Image, list, tuple, np.ndarray, torch.Tensor
] = None,
stream: bool = False,
predictor=None,
**kwargs
) -> List[Results]
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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
source |
str | Path | int | Image | ndarray | Tensor | List | Tuple
|
The source of the image(s) to make predictions on. Accepts various types including file paths, URLs, PIL images, numpy arrays, and torch tensors. |
None
|
stream |
bool
|
If True, treats the input source as a continuous stream for predictions. |
False
|
predictor |
BasePredictor | None
|
An instance of a custom predictor class for making predictions. If None, the method uses a default predictor. |
None
|
**kwargs |
Any
|
Additional keyword arguments for configuring the prediction process. |
{}
|
Returns:
Type | Description |
---|---|
List[Results]
|
A list of prediction results, each encapsulated in a Results object. |
Examples:
>>> model = YOLO("yolov8n.pt")
>>> results = model.predict(source="path/to/image.jpg", conf=0.25)
>>> for r in results:
... print(r.boxes.data) # print detection bounding boxes
Notes
- If 'source' is not provided, it defaults to the ASSETS constant with a warning.
- The method sets up a new predictor if not already present and updates its arguments with each call.
- For SAM-type models, 'prompts' can be passed as a keyword argument.
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 previously added. It iterates through all default callback events and replaces the current callbacks with the default ones.
The default callbacks are defined in the 'callbacks.default_callbacks' dictionary, which contains predefined functions for various events in the model's lifecycle, such as on_train_start, on_epoch_end, etc.
This method is useful when you want to revert to the original set of callbacks after making custom modifications, ensuring consistent behavior across different runs or experiments.
Examples:
>>> model = YOLO("yolov8n.pt")
>>> model.add_callback("on_train_start", custom_function)
>>> model.reset_callbacks()
# All callbacks are now reset to their default functions
Source code in ultralytics/engine/model.py
reset_weights
Resets the model's weights to their initial state.
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:
Type | Description |
---|---|
Model
|
The instance of the class with reset weights. |
Raises:
Type | Description |
---|---|
AssertionError
|
If the model is not a PyTorch model. |
Examples:
Source code in ultralytics/engine/model.py
save
Saves the current model state to a file.
This method exports the model's checkpoint (ckpt) to the specified filename. It includes metadata such as the date, Ultralytics version, license information, and a link to the documentation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filename |
Union[str, Path]
|
The name of the file to save the model to. |
'saved_model.pt'
|
Raises:
Type | Description |
---|---|
AssertionError
|
If the model is not a PyTorch model. |
Examples:
Source code in ultralytics/engine/model.py
track
track(
source: Union[str, Path, int, list, tuple, np.ndarray, torch.Tensor] = None,
stream: bool = False,
persist: bool = False,
**kwargs
) -> List[Results]
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 handles various input sources such as file paths or video streams, and supports customization through keyword arguments. The method registers trackers if not already present and can persist them between calls.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
source |
Union[str, Path, int, List, Tuple, ndarray, Tensor]
|
Input source for object tracking. Can be a file path, URL, or video stream. |
None
|
stream |
bool
|
If True, treats the input source as a continuous video stream. Defaults to False. |
False
|
persist |
bool
|
If True, persists trackers between different calls to this method. Defaults to False. |
False
|
**kwargs |
Any
|
Additional keyword arguments for configuring the tracking process. |
{}
|
Returns:
Type | Description |
---|---|
List[Results]
|
A list of tracking results, each a Results object. |
Raises:
Type | Description |
---|---|
AttributeError
|
If the predictor does not have registered trackers. |
Examples:
>>> model = YOLO("yolov8n.pt")
>>> results = model.track(source="path/to/video.mp4", show=True)
>>> for r in results:
... print(r.boxes.id) # print tracking IDs
Notes
- This method sets a default confidence threshold of 0.1 for ByteTrack-based tracking.
- The tracking mode is explicitly set in the keyword arguments.
- Batch size is set to 1 for tracking in videos.
Source code in ultralytics/engine/model.py
train
Trains the model using the specified dataset and training configuration.
This method facilitates model training with a range of customizable settings. It supports training with a custom trainer or the default training approach. The method handles 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 has a loaded model, the method prioritizes HUB training arguments and warns 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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
trainer |
BaseTrainer | None
|
Custom trainer instance for model training. If None, uses default. |
None
|
**kwargs |
Any
|
Arbitrary keyword arguments for training configuration. Common options include: data (str): Path to dataset configuration file. epochs (int): Number of training epochs. batch_size (int): Batch size for training. imgsz (int): Input image size. device (str): Device to run training on (e.g., 'cuda', 'cpu'). workers (int): Number of worker threads for data loading. optimizer (str): Optimizer to use for training. lr0 (float): Initial learning rate. patience (int): Epochs to wait for no observable improvement for early stopping of training. |
{}
|
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. |
Examples:
Source code in ultralytics/engine/model.py
tune
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 |
Dict
|
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. |
Examples:
>>> model = YOLO("yolov8n.pt")
>>> results = model.tune(use_ray=True, iterations=20)
>>> print(results)
Source code in ultralytics/engine/model.py
val
Validates the model using a specified dataset and validation configuration.
This method facilitates the model validation process, allowing for customization through various settings. 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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
validator |
BaseValidator | None
|
An instance of a custom validator class for validating the model. |
None
|
**kwargs |
Any
|
Arbitrary keyword arguments for customizing the validation process. |
{}
|
Returns:
Type | Description |
---|---|
DetMetrics
|
Validation metrics obtained from the validation process. |
Raises:
Type | Description |
---|---|
AssertionError
|
If the model is not a PyTorch model. |
Examples:
>>> model = YOLO("yolov8n.pt")
>>> results = model.val(data="coco128.yaml", imgsz=640)
>>> print(results.box.map) # Print mAP50-95