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 for improved computation
efficiency.
Returns:
Type | Description |
---|---|
Module
|
The fused model is returned. |
Source code in ultralytics/nn/tasks.py
info
Print model information.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
detailed
|
bool
|
If True, prints out detailed information about the model. |
False
|
verbose
|
bool
|
If True, prints out the model information. |
True
|
imgsz
|
int
|
The size of the image that the model will be trained on. |
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. |
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 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. |
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. |
False
|
visualize
|
bool
|
Save the feature maps of the model if True. |
False
|
augment
|
bool
|
Augment image during prediction. |
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
YOLO detection model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cfg
|
str | dict
|
Model configuration file path or dictionary. |
'yolo11n.yaml'
|
ch
|
int
|
Number of input channels. |
3
|
nc
|
int
|
Number of classes. |
None
|
verbose
|
bool
|
Whether to display model information. |
True
|
Source code in ultralytics/nn/tasks.py
init_criterion
ultralytics.nn.tasks.OBBModel
Bases: DetectionModel
YOLO Oriented Bounding Box (OBB) model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cfg
|
str | dict
|
Model configuration file path or dictionary. |
'yolo11n-obb.yaml'
|
ch
|
int
|
Number of input channels. |
3
|
nc
|
int
|
Number of classes. |
None
|
verbose
|
bool
|
Whether to display model information. |
True
|
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.SegmentationModel
Bases: DetectionModel
YOLO segmentation model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cfg
|
str | dict
|
Model configuration file path or dictionary. |
'yolo11n-seg.yaml'
|
ch
|
int
|
Number of input channels. |
3
|
nc
|
int
|
Number of classes. |
None
|
verbose
|
bool
|
Whether to display model information. |
True
|
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.PoseModel
Bases: DetectionModel
YOLO pose model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cfg
|
str | dict
|
Model configuration file path or dictionary. |
'yolo11n-pose.yaml'
|
ch
|
int
|
Number of input channels. |
3
|
nc
|
int
|
Number of classes. |
None
|
data_kpt_shape
|
tuple
|
Shape of keypoints data. |
(None, None)
|
verbose
|
bool
|
Whether to display model information. |
True
|
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.ClassificationModel
Bases: BaseModel
YOLO classification model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cfg
|
str | dict
|
Model configuration file path or dictionary. |
'yolo11n-cls.yaml'
|
ch
|
int
|
Number of input channels. |
3
|
nc
|
int
|
Number of classes. |
None
|
verbose
|
bool
|
Whether to display model information. |
True
|
Source code in ultralytics/nn/tasks.py
init_criterion
reshape_outputs
staticmethod
Update a TorchVision classification model to class count 'n' if required.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
Module
|
Model to update. |
required |
nc
|
int
|
New number of classes. |
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.
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 | dict
|
Configuration file name or path. |
'rtdetr-l.yaml'
|
ch
|
int
|
Number of input channels. |
3
|
nc
|
int
|
Number of classes. |
None
|
verbose
|
bool
|
Print additional information during initialization. |
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. |
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. |
False
|
visualize
|
bool
|
If True, save feature maps for visualization. |
False
|
batch
|
dict
|
Ground truth data for evaluation. |
None
|
augment
|
bool
|
If True, perform data augmentation during inference. |
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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cfg
|
str | dict
|
Model configuration file path or dictionary. |
'yolov8s-world.yaml'
|
ch
|
int
|
Number of input channels. |
3
|
nc
|
int
|
Number of classes. |
None
|
verbose
|
bool
|
Whether to display model information. |
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 model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Tensor
|
The input tensor. |
required |
profile
|
bool
|
If True, profile the computation time for each layer. |
False
|
visualize
|
bool
|
If True, save feature maps for visualization. |
False
|
txt_feats
|
Tensor
|
The text features, use it if it's given. |
None
|
augment
|
bool
|
If True, perform data augmentation during inference. |
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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
List[str]
|
List of class names. |
required |
batch
|
int
|
Batch size for processing text tokens. |
80
|
cache_clip_model
|
bool
|
Whether to cache the CLIP model. |
True
|
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.Ensemble
Bases: ModuleList
Ensemble of models.
Source code in ultralytics/nn/tasks.py
forward
Generate the YOLO network's final layer.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Tensor
|
Input tensor. |
required |
augment
|
bool
|
Whether to augment the input. |
False
|
profile
|
bool
|
Whether to profile the model. |
False
|
visualize
|
bool
|
Whether to visualize the features. |
False
|
Returns:
Type | Description |
---|---|
tuple
|
Tuple containing the concatenated predictions and None. |
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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
module
|
str
|
Module name. |
required |
name
|
str
|
Class name. |
required |
Returns:
Type | Description |
---|---|
type
|
Found class or SafeClass. |
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
|
Examples:
>>> with temporary_modules({"old.module": "new.module"}, {"old.module.attribute": "new.module.attribute"}):
>>> import old.module # this will now import new.module
>>> from old.module import attribute # this will now import new.module.attribute
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
|
Returns:
Name | Type | Description |
---|---|---|
ckpt |
dict
|
The loaded model checkpoint. |
file |
str
|
The loaded filename. |
Examples:
>>> from ultralytics.nn.tasks import torch_safe_load
>>> ckpt, file = torch_safe_load("path/to/best.pt", safe_only=True)
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.attempt_load_weights
Load an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
weights
|
str | List[str]
|
Model weights path(s). |
required |
device
|
device
|
Device to load model to. |
None
|
inplace
|
bool
|
Whether to do inplace operations. |
True
|
fuse
|
bool
|
Whether to fuse model. |
False
|
Returns:
Type | Description |
---|---|
Module
|
Loaded model. |
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.attempt_load_one_weight
Load a single model weights.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
weight
|
str
|
Model weight path. |
required |
device
|
device
|
Device to load model to. |
None
|
inplace
|
bool
|
Whether to do inplace operations. |
True
|
fuse
|
bool
|
Whether to fuse model. |
False
|
Returns:
Type | Description |
---|---|
tuple
|
Tuple containing the model and checkpoint. |
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.parse_model
Parse a YOLO model.yaml dictionary into a PyTorch model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
d
|
dict
|
Model dictionary. |
required |
ch
|
int
|
Input channels. |
required |
verbose
|
bool
|
Whether to print model details. |
True
|
Returns:
Type | Description |
---|---|
tuple
|
Tuple containing the PyTorch model and sorted list of output layers. |
Source code in ultralytics/nn/tasks.py
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 1110 1111 1112 1113 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 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 |
|
ultralytics.nn.tasks.yaml_model_load
Load a YOLOv8 model from a YAML file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path
|
str | Path
|
Path to the YAML file. |
required |
Returns:
Type | Description |
---|---|
dict
|
Model dictionary. |
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.guess_model_scale
Extract the size character n, s, m, l, or x of the model's scale from the model path.
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 (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', 'obb'). |
Source code in ultralytics/nn/tasks.py
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 |
|