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.
Source code in ultralytics/nn/tasks.py
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 |
|
forward(x, *args, **kwargs)
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(verbose=True)
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(detailed=False, verbose=True, imgsz=640)
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(thresh=10)
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(weights, verbose=True)
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(batch, preds=None)
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(x, profile=False, visualize=False, augment=False, embed=None)
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__(cfg='yolov8n.yaml', ch=3, nc=None, verbose=True)
Initialize the YOLOv8 detection model with the given config and parameters.
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.OBBModel
Bases: DetectionModel
YOLOv8 Oriented Bounding Box (OBB) model.
Source code in ultralytics/nn/tasks.py
__init__(cfg='yolov8n-obb.yaml', ch=3, nc=None, verbose=True)
Initialize YOLOv8 OBB model with given config and parameters.
ultralytics.nn.tasks.SegmentationModel
Bases: DetectionModel
YOLOv8 segmentation model.
Source code in ultralytics/nn/tasks.py
__init__(cfg='yolov8n-seg.yaml', ch=3, nc=None, verbose=True)
Initialize YOLOv8 segmentation model with given config and parameters.
ultralytics.nn.tasks.PoseModel
Bases: DetectionModel
YOLOv8 pose model.
Source code in ultralytics/nn/tasks.py
__init__(cfg='yolov8n-pose.yaml', ch=3, nc=None, data_kpt_shape=(None, None), verbose=True)
Initialize 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__(cfg='yolov8n-cls.yaml', ch=3, nc=None, verbose=True)
Init ClassificationModel with YAML, channels, number of classes, verbose flag.
init_criterion()
reshape_outputs(model, nc)
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. |
Source code in ultralytics/nn/tasks.py
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 |
|
__init__(cfg='rtdetr-l.yaml', ch=3, nc=None, verbose=True)
Initialize the RTDETRDetectionModel.
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(batch, preds=None)
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(x, profile=False, visualize=False, batch=None, augment=False, embed=None)
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
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 |
|
__init__(cfg='yolov8s-world.yaml', ch=3, nc=None, verbose=True)
Initialize YOLOv8 world model with given config and parameters.
Source code in ultralytics/nn/tasks.py
loss(batch, preds=None)
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(x, profile=False, visualize=False, txt_feats=None, augment=False, embed=None)
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(text, batch=80, cache_clip_model=True)
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
__init__()
forward(x, augment=False, profile=False, visualize=False)
Function generates the YOLO network's final layer.
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.temporary_modules(modules=None)
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
|
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(weight)
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(weights, device=None, inplace=True, fuse=False)
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(weight, device=None, inplace=True, fuse=False)
Loads a single model weights.
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.parse_model(d, ch, verbose=True)
Parse a YOLO model.yaml dictionary into a PyTorch model.
Source code in ultralytics/nn/tasks.py
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 868 869 870 871 872 873 874 875 876 877 878 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 |
|
ultralytics.nn.tasks.yaml_model_load(path)
Load a YOLOv8 model from a YAML file.
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.guess_model_scale(model_path)
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(model)
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
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 |
|