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
Base class for all YOLO models in the Ultralytics family.
This class provides common functionality for YOLO models including forward pass handling, model fusion, information display, and weight loading capabilities.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
Module
|
The neural network model. |
save |
list
|
List of layer indices to save outputs from. |
stride |
Tensor
|
Model stride values. |
Methods:
| Name | Description |
|---|---|
forward |
Perform forward pass for training or inference. |
predict |
Perform inference on input tensor. |
fuse |
Fuse Conv2d and BatchNorm2d layers for optimization. |
info |
Print model information. |
load |
Load weights into the model. |
loss |
Compute loss for training. |
Examples:
Create a BaseModel instance
>>> model = BaseModel()
>>> model.info() # Display model information
forward
forward(x, *args, **kwargs)
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
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | |
fuse
fuse(verbose=True)
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
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 | |
info
info(detailed=False, verbose=True, imgsz=640)
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
262 263 264 265 266 267 268 269 270 | |
init_criterion
init_criterion()
Initialize the loss criterion for the BaseModel.
Source code in ultralytics/nn/tasks.py
330 331 332 | |
is_fused
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. |
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
250 251 252 253 254 255 256 257 258 259 260 | |
load
load(weights, verbose=True)
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
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 | |
loss
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
316 317 318 319 320 321 322 323 324 325 326 327 328 | |
predict
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. |
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
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | |
ultralytics.nn.tasks.DetectionModel
DetectionModel(cfg='yolo11n.yaml', ch=3, nc=None, verbose=True)
Bases: BaseModel
YOLO detection model.
This class implements the YOLO detection architecture, handling model initialization, forward pass, augmented inference, and loss computation for object detection tasks.
Attributes:
| Name | Type | Description |
|---|---|---|
yaml |
dict
|
Model configuration dictionary. |
model |
Sequential
|
The neural network model. |
save |
list
|
List of layer indices to save outputs from. |
names |
dict
|
Class names dictionary. |
inplace |
bool
|
Whether to use inplace operations. |
end2end |
bool
|
Whether the model uses end-to-end detection. |
stride |
Tensor
|
Model stride values. |
Methods:
| Name | Description |
|---|---|
_predict_augment |
Perform augmented inference. |
_descale_pred |
De-scale predictions following augmented inference. |
_clip_augmented |
Clip YOLO augmented inference tails. |
init_criterion |
Initialize the loss criterion. |
Examples:
Initialize a detection model
>>> model = DetectionModel("yolo11n.yaml", ch=3, nc=80)
>>> results = model.predict(image_tensor)
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
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 | |
init_criterion
init_criterion()
Initialize the loss criterion for the DetectionModel.
Source code in ultralytics/nn/tasks.py
482 483 484 | |
ultralytics.nn.tasks.OBBModel
OBBModel(cfg='yolo11n-obb.yaml', ch=3, nc=None, verbose=True)
Bases: DetectionModel
YOLO Oriented Bounding Box (OBB) model.
This class extends DetectionModel to handle oriented bounding box detection tasks, providing specialized loss computation for rotated object detection.
Methods:
| Name | Description |
|---|---|
init_criterion |
Initialize the loss criterion for OBB detection. |
Examples:
Initialize an OBB model
>>> model = OBBModel("yolo11n-obb.yaml", ch=3, nc=80)
>>> results = model.predict(image_tensor)
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
503 504 505 506 507 508 509 510 511 512 | |
init_criterion
init_criterion()
Initialize the loss criterion for the model.
Source code in ultralytics/nn/tasks.py
514 515 516 | |
ultralytics.nn.tasks.SegmentationModel
SegmentationModel(cfg='yolo11n-seg.yaml', ch=3, nc=None, verbose=True)
Bases: DetectionModel
YOLO segmentation model.
This class extends DetectionModel to handle instance segmentation tasks, providing specialized loss computation for pixel-level object detection and segmentation.
Methods:
| Name | Description |
|---|---|
init_criterion |
Initialize the loss criterion for segmentation. |
Examples:
Initialize a segmentation model
>>> model = SegmentationModel("yolo11n-seg.yaml", ch=3, nc=80)
>>> results = model.predict(image_tensor)
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
535 536 537 538 539 540 541 542 543 544 | |
init_criterion
init_criterion()
Initialize the loss criterion for the SegmentationModel.
Source code in ultralytics/nn/tasks.py
546 547 548 | |
ultralytics.nn.tasks.PoseModel
PoseModel(
cfg="yolo11n-pose.yaml",
ch=3,
nc=None,
data_kpt_shape=(None, None),
verbose=True,
)
Bases: DetectionModel
YOLO pose model.
This class extends DetectionModel to handle human pose estimation tasks, providing specialized loss computation for keypoint detection and pose estimation.
Attributes:
| Name | Type | Description |
|---|---|---|
kpt_shape |
tuple
|
Shape of keypoints data (num_keypoints, num_dimensions). |
Methods:
| Name | Description |
|---|---|
init_criterion |
Initialize the loss criterion for pose estimation. |
Examples:
Initialize a pose model
>>> model = PoseModel("yolo11n-pose.yaml", ch=3, nc=1, data_kpt_shape=(17, 3))
>>> results = model.predict(image_tensor)
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
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 | |
init_criterion
init_criterion()
Initialize the loss criterion for the PoseModel.
Source code in ultralytics/nn/tasks.py
587 588 589 | |
ultralytics.nn.tasks.ClassificationModel
ClassificationModel(cfg='yolo11n-cls.yaml', ch=3, nc=None, verbose=True)
Bases: BaseModel
YOLO classification model.
This class implements the YOLO classification architecture for image classification tasks, providing model initialization, configuration, and output reshaping capabilities.
Attributes:
| Name | Type | Description |
|---|---|---|
yaml |
dict
|
Model configuration dictionary. |
model |
Sequential
|
The neural network model. |
stride |
Tensor
|
Model stride values. |
names |
dict
|
Class names dictionary. |
Methods:
| Name | Description |
|---|---|
_from_yaml |
Set model configurations and define architecture. |
reshape_outputs |
Update model to specified class count. |
init_criterion |
Initialize the loss criterion. |
Examples:
Initialize a classification model
>>> model = ClassificationModel("yolo11n-cls.yaml", ch=3, nc=1000)
>>> results = model.predict(image_tensor)
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
616 617 618 619 620 621 622 623 624 625 626 | |
init_criterion
init_criterion()
Initialize the loss criterion for the ClassificationModel.
Source code in ultralytics/nn/tasks.py
679 680 681 | |
reshape_outputs
staticmethod
reshape_outputs(model, nc)
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
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 | |
ultralytics.nn.tasks.RTDETRDetectionModel
RTDETRDetectionModel(cfg='rtdetr-l.yaml', ch=3, nc=None, verbose=True)
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 |
|---|---|---|
nc |
int
|
Number of classes for detection. |
criterion |
RTDETRDetectionLoss
|
Loss function for training. |
Methods:
| Name | Description |
|---|---|
init_criterion |
Initialize the loss criterion. |
loss |
Compute loss for training. |
predict |
Perform forward pass through the model. |
Examples:
Initialize an RTDETR model
>>> model = RTDETRDetectionModel("rtdetr-l.yaml", ch=3, nc=80)
>>> results = model.predict(image_tensor)
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
707 708 709 710 711 712 713 714 715 716 | |
init_criterion
init_criterion()
Initialize the loss criterion for the RTDETRDetectionModel.
Source code in ultralytics/nn/tasks.py
733 734 735 736 737 | |
loss
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. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
loss_sum |
Tensor
|
Total loss value. |
loss_items |
Tensor
|
Main three losses in a tensor. |
Source code in ultralytics/nn/tasks.py
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 | |
predict
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. |
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
785 786 787 788 789 790 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 | |
ultralytics.nn.tasks.WorldModel
WorldModel(cfg='yolov8s-world.yaml', ch=3, nc=None, verbose=True)
Bases: DetectionModel
YOLOv8 World Model.
This class implements the YOLOv8 World model for open-vocabulary object detection, supporting text-based class specification and CLIP model integration for zero-shot detection capabilities.
Attributes:
| Name | Type | Description |
|---|---|---|
txt_feats |
Tensor
|
Text feature embeddings for classes. |
clip_model |
Module
|
CLIP model for text encoding. |
Methods:
| Name | Description |
|---|---|
set_classes |
Set classes for offline inference. |
get_text_pe |
Get text positional embeddings. |
predict |
Perform forward pass with text features. |
loss |
Compute loss with text features. |
Examples:
Initialize a world model
>>> model = WorldModel("yolov8s-world.yaml", ch=3, nc=80)
>>> model.set_classes(["person", "car", "bicycle"])
>>> results = model.predict(image_tensor)
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
844 845 846 847 848 849 850 851 852 853 854 855 | |
get_text_pe
get_text_pe(text, batch=80, cache_clip_model=True)
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
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Text positional embeddings. |
Source code in ultralytics/nn/tasks.py
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 | |
loss
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
935 936 937 938 939 940 941 942 943 944 945 946 947 | |
predict
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. |
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
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 | |
set_classes
set_classes(text, batch=80, cache_clip_model=True)
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
857 858 859 860 861 862 863 864 865 866 | |
ultralytics.nn.tasks.YOLOEModel
YOLOEModel(cfg='yoloe-v8s.yaml', ch=3, nc=None, verbose=True)
Bases: DetectionModel
YOLOE detection model.
This class implements the YOLOE architecture for efficient object detection with text and visual prompts, supporting both prompt-based and prompt-free inference modes.
Attributes:
| Name | Type | Description |
|---|---|---|
pe |
Tensor
|
Prompt embeddings for classes. |
clip_model |
Module
|
CLIP model for text encoding. |
Methods:
| Name | Description |
|---|---|
get_text_pe |
Get text positional embeddings. |
get_visual_pe |
Get visual embeddings. |
set_vocab |
Set vocabulary for prompt-free model. |
get_vocab |
Get fused vocabulary layer. |
set_classes |
Set classes for offline inference. |
get_cls_pe |
Get class positional embeddings. |
predict |
Perform forward pass with prompts. |
loss |
Compute loss with prompts. |
Examples:
Initialize a YOLOE model
>>> model = YOLOEModel("yoloe-v8s.yaml", ch=3, nc=80)
>>> results = model.predict(image_tensor, tpe=text_embeddings)
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
977 978 979 980 981 982 983 984 985 986 | |
get_cls_pe
get_cls_pe(tpe, vpe)
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
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 | |
get_text_pe
get_text_pe(text, batch=80, cache_clip_model=False, without_reprta=False)
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
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 | |
get_visual_pe
get_visual_pe(img, visual)
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
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 | |
get_vocab
get_vocab(names)
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
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 | |
loss
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
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 | |
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
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 | |
set_classes
set_classes(names, embeddings)
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
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 | |
set_vocab
set_vocab(vocab, names)
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
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 | |
ultralytics.nn.tasks.YOLOESegModel
YOLOESegModel(cfg='yoloe-v8s-seg.yaml', ch=3, nc=None, verbose=True)
Bases: YOLOEModel, SegmentationModel
YOLOE segmentation model.
This class extends YOLOEModel to handle instance segmentation tasks with text and visual prompts, providing specialized loss computation for pixel-level object detection and segmentation.
Methods:
| Name | Description |
|---|---|
loss |
Compute loss with prompts for segmentation. |
Examples:
Initialize a YOLOE segmentation model
>>> model = YOLOESegModel("yoloe-v8s-seg.yaml", ch=3, nc=80)
>>> results = model.predict(image_tensor, tpe=text_embeddings)
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
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 | |
loss
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
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 | |
ultralytics.nn.tasks.Ensemble
Ensemble()
Bases: ModuleList
Ensemble of models.
This class allows combining multiple YOLO models into an ensemble for improved performance through model averaging or other ensemble techniques.
Methods:
| Name | Description |
|---|---|
forward |
Generate predictions from all models in the ensemble. |
Examples:
Create an ensemble of models
>>> ensemble = Ensemble()
>>> ensemble.append(model1)
>>> ensemble.append(model2)
>>> results = ensemble(image_tensor)
Source code in ultralytics/nn/tasks.py
1252 1253 1254 | |
forward
forward(x, augment=False, profile=False, visualize=False)
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:
| Name | Type | Description |
|---|---|---|
y |
Tensor
|
Concatenated predictions from all models. |
train_out |
None
|
Always None for ensemble inference. |
Source code in ultralytics/nn/tasks.py
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 | |
ultralytics.nn.tasks.SafeClass
SafeClass(*args, **kwargs)
A placeholder class to replace unknown classes during unpickling.
Source code in ultralytics/nn/tasks.py
1330 1331 1332 | |
__call__
__call__(*args, **kwargs)
Run SafeClass instance, ignoring all arguments.
Source code in ultralytics/nn/tasks.py
1334 1335 1336 | |
ultralytics.nn.tasks.SafeUnpickler
Bases: Unpickler
Custom Unpickler that replaces unknown classes with SafeClass.
find_class
find_class(module, name)
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
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 | |
ultralytics.nn.tasks.temporary_modules
temporary_modules(modules=None, attributes=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
|
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
Notes
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
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 | |
ultralytics.nn.tasks.torch_safe_load
torch_safe_load(weight, safe_only=False)
Attempt 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
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 | |
ultralytics.nn.tasks.load_checkpoint
load_checkpoint(weight, device=None, inplace=True, fuse=False)
Load a single model weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight
|
str | Path
|
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:
| Name | Type | Description |
|---|---|---|
model |
Module
|
Loaded model. |
ckpt |
dict
|
Model checkpoint dictionary. |
Source code in ultralytics/nn/tasks.py
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 | |
ultralytics.nn.tasks.parse_model
parse_model(d, ch, verbose=True)
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:
| Name | Type | Description |
|---|---|---|
model |
Sequential
|
PyTorch model. |
save |
list
|
Sorted list of output layers. |
Source code in ultralytics/nn/tasks.py
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 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 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 | |
ultralytics.nn.tasks.yaml_model_load
yaml_model_load(path)
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
1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 | |
ultralytics.nn.tasks.guess_model_scale
guess_model_scale(model_path)
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
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 | |
ultralytics.nn.tasks.guess_model_task
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', 'obb'). |
Source code in ultralytics/nn/tasks.py
1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 | |