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
Perform forward pass of the model for either training or inference.
If x is a dict, calculates and returns the loss for training. Otherwise, returns predictions for inference.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x | Tensor | dict | Input tensor for inference, or dict with image tensor and labels for training. | required |
*args | Any | Variable length argument list. | () |
**kwargs | Any | Arbitrary keyword arguments. | {} |
Returns:
Type | Description |
---|---|
Tensor | Loss if x is a dict (training), or network predictions (inference). |
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.SafeClass
A placeholder class to replace unknown classes during unpickling.
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.SafeUnpickler
Bases: Unpickler
Custom Unpickler that replaces unknown classes with SafeClass.
find_class
Attempt to find a class, returning SafeClass if not among safe modules.
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
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 |
safe_only | bool | If True, replace unknown classes with SafeClass during loading. | False |
Example:
from ultralytics.nn.tasks import torch_safe_load
ckpt, file = torch_safe_load("path/to/best.pt", safe_only=True)
Returns:
Name | Type | Description |
---|---|---|
ckpt | dict | The loaded model checkpoint. |
file | str | The loaded filename |
Source code in ultralytics/nn/tasks.py
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 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 |
|
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
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 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 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 |
|
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
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 |
|