Reference for ultralytics/nn/tasks.py
Note
This file is available at https://github.com/ultralytics/ultralytics/blob/main/ultralytics/nn/tasks.py. If you spot a problem please help fix it by contributing a Pull Request 🛠️. Thank you 🙏!
ultralytics.nn.tasks.BaseModel
Bases: Module
The BaseModel class serves as a base class for all the models in the Ultralytics YOLO family.
forward
Forward pass of the model on a single scale. Wrapper for _forward_once
method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
Tensor | dict
|
The input image tensor or a dict including image tensor and gt labels. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
The output of the network. |
Source code in ultralytics/nn/tasks.py
fuse
Fuse the Conv2d()
and BatchNorm2d()
layers of the model into a single layer, in order to improve the
computation efficiency.
Returns:
Type | Description |
---|---|
Module
|
The fused model is returned. |
Source code in ultralytics/nn/tasks.py
info
Prints model information.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
detailed |
bool
|
if True, prints out detailed information about the model. Defaults to False |
False
|
verbose |
bool
|
if True, prints out the model information. Defaults to False |
True
|
imgsz |
int
|
the size of the image that the model will be trained on. Defaults to 640 |
640
|
Source code in ultralytics/nn/tasks.py
init_criterion
is_fused
Check if the model has less than a certain threshold of BatchNorm layers.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
thresh |
int
|
The threshold number of BatchNorm layers. Default is 10. |
10
|
Returns:
Type | Description |
---|---|
bool
|
True if the number of BatchNorm layers in the model is less than the threshold, False otherwise. |
Source code in ultralytics/nn/tasks.py
load
Load the weights into the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
weights |
dict | Module
|
The pre-trained weights to be loaded. |
required |
verbose |
bool
|
Whether to log the transfer progress. Defaults to True. |
True
|
Source code in ultralytics/nn/tasks.py
loss
Compute loss.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch |
dict
|
Batch to compute loss on |
required |
preds |
Tensor | List[Tensor]
|
Predictions. |
None
|
Source code in ultralytics/nn/tasks.py
predict
Perform a forward pass through the network.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
Tensor
|
The input tensor to the model. |
required |
profile |
bool
|
Print the computation time of each layer if True, defaults to False. |
False
|
visualize |
bool
|
Save the feature maps of the model if True, defaults to False. |
False
|
augment |
bool
|
Augment image during prediction, defaults to False. |
False
|
embed |
list
|
A list of feature vectors/embeddings to return. |
None
|
Returns:
Type | Description |
---|---|
Tensor
|
The last output of the model. |
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.DetectionModel
Bases: BaseModel
YOLOv8 detection model.
Source code in ultralytics/nn/tasks.py
init_criterion
ultralytics.nn.tasks.OBBModel
Bases: DetectionModel
YOLOv8 Oriented Bounding Box (OBB) model.
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.SegmentationModel
ultralytics.nn.tasks.PoseModel
Bases: DetectionModel
YOLOv8 pose model.
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.ClassificationModel
Bases: BaseModel
YOLOv8 classification model.
Source code in ultralytics/nn/tasks.py
init_criterion
reshape_outputs
staticmethod
Update a TorchVision classification model to class count 'n' if required.
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.RTDETRDetectionModel
Bases: DetectionModel
RTDETR (Real-time DEtection and Tracking using Transformers) Detection Model class.
This class is responsible for constructing the RTDETR architecture, defining loss functions, and facilitating both the training and inference processes. RTDETR is an object detection and tracking model that extends from the DetectionModel base class.
Attributes:
Name | Type | Description |
---|---|---|
cfg |
str
|
The configuration file path or preset string. Default is 'rtdetr-l.yaml'. |
ch |
int
|
Number of input channels. Default is 3 (RGB). |
nc |
int
|
Number of classes for object detection. Default is None. |
verbose |
bool
|
Specifies if summary statistics are shown during initialization. Default is True. |
Methods:
Name | Description |
---|---|
init_criterion |
Initializes the criterion used for loss calculation. |
loss |
Computes and returns the loss during training. |
predict |
Performs a forward pass through the network and returns the output. |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cfg |
str
|
Configuration file name or path. |
'rtdetr-l.yaml'
|
ch |
int
|
Number of input channels. |
3
|
nc |
int
|
Number of classes. Defaults to None. |
None
|
verbose |
bool
|
Print additional information during initialization. Defaults to True. |
True
|
Source code in ultralytics/nn/tasks.py
init_criterion
Initialize the loss criterion for the RTDETRDetectionModel.
loss
Compute the loss for the given batch of data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch |
dict
|
Dictionary containing image and label data. |
required |
preds |
Tensor
|
Precomputed model predictions. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
tuple
|
A tuple containing the total loss and main three losses in a tensor. |
Source code in ultralytics/nn/tasks.py
predict
Perform a forward pass through the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
Tensor
|
The input tensor. |
required |
profile |
bool
|
If True, profile the computation time for each layer. Defaults to False. |
False
|
visualize |
bool
|
If True, save feature maps for visualization. Defaults to False. |
False
|
batch |
dict
|
Ground truth data for evaluation. Defaults to None. |
None
|
augment |
bool
|
If True, perform data augmentation during inference. Defaults to False. |
False
|
embed |
list
|
A list of feature vectors/embeddings to return. |
None
|
Returns:
Type | Description |
---|---|
Tensor
|
Model's output tensor. |
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.WorldModel
Bases: DetectionModel
YOLOv8 World Model.
Source code in ultralytics/nn/tasks.py
loss
Compute loss.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch |
dict
|
Batch to compute loss on. |
required |
preds |
Tensor | List[Tensor]
|
Predictions. |
None
|
Source code in ultralytics/nn/tasks.py
predict
Perform a forward pass through the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
Tensor
|
The input tensor. |
required |
profile |
bool
|
If True, profile the computation time for each layer. Defaults to False. |
False
|
visualize |
bool
|
If True, save feature maps for visualization. Defaults to False. |
False
|
txt_feats |
Tensor
|
The text features, use it if it's given. Defaults to None. |
None
|
augment |
bool
|
If True, perform data augmentation during inference. Defaults to False. |
False
|
embed |
list
|
A list of feature vectors/embeddings to return. |
None
|
Returns:
Type | Description |
---|---|
Tensor
|
Model's output tensor. |
Source code in ultralytics/nn/tasks.py
set_classes
Set classes in advance so that model could do offline-inference without clip model.
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.Ensemble
Bases: ModuleList
Ensemble of models.
Source code in ultralytics/nn/tasks.py
forward
Function generates the YOLO network's final layer.
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.temporary_modules
Context manager for temporarily adding or modifying modules in Python's module cache (sys.modules
).
This function can be used to change the module paths during runtime. It's useful when refactoring code, where you've moved a module from one location to another, but you still want to support the old import paths for backwards compatibility.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
modules |
dict
|
A dictionary mapping old module paths to new module paths. |
None
|
attributes |
dict
|
A dictionary mapping old module attributes to new module attributes. |
None
|
Example
Note
The changes are only in effect inside the context manager and are undone once the context manager exits.
Be aware that directly manipulating sys.modules
can lead to unpredictable results, especially in larger
applications or libraries. Use this function with caution.
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.torch_safe_load
This function attempts to load a PyTorch model with the torch.load() function. If a ModuleNotFoundError is raised, it catches the error, logs a warning message, and attempts to install the missing module via the check_requirements() function. After installation, the function again attempts to load the model using torch.load().
Parameters:
Name | Type | Description | Default |
---|---|---|---|
weight |
str
|
The file path of the PyTorch model. |
required |
Returns:
Type | Description |
---|---|
dict
|
The loaded PyTorch model. |
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.attempt_load_weights
Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a.
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.attempt_load_one_weight
Loads a single model weights.
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.parse_model
Parse a YOLO model.yaml dictionary into a PyTorch model.
Source code in ultralytics/nn/tasks.py
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 |
|
ultralytics.nn.tasks.yaml_model_load
Load a YOLOv8 model from a YAML file.
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.guess_model_scale
Takes a path to a YOLO model's YAML file as input and extracts the size character of the model's scale. The function uses regular expression matching to find the pattern of the model scale in the YAML file name, which is denoted by n, s, m, l, or x. The function returns the size character of the model scale as a string.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_path |
str | Path
|
The path to the YOLO model's YAML file. |
required |
Returns:
Type | Description |
---|---|
str
|
The size character of the model's scale, which can be n, s, m, l, or x. |
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.guess_model_task
Guess the task of a PyTorch model from its architecture or configuration.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model |
Module | dict
|
PyTorch model or model configuration in YAML format. |
required |
Returns:
Type | Description |
---|---|
str
|
Task of the model ('detect', 'segment', 'classify', 'pose'). |
Raises:
Type | Description |
---|---|
SyntaxError
|
If the task of the model could not be determined. |
Source code in ultralytics/nn/tasks.py
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 |
|