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.YOLOEModel
Bases: DetectionModel
YOLOE detection model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cfg
|
str | dict
|
Model configuration file path or dictionary. |
'yoloe-v8s.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
get_cls_pe
Get class positional embeddings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tpe
|
Tensor
|
Text positional embeddings. |
required |
vpe
|
Tensor
|
Visual positional embeddings. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
Class positional embeddings. |
Source code in ultralytics/nn/tasks.py
get_text_pe
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. |
False
|
without_reprta
|
bool
|
Whether to return text embeddings cooperated with reprta module. |
False
|
Returns:
Type | Description |
---|---|
Tensor
|
Text positional embeddings. |
Source code in ultralytics/nn/tasks.py
get_visual_pe
Get visual embeddings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
img
|
Tensor
|
Input image tensor. |
required |
visual
|
Tensor
|
Visual features. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
Visual positional embeddings. |
Source code in ultralytics/nn/tasks.py
get_vocab
Get fused vocabulary layer from the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
names
|
list
|
List of class names. |
required |
Returns:
Type | Description |
---|---|
ModuleList
|
List of vocabulary modules. |
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
predict(
x,
profile=False,
visualize=False,
tpe=None,
augment=False,
embed=None,
vpe=None,
return_vpe=False,
)
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
|
tpe
|
Tensor
|
Text positional embeddings. |
None
|
augment
|
bool
|
If True, perform data augmentation during inference. |
False
|
embed
|
list
|
A list of feature vectors/embeddings to return. |
None
|
vpe
|
Tensor
|
Visual positional embeddings. |
None
|
return_vpe
|
bool
|
If True, return visual positional embeddings. |
False
|
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 |
---|---|---|---|
names
|
List[str]
|
List of class names. |
required |
embeddings
|
Tensor
|
Embeddings tensor. |
required |
Source code in ultralytics/nn/tasks.py
set_vocab
Set vocabulary for the prompt-free model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vocab
|
ModuleList
|
List of vocabulary items. |
required |
names
|
List[str]
|
List of class names. |
required |
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.YOLOESegModel
Bases: YOLOEModel
, SegmentationModel
YOLOE segmentation model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cfg
|
str | dict
|
Model configuration file path or dictionary. |
'yoloe-v8s-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
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
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
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 1235 1236 1237 1238 1239 |
|
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
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 |
|
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
1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 |
|