ultralytics-opencv-headless 8.3.242__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (298) hide show
  1. tests/__init__.py +23 -0
  2. tests/conftest.py +59 -0
  3. tests/test_cli.py +131 -0
  4. tests/test_cuda.py +216 -0
  5. tests/test_engine.py +157 -0
  6. tests/test_exports.py +309 -0
  7. tests/test_integrations.py +151 -0
  8. tests/test_python.py +777 -0
  9. tests/test_solutions.py +371 -0
  10. ultralytics/__init__.py +48 -0
  11. ultralytics/assets/bus.jpg +0 -0
  12. ultralytics/assets/zidane.jpg +0 -0
  13. ultralytics/cfg/__init__.py +1026 -0
  14. ultralytics/cfg/datasets/Argoverse.yaml +78 -0
  15. ultralytics/cfg/datasets/DOTAv1.5.yaml +37 -0
  16. ultralytics/cfg/datasets/DOTAv1.yaml +36 -0
  17. ultralytics/cfg/datasets/GlobalWheat2020.yaml +68 -0
  18. ultralytics/cfg/datasets/HomeObjects-3K.yaml +32 -0
  19. ultralytics/cfg/datasets/ImageNet.yaml +2025 -0
  20. ultralytics/cfg/datasets/Objects365.yaml +447 -0
  21. ultralytics/cfg/datasets/SKU-110K.yaml +58 -0
  22. ultralytics/cfg/datasets/VOC.yaml +102 -0
  23. ultralytics/cfg/datasets/VisDrone.yaml +87 -0
  24. ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
  25. ultralytics/cfg/datasets/brain-tumor.yaml +22 -0
  26. ultralytics/cfg/datasets/carparts-seg.yaml +44 -0
  27. ultralytics/cfg/datasets/coco-pose.yaml +64 -0
  28. ultralytics/cfg/datasets/coco.yaml +118 -0
  29. ultralytics/cfg/datasets/coco128-seg.yaml +101 -0
  30. ultralytics/cfg/datasets/coco128.yaml +101 -0
  31. ultralytics/cfg/datasets/coco8-grayscale.yaml +103 -0
  32. ultralytics/cfg/datasets/coco8-multispectral.yaml +104 -0
  33. ultralytics/cfg/datasets/coco8-pose.yaml +47 -0
  34. ultralytics/cfg/datasets/coco8-seg.yaml +101 -0
  35. ultralytics/cfg/datasets/coco8.yaml +101 -0
  36. ultralytics/cfg/datasets/construction-ppe.yaml +32 -0
  37. ultralytics/cfg/datasets/crack-seg.yaml +22 -0
  38. ultralytics/cfg/datasets/dog-pose.yaml +52 -0
  39. ultralytics/cfg/datasets/dota8-multispectral.yaml +38 -0
  40. ultralytics/cfg/datasets/dota8.yaml +35 -0
  41. ultralytics/cfg/datasets/hand-keypoints.yaml +50 -0
  42. ultralytics/cfg/datasets/kitti.yaml +27 -0
  43. ultralytics/cfg/datasets/lvis.yaml +1240 -0
  44. ultralytics/cfg/datasets/medical-pills.yaml +21 -0
  45. ultralytics/cfg/datasets/open-images-v7.yaml +663 -0
  46. ultralytics/cfg/datasets/package-seg.yaml +22 -0
  47. ultralytics/cfg/datasets/signature.yaml +21 -0
  48. ultralytics/cfg/datasets/tiger-pose.yaml +41 -0
  49. ultralytics/cfg/datasets/xView.yaml +155 -0
  50. ultralytics/cfg/default.yaml +130 -0
  51. ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +17 -0
  52. ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
  53. ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
  54. ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
  55. ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
  56. ultralytics/cfg/models/11/yolo11.yaml +50 -0
  57. ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
  58. ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
  59. ultralytics/cfg/models/12/yolo12-cls.yaml +32 -0
  60. ultralytics/cfg/models/12/yolo12-obb.yaml +48 -0
  61. ultralytics/cfg/models/12/yolo12-pose.yaml +49 -0
  62. ultralytics/cfg/models/12/yolo12-seg.yaml +48 -0
  63. ultralytics/cfg/models/12/yolo12.yaml +48 -0
  64. ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +53 -0
  65. ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +45 -0
  66. ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +45 -0
  67. ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +57 -0
  68. ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
  69. ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
  70. ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
  71. ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
  72. ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
  73. ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
  74. ultralytics/cfg/models/v3/yolov3-spp.yaml +49 -0
  75. ultralytics/cfg/models/v3/yolov3-tiny.yaml +40 -0
  76. ultralytics/cfg/models/v3/yolov3.yaml +49 -0
  77. ultralytics/cfg/models/v5/yolov5-p6.yaml +62 -0
  78. ultralytics/cfg/models/v5/yolov5.yaml +51 -0
  79. ultralytics/cfg/models/v6/yolov6.yaml +56 -0
  80. ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +48 -0
  81. ultralytics/cfg/models/v8/yoloe-v8.yaml +48 -0
  82. ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +28 -0
  83. ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +28 -0
  84. ultralytics/cfg/models/v8/yolov8-cls.yaml +32 -0
  85. ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +58 -0
  86. ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +60 -0
  87. ultralytics/cfg/models/v8/yolov8-ghost.yaml +50 -0
  88. ultralytics/cfg/models/v8/yolov8-obb.yaml +49 -0
  89. ultralytics/cfg/models/v8/yolov8-p2.yaml +57 -0
  90. ultralytics/cfg/models/v8/yolov8-p6.yaml +59 -0
  91. ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +60 -0
  92. ultralytics/cfg/models/v8/yolov8-pose.yaml +50 -0
  93. ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +49 -0
  94. ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +59 -0
  95. ultralytics/cfg/models/v8/yolov8-seg.yaml +49 -0
  96. ultralytics/cfg/models/v8/yolov8-world.yaml +51 -0
  97. ultralytics/cfg/models/v8/yolov8-worldv2.yaml +49 -0
  98. ultralytics/cfg/models/v8/yolov8.yaml +49 -0
  99. ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
  100. ultralytics/cfg/models/v9/yolov9c.yaml +41 -0
  101. ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
  102. ultralytics/cfg/models/v9/yolov9e.yaml +64 -0
  103. ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
  104. ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
  105. ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
  106. ultralytics/cfg/trackers/botsort.yaml +21 -0
  107. ultralytics/cfg/trackers/bytetrack.yaml +12 -0
  108. ultralytics/data/__init__.py +26 -0
  109. ultralytics/data/annotator.py +66 -0
  110. ultralytics/data/augment.py +2801 -0
  111. ultralytics/data/base.py +435 -0
  112. ultralytics/data/build.py +437 -0
  113. ultralytics/data/converter.py +855 -0
  114. ultralytics/data/dataset.py +834 -0
  115. ultralytics/data/loaders.py +704 -0
  116. ultralytics/data/scripts/download_weights.sh +18 -0
  117. ultralytics/data/scripts/get_coco.sh +61 -0
  118. ultralytics/data/scripts/get_coco128.sh +18 -0
  119. ultralytics/data/scripts/get_imagenet.sh +52 -0
  120. ultralytics/data/split.py +138 -0
  121. ultralytics/data/split_dota.py +344 -0
  122. ultralytics/data/utils.py +798 -0
  123. ultralytics/engine/__init__.py +1 -0
  124. ultralytics/engine/exporter.py +1574 -0
  125. ultralytics/engine/model.py +1124 -0
  126. ultralytics/engine/predictor.py +508 -0
  127. ultralytics/engine/results.py +1522 -0
  128. ultralytics/engine/trainer.py +974 -0
  129. ultralytics/engine/tuner.py +448 -0
  130. ultralytics/engine/validator.py +384 -0
  131. ultralytics/hub/__init__.py +166 -0
  132. ultralytics/hub/auth.py +151 -0
  133. ultralytics/hub/google/__init__.py +174 -0
  134. ultralytics/hub/session.py +422 -0
  135. ultralytics/hub/utils.py +162 -0
  136. ultralytics/models/__init__.py +9 -0
  137. ultralytics/models/fastsam/__init__.py +7 -0
  138. ultralytics/models/fastsam/model.py +79 -0
  139. ultralytics/models/fastsam/predict.py +169 -0
  140. ultralytics/models/fastsam/utils.py +23 -0
  141. ultralytics/models/fastsam/val.py +38 -0
  142. ultralytics/models/nas/__init__.py +7 -0
  143. ultralytics/models/nas/model.py +98 -0
  144. ultralytics/models/nas/predict.py +56 -0
  145. ultralytics/models/nas/val.py +38 -0
  146. ultralytics/models/rtdetr/__init__.py +7 -0
  147. ultralytics/models/rtdetr/model.py +63 -0
  148. ultralytics/models/rtdetr/predict.py +88 -0
  149. ultralytics/models/rtdetr/train.py +89 -0
  150. ultralytics/models/rtdetr/val.py +216 -0
  151. ultralytics/models/sam/__init__.py +25 -0
  152. ultralytics/models/sam/amg.py +275 -0
  153. ultralytics/models/sam/build.py +365 -0
  154. ultralytics/models/sam/build_sam3.py +377 -0
  155. ultralytics/models/sam/model.py +169 -0
  156. ultralytics/models/sam/modules/__init__.py +1 -0
  157. ultralytics/models/sam/modules/blocks.py +1067 -0
  158. ultralytics/models/sam/modules/decoders.py +495 -0
  159. ultralytics/models/sam/modules/encoders.py +794 -0
  160. ultralytics/models/sam/modules/memory_attention.py +298 -0
  161. ultralytics/models/sam/modules/sam.py +1160 -0
  162. ultralytics/models/sam/modules/tiny_encoder.py +979 -0
  163. ultralytics/models/sam/modules/transformer.py +344 -0
  164. ultralytics/models/sam/modules/utils.py +512 -0
  165. ultralytics/models/sam/predict.py +3940 -0
  166. ultralytics/models/sam/sam3/__init__.py +3 -0
  167. ultralytics/models/sam/sam3/decoder.py +546 -0
  168. ultralytics/models/sam/sam3/encoder.py +529 -0
  169. ultralytics/models/sam/sam3/geometry_encoders.py +415 -0
  170. ultralytics/models/sam/sam3/maskformer_segmentation.py +286 -0
  171. ultralytics/models/sam/sam3/model_misc.py +199 -0
  172. ultralytics/models/sam/sam3/necks.py +129 -0
  173. ultralytics/models/sam/sam3/sam3_image.py +339 -0
  174. ultralytics/models/sam/sam3/text_encoder_ve.py +307 -0
  175. ultralytics/models/sam/sam3/vitdet.py +547 -0
  176. ultralytics/models/sam/sam3/vl_combiner.py +160 -0
  177. ultralytics/models/utils/__init__.py +1 -0
  178. ultralytics/models/utils/loss.py +466 -0
  179. ultralytics/models/utils/ops.py +315 -0
  180. ultralytics/models/yolo/__init__.py +7 -0
  181. ultralytics/models/yolo/classify/__init__.py +7 -0
  182. ultralytics/models/yolo/classify/predict.py +90 -0
  183. ultralytics/models/yolo/classify/train.py +202 -0
  184. ultralytics/models/yolo/classify/val.py +216 -0
  185. ultralytics/models/yolo/detect/__init__.py +7 -0
  186. ultralytics/models/yolo/detect/predict.py +122 -0
  187. ultralytics/models/yolo/detect/train.py +227 -0
  188. ultralytics/models/yolo/detect/val.py +507 -0
  189. ultralytics/models/yolo/model.py +430 -0
  190. ultralytics/models/yolo/obb/__init__.py +7 -0
  191. ultralytics/models/yolo/obb/predict.py +56 -0
  192. ultralytics/models/yolo/obb/train.py +79 -0
  193. ultralytics/models/yolo/obb/val.py +302 -0
  194. ultralytics/models/yolo/pose/__init__.py +7 -0
  195. ultralytics/models/yolo/pose/predict.py +65 -0
  196. ultralytics/models/yolo/pose/train.py +110 -0
  197. ultralytics/models/yolo/pose/val.py +248 -0
  198. ultralytics/models/yolo/segment/__init__.py +7 -0
  199. ultralytics/models/yolo/segment/predict.py +109 -0
  200. ultralytics/models/yolo/segment/train.py +69 -0
  201. ultralytics/models/yolo/segment/val.py +307 -0
  202. ultralytics/models/yolo/world/__init__.py +5 -0
  203. ultralytics/models/yolo/world/train.py +173 -0
  204. ultralytics/models/yolo/world/train_world.py +178 -0
  205. ultralytics/models/yolo/yoloe/__init__.py +22 -0
  206. ultralytics/models/yolo/yoloe/predict.py +162 -0
  207. ultralytics/models/yolo/yoloe/train.py +287 -0
  208. ultralytics/models/yolo/yoloe/train_seg.py +122 -0
  209. ultralytics/models/yolo/yoloe/val.py +206 -0
  210. ultralytics/nn/__init__.py +27 -0
  211. ultralytics/nn/autobackend.py +958 -0
  212. ultralytics/nn/modules/__init__.py +182 -0
  213. ultralytics/nn/modules/activation.py +54 -0
  214. ultralytics/nn/modules/block.py +1947 -0
  215. ultralytics/nn/modules/conv.py +669 -0
  216. ultralytics/nn/modules/head.py +1183 -0
  217. ultralytics/nn/modules/transformer.py +793 -0
  218. ultralytics/nn/modules/utils.py +159 -0
  219. ultralytics/nn/tasks.py +1768 -0
  220. ultralytics/nn/text_model.py +356 -0
  221. ultralytics/py.typed +1 -0
  222. ultralytics/solutions/__init__.py +41 -0
  223. ultralytics/solutions/ai_gym.py +108 -0
  224. ultralytics/solutions/analytics.py +264 -0
  225. ultralytics/solutions/config.py +107 -0
  226. ultralytics/solutions/distance_calculation.py +123 -0
  227. ultralytics/solutions/heatmap.py +125 -0
  228. ultralytics/solutions/instance_segmentation.py +86 -0
  229. ultralytics/solutions/object_blurrer.py +89 -0
  230. ultralytics/solutions/object_counter.py +190 -0
  231. ultralytics/solutions/object_cropper.py +87 -0
  232. ultralytics/solutions/parking_management.py +280 -0
  233. ultralytics/solutions/queue_management.py +93 -0
  234. ultralytics/solutions/region_counter.py +133 -0
  235. ultralytics/solutions/security_alarm.py +151 -0
  236. ultralytics/solutions/similarity_search.py +219 -0
  237. ultralytics/solutions/solutions.py +828 -0
  238. ultralytics/solutions/speed_estimation.py +114 -0
  239. ultralytics/solutions/streamlit_inference.py +260 -0
  240. ultralytics/solutions/templates/similarity-search.html +156 -0
  241. ultralytics/solutions/trackzone.py +88 -0
  242. ultralytics/solutions/vision_eye.py +67 -0
  243. ultralytics/trackers/__init__.py +7 -0
  244. ultralytics/trackers/basetrack.py +115 -0
  245. ultralytics/trackers/bot_sort.py +257 -0
  246. ultralytics/trackers/byte_tracker.py +469 -0
  247. ultralytics/trackers/track.py +116 -0
  248. ultralytics/trackers/utils/__init__.py +1 -0
  249. ultralytics/trackers/utils/gmc.py +339 -0
  250. ultralytics/trackers/utils/kalman_filter.py +482 -0
  251. ultralytics/trackers/utils/matching.py +154 -0
  252. ultralytics/utils/__init__.py +1450 -0
  253. ultralytics/utils/autobatch.py +118 -0
  254. ultralytics/utils/autodevice.py +205 -0
  255. ultralytics/utils/benchmarks.py +728 -0
  256. ultralytics/utils/callbacks/__init__.py +5 -0
  257. ultralytics/utils/callbacks/base.py +233 -0
  258. ultralytics/utils/callbacks/clearml.py +146 -0
  259. ultralytics/utils/callbacks/comet.py +625 -0
  260. ultralytics/utils/callbacks/dvc.py +197 -0
  261. ultralytics/utils/callbacks/hub.py +110 -0
  262. ultralytics/utils/callbacks/mlflow.py +134 -0
  263. ultralytics/utils/callbacks/neptune.py +126 -0
  264. ultralytics/utils/callbacks/platform.py +73 -0
  265. ultralytics/utils/callbacks/raytune.py +42 -0
  266. ultralytics/utils/callbacks/tensorboard.py +123 -0
  267. ultralytics/utils/callbacks/wb.py +188 -0
  268. ultralytics/utils/checks.py +998 -0
  269. ultralytics/utils/cpu.py +85 -0
  270. ultralytics/utils/dist.py +123 -0
  271. ultralytics/utils/downloads.py +529 -0
  272. ultralytics/utils/errors.py +35 -0
  273. ultralytics/utils/events.py +113 -0
  274. ultralytics/utils/export/__init__.py +7 -0
  275. ultralytics/utils/export/engine.py +237 -0
  276. ultralytics/utils/export/imx.py +315 -0
  277. ultralytics/utils/export/tensorflow.py +231 -0
  278. ultralytics/utils/files.py +219 -0
  279. ultralytics/utils/git.py +137 -0
  280. ultralytics/utils/instance.py +484 -0
  281. ultralytics/utils/logger.py +444 -0
  282. ultralytics/utils/loss.py +849 -0
  283. ultralytics/utils/metrics.py +1560 -0
  284. ultralytics/utils/nms.py +337 -0
  285. ultralytics/utils/ops.py +664 -0
  286. ultralytics/utils/patches.py +201 -0
  287. ultralytics/utils/plotting.py +1045 -0
  288. ultralytics/utils/tal.py +403 -0
  289. ultralytics/utils/torch_utils.py +984 -0
  290. ultralytics/utils/tqdm.py +440 -0
  291. ultralytics/utils/triton.py +112 -0
  292. ultralytics/utils/tuner.py +160 -0
  293. ultralytics_opencv_headless-8.3.242.dist-info/METADATA +374 -0
  294. ultralytics_opencv_headless-8.3.242.dist-info/RECORD +298 -0
  295. ultralytics_opencv_headless-8.3.242.dist-info/WHEEL +5 -0
  296. ultralytics_opencv_headless-8.3.242.dist-info/entry_points.txt +3 -0
  297. ultralytics_opencv_headless-8.3.242.dist-info/licenses/LICENSE +661 -0
  298. ultralytics_opencv_headless-8.3.242.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1183 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+ """Model head modules."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import copy
7
+ import math
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+ from torch.nn.init import constant_, xavier_uniform_
13
+
14
+ from ultralytics.utils import NOT_MACOS14
15
+ from ultralytics.utils.tal import dist2bbox, dist2rbox, make_anchors
16
+ from ultralytics.utils.torch_utils import TORCH_1_11, fuse_conv_and_bn, smart_inference_mode
17
+
18
+ from .block import DFL, SAVPE, BNContrastiveHead, ContrastiveHead, Proto, Residual, SwiGLUFFN
19
+ from .conv import Conv, DWConv
20
+ from .transformer import MLP, DeformableTransformerDecoder, DeformableTransformerDecoderLayer
21
+ from .utils import bias_init_with_prob, linear_init
22
+
23
+ __all__ = "OBB", "Classify", "Detect", "Pose", "RTDETRDecoder", "Segment", "YOLOEDetect", "YOLOESegment", "v10Detect"
24
+
25
+
26
+ class Detect(nn.Module):
27
+ """YOLO Detect head for object detection models.
28
+
29
+ This class implements the detection head used in YOLO models for predicting bounding boxes and class probabilities.
30
+ It supports both training and inference modes, with optional end-to-end detection capabilities.
31
+
32
+ Attributes:
33
+ dynamic (bool): Force grid reconstruction.
34
+ export (bool): Export mode flag.
35
+ format (str): Export format.
36
+ end2end (bool): End-to-end detection mode.
37
+ max_det (int): Maximum detections per image.
38
+ shape (tuple): Input shape.
39
+ anchors (torch.Tensor): Anchor points.
40
+ strides (torch.Tensor): Feature map strides.
41
+ legacy (bool): Backward compatibility for v3/v5/v8/v9 models.
42
+ xyxy (bool): Output format, xyxy or xywh.
43
+ nc (int): Number of classes.
44
+ nl (int): Number of detection layers.
45
+ reg_max (int): DFL channels.
46
+ no (int): Number of outputs per anchor.
47
+ stride (torch.Tensor): Strides computed during build.
48
+ cv2 (nn.ModuleList): Convolution layers for box regression.
49
+ cv3 (nn.ModuleList): Convolution layers for classification.
50
+ dfl (nn.Module): Distribution Focal Loss layer.
51
+ one2one_cv2 (nn.ModuleList): One-to-one convolution layers for box regression.
52
+ one2one_cv3 (nn.ModuleList): One-to-one convolution layers for classification.
53
+
54
+ Methods:
55
+ forward: Perform forward pass and return predictions.
56
+ forward_end2end: Perform forward pass for end-to-end detection.
57
+ bias_init: Initialize detection head biases.
58
+ decode_bboxes: Decode bounding boxes from predictions.
59
+ postprocess: Post-process model predictions.
60
+
61
+ Examples:
62
+ Create a detection head for 80 classes
63
+ >>> detect = Detect(nc=80, ch=(256, 512, 1024))
64
+ >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)]
65
+ >>> outputs = detect(x)
66
+ """
67
+
68
+ dynamic = False # force grid reconstruction
69
+ export = False # export mode
70
+ format = None # export format
71
+ end2end = False # end2end
72
+ max_det = 300 # max_det
73
+ shape = None
74
+ anchors = torch.empty(0) # init
75
+ strides = torch.empty(0) # init
76
+ legacy = False # backward compatibility for v3/v5/v8/v9 models
77
+ xyxy = False # xyxy or xywh output
78
+
79
+ def __init__(self, nc: int = 80, ch: tuple = ()):
80
+ """Initialize the YOLO detection layer with specified number of classes and channels.
81
+
82
+ Args:
83
+ nc (int): Number of classes.
84
+ ch (tuple): Tuple of channel sizes from backbone feature maps.
85
+ """
86
+ super().__init__()
87
+ self.nc = nc # number of classes
88
+ self.nl = len(ch) # number of detection layers
89
+ self.reg_max = 16 # DFL channels (ch[0] // 16 to scale 4/8/12/16/20 for n/s/m/l/x)
90
+ self.no = nc + self.reg_max * 4 # number of outputs per anchor
91
+ self.stride = torch.zeros(self.nl) # strides computed during build
92
+ c2, c3 = max((16, ch[0] // 4, self.reg_max * 4)), max(ch[0], min(self.nc, 100)) # channels
93
+ self.cv2 = nn.ModuleList(
94
+ nn.Sequential(Conv(x, c2, 3), Conv(c2, c2, 3), nn.Conv2d(c2, 4 * self.reg_max, 1)) for x in ch
95
+ )
96
+ self.cv3 = (
97
+ nn.ModuleList(nn.Sequential(Conv(x, c3, 3), Conv(c3, c3, 3), nn.Conv2d(c3, self.nc, 1)) for x in ch)
98
+ if self.legacy
99
+ else nn.ModuleList(
100
+ nn.Sequential(
101
+ nn.Sequential(DWConv(x, x, 3), Conv(x, c3, 1)),
102
+ nn.Sequential(DWConv(c3, c3, 3), Conv(c3, c3, 1)),
103
+ nn.Conv2d(c3, self.nc, 1),
104
+ )
105
+ for x in ch
106
+ )
107
+ )
108
+ self.dfl = DFL(self.reg_max) if self.reg_max > 1 else nn.Identity()
109
+
110
+ if self.end2end:
111
+ self.one2one_cv2 = copy.deepcopy(self.cv2)
112
+ self.one2one_cv3 = copy.deepcopy(self.cv3)
113
+
114
+ def forward(self, x: list[torch.Tensor]) -> list[torch.Tensor] | tuple:
115
+ """Concatenate and return predicted bounding boxes and class probabilities."""
116
+ if self.end2end:
117
+ return self.forward_end2end(x)
118
+
119
+ for i in range(self.nl):
120
+ x[i] = torch.cat((self.cv2[i](x[i]), self.cv3[i](x[i])), 1)
121
+ if self.training: # Training path
122
+ return x
123
+ y = self._inference(x)
124
+ return y if self.export else (y, x)
125
+
126
+ def forward_end2end(self, x: list[torch.Tensor]) -> dict | tuple:
127
+ """Perform forward pass of the v10Detect module.
128
+
129
+ Args:
130
+ x (list[torch.Tensor]): Input feature maps from different levels.
131
+
132
+ Returns:
133
+ outputs (dict | tuple): Training mode returns dict with one2many and one2one outputs. Inference mode returns
134
+ processed detections or tuple with detections and raw outputs.
135
+ """
136
+ x_detach = [xi.detach() for xi in x]
137
+ one2one = [
138
+ torch.cat((self.one2one_cv2[i](x_detach[i]), self.one2one_cv3[i](x_detach[i])), 1) for i in range(self.nl)
139
+ ]
140
+ for i in range(self.nl):
141
+ x[i] = torch.cat((self.cv2[i](x[i]), self.cv3[i](x[i])), 1)
142
+ if self.training: # Training path
143
+ return {"one2many": x, "one2one": one2one}
144
+
145
+ y = self._inference(one2one)
146
+ y = self.postprocess(y.permute(0, 2, 1), self.max_det, self.nc)
147
+ return y if self.export else (y, {"one2many": x, "one2one": one2one})
148
+
149
+ def _inference(self, x: list[torch.Tensor]) -> torch.Tensor:
150
+ """Decode predicted bounding boxes and class probabilities based on multiple-level feature maps.
151
+
152
+ Args:
153
+ x (list[torch.Tensor]): List of feature maps from different detection layers.
154
+
155
+ Returns:
156
+ (torch.Tensor): Concatenated tensor of decoded bounding boxes and class probabilities.
157
+ """
158
+ # Inference path
159
+ shape = x[0].shape # BCHW
160
+ x_cat = torch.cat([xi.view(shape[0], self.no, -1) for xi in x], 2)
161
+ if self.dynamic or self.shape != shape:
162
+ self.anchors, self.strides = (x.transpose(0, 1) for x in make_anchors(x, self.stride, 0.5))
163
+ self.shape = shape
164
+
165
+ box, cls = x_cat.split((self.reg_max * 4, self.nc), 1)
166
+ dbox = self.decode_bboxes(self.dfl(box), self.anchors.unsqueeze(0)) * self.strides
167
+ return torch.cat((dbox, cls.sigmoid()), 1)
168
+
169
+ def bias_init(self):
170
+ """Initialize Detect() biases, WARNING: requires stride availability."""
171
+ m = self # self.model[-1] # Detect() module
172
+ # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1
173
+ # ncf = math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # nominal class frequency
174
+ for a, b, s in zip(m.cv2, m.cv3, m.stride): # from
175
+ a[-1].bias.data[:] = 1.0 # box
176
+ b[-1].bias.data[: m.nc] = math.log(5 / m.nc / (640 / s) ** 2) # cls (.01 objects, 80 classes, 640 img)
177
+ if self.end2end:
178
+ for a, b, s in zip(m.one2one_cv2, m.one2one_cv3, m.stride): # from
179
+ a[-1].bias.data[:] = 1.0 # box
180
+ b[-1].bias.data[: m.nc] = math.log(5 / m.nc / (640 / s) ** 2) # cls (.01 objects, 80 classes, 640 img)
181
+
182
+ def decode_bboxes(self, bboxes: torch.Tensor, anchors: torch.Tensor, xywh: bool = True) -> torch.Tensor:
183
+ """Decode bounding boxes from predictions."""
184
+ return dist2bbox(
185
+ bboxes,
186
+ anchors,
187
+ xywh=xywh and not self.end2end and not self.xyxy,
188
+ dim=1,
189
+ )
190
+
191
+ @staticmethod
192
+ def postprocess(preds: torch.Tensor, max_det: int, nc: int = 80) -> torch.Tensor:
193
+ """Post-process YOLO model predictions.
194
+
195
+ Args:
196
+ preds (torch.Tensor): Raw predictions with shape (batch_size, num_anchors, 4 + nc) with last dimension
197
+ format [x, y, w, h, class_probs].
198
+ max_det (int): Maximum detections per image.
199
+ nc (int, optional): Number of classes.
200
+
201
+ Returns:
202
+ (torch.Tensor): Processed predictions with shape (batch_size, min(max_det, num_anchors), 6) and last
203
+ dimension format [x, y, w, h, max_class_prob, class_index].
204
+ """
205
+ batch_size, anchors, _ = preds.shape # i.e. shape(16,8400,84)
206
+ boxes, scores = preds.split([4, nc], dim=-1)
207
+ index = scores.amax(dim=-1).topk(min(max_det, anchors))[1].unsqueeze(-1)
208
+ boxes = boxes.gather(dim=1, index=index.repeat(1, 1, 4))
209
+ scores = scores.gather(dim=1, index=index.repeat(1, 1, nc))
210
+ scores, index = scores.flatten(1).topk(min(max_det, anchors))
211
+ i = torch.arange(batch_size)[..., None] # batch indices
212
+ return torch.cat([boxes[i, index // nc], scores[..., None], (index % nc)[..., None].float()], dim=-1)
213
+
214
+
215
+ class Segment(Detect):
216
+ """YOLO Segment head for segmentation models.
217
+
218
+ This class extends the Detect head to include mask prediction capabilities for instance segmentation tasks.
219
+
220
+ Attributes:
221
+ nm (int): Number of masks.
222
+ npr (int): Number of protos.
223
+ proto (Proto): Prototype generation module.
224
+ cv4 (nn.ModuleList): Convolution layers for mask coefficients.
225
+
226
+ Methods:
227
+ forward: Return model outputs and mask coefficients.
228
+
229
+ Examples:
230
+ Create a segmentation head
231
+ >>> segment = Segment(nc=80, nm=32, npr=256, ch=(256, 512, 1024))
232
+ >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)]
233
+ >>> outputs = segment(x)
234
+ """
235
+
236
+ def __init__(self, nc: int = 80, nm: int = 32, npr: int = 256, ch: tuple = ()):
237
+ """Initialize the YOLO model attributes such as the number of masks, prototypes, and the convolution layers.
238
+
239
+ Args:
240
+ nc (int): Number of classes.
241
+ nm (int): Number of masks.
242
+ npr (int): Number of protos.
243
+ ch (tuple): Tuple of channel sizes from backbone feature maps.
244
+ """
245
+ super().__init__(nc, ch)
246
+ self.nm = nm # number of masks
247
+ self.npr = npr # number of protos
248
+ self.proto = Proto(ch[0], self.npr, self.nm) # protos
249
+
250
+ c4 = max(ch[0] // 4, self.nm)
251
+ self.cv4 = nn.ModuleList(nn.Sequential(Conv(x, c4, 3), Conv(c4, c4, 3), nn.Conv2d(c4, self.nm, 1)) for x in ch)
252
+
253
+ def forward(self, x: list[torch.Tensor]) -> tuple | list[torch.Tensor]:
254
+ """Return model outputs and mask coefficients if training, otherwise return outputs and mask coefficients."""
255
+ p = self.proto(x[0]) # mask protos
256
+ bs = p.shape[0] # batch size
257
+
258
+ mc = torch.cat([self.cv4[i](x[i]).view(bs, self.nm, -1) for i in range(self.nl)], 2) # mask coefficients
259
+ x = Detect.forward(self, x)
260
+ if self.training:
261
+ return x, mc, p
262
+ return (torch.cat([x, mc], 1), p) if self.export else (torch.cat([x[0], mc], 1), (x[1], mc, p))
263
+
264
+
265
+ class OBB(Detect):
266
+ """YOLO OBB detection head for detection with rotation models.
267
+
268
+ This class extends the Detect head to include oriented bounding box prediction with rotation angles.
269
+
270
+ Attributes:
271
+ ne (int): Number of extra parameters.
272
+ cv4 (nn.ModuleList): Convolution layers for angle prediction.
273
+ angle (torch.Tensor): Predicted rotation angles.
274
+
275
+ Methods:
276
+ forward: Concatenate and return predicted bounding boxes and class probabilities.
277
+ decode_bboxes: Decode rotated bounding boxes.
278
+
279
+ Examples:
280
+ Create an OBB detection head
281
+ >>> obb = OBB(nc=80, ne=1, ch=(256, 512, 1024))
282
+ >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)]
283
+ >>> outputs = obb(x)
284
+ """
285
+
286
+ def __init__(self, nc: int = 80, ne: int = 1, ch: tuple = ()):
287
+ """Initialize OBB with number of classes `nc` and layer channels `ch`.
288
+
289
+ Args:
290
+ nc (int): Number of classes.
291
+ ne (int): Number of extra parameters.
292
+ ch (tuple): Tuple of channel sizes from backbone feature maps.
293
+ """
294
+ super().__init__(nc, ch)
295
+ self.ne = ne # number of extra parameters
296
+
297
+ c4 = max(ch[0] // 4, self.ne)
298
+ self.cv4 = nn.ModuleList(nn.Sequential(Conv(x, c4, 3), Conv(c4, c4, 3), nn.Conv2d(c4, self.ne, 1)) for x in ch)
299
+
300
+ def forward(self, x: list[torch.Tensor]) -> torch.Tensor | tuple:
301
+ """Concatenate and return predicted bounding boxes and class probabilities."""
302
+ bs = x[0].shape[0] # batch size
303
+ angle = torch.cat([self.cv4[i](x[i]).view(bs, self.ne, -1) for i in range(self.nl)], 2) # OBB theta logits
304
+ # NOTE: set `angle` as an attribute so that `decode_bboxes` could use it.
305
+ angle = (angle.sigmoid() - 0.25) * math.pi # [-pi/4, 3pi/4]
306
+ # angle = angle.sigmoid() * math.pi / 2 # [0, pi/2]
307
+ if not self.training:
308
+ self.angle = angle
309
+ x = Detect.forward(self, x)
310
+ if self.training:
311
+ return x, angle
312
+ return torch.cat([x, angle], 1) if self.export else (torch.cat([x[0], angle], 1), (x[1], angle))
313
+
314
+ def decode_bboxes(self, bboxes: torch.Tensor, anchors: torch.Tensor) -> torch.Tensor:
315
+ """Decode rotated bounding boxes."""
316
+ return dist2rbox(bboxes, self.angle, anchors, dim=1)
317
+
318
+
319
+ class Pose(Detect):
320
+ """YOLO Pose head for keypoints models.
321
+
322
+ This class extends the Detect head to include keypoint prediction capabilities for pose estimation tasks.
323
+
324
+ Attributes:
325
+ kpt_shape (tuple): Number of keypoints and dimensions (2 for x,y or 3 for x,y,visible).
326
+ nk (int): Total number of keypoint values.
327
+ cv4 (nn.ModuleList): Convolution layers for keypoint prediction.
328
+
329
+ Methods:
330
+ forward: Perform forward pass through YOLO model and return predictions.
331
+ kpts_decode: Decode keypoints from predictions.
332
+
333
+ Examples:
334
+ Create a pose detection head
335
+ >>> pose = Pose(nc=80, kpt_shape=(17, 3), ch=(256, 512, 1024))
336
+ >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)]
337
+ >>> outputs = pose(x)
338
+ """
339
+
340
+ def __init__(self, nc: int = 80, kpt_shape: tuple = (17, 3), ch: tuple = ()):
341
+ """Initialize YOLO network with default parameters and Convolutional Layers.
342
+
343
+ Args:
344
+ nc (int): Number of classes.
345
+ kpt_shape (tuple): Number of keypoints, number of dims (2 for x,y or 3 for x,y,visible).
346
+ ch (tuple): Tuple of channel sizes from backbone feature maps.
347
+ """
348
+ super().__init__(nc, ch)
349
+ self.kpt_shape = kpt_shape # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible)
350
+ self.nk = kpt_shape[0] * kpt_shape[1] # number of keypoints total
351
+
352
+ c4 = max(ch[0] // 4, self.nk)
353
+ self.cv4 = nn.ModuleList(nn.Sequential(Conv(x, c4, 3), Conv(c4, c4, 3), nn.Conv2d(c4, self.nk, 1)) for x in ch)
354
+
355
+ def forward(self, x: list[torch.Tensor]) -> torch.Tensor | tuple:
356
+ """Perform forward pass through YOLO model and return predictions."""
357
+ bs = x[0].shape[0] # batch size
358
+ kpt = torch.cat([self.cv4[i](x[i]).view(bs, self.nk, -1) for i in range(self.nl)], -1) # (bs, 17*3, h*w)
359
+ x = Detect.forward(self, x)
360
+ if self.training:
361
+ return x, kpt
362
+ pred_kpt = self.kpts_decode(bs, kpt)
363
+ return torch.cat([x, pred_kpt], 1) if self.export else (torch.cat([x[0], pred_kpt], 1), (x[1], kpt))
364
+
365
+ def kpts_decode(self, bs: int, kpts: torch.Tensor) -> torch.Tensor:
366
+ """Decode keypoints from predictions."""
367
+ ndim = self.kpt_shape[1]
368
+ if self.export:
369
+ # NCNN fix
370
+ y = kpts.view(bs, *self.kpt_shape, -1)
371
+ a = (y[:, :, :2] * 2.0 + (self.anchors - 0.5)) * self.strides
372
+ if ndim == 3:
373
+ a = torch.cat((a, y[:, :, 2:3].sigmoid()), 2)
374
+ return a.view(bs, self.nk, -1)
375
+ else:
376
+ y = kpts.clone()
377
+ if ndim == 3:
378
+ if NOT_MACOS14:
379
+ y[:, 2::ndim].sigmoid_()
380
+ else: # Apple macOS14 MPS bug https://github.com/ultralytics/ultralytics/pull/21878
381
+ y[:, 2::ndim] = y[:, 2::ndim].sigmoid()
382
+ y[:, 0::ndim] = (y[:, 0::ndim] * 2.0 + (self.anchors[0] - 0.5)) * self.strides
383
+ y[:, 1::ndim] = (y[:, 1::ndim] * 2.0 + (self.anchors[1] - 0.5)) * self.strides
384
+ return y
385
+
386
+
387
+ class Classify(nn.Module):
388
+ """YOLO classification head, i.e. x(b,c1,20,20) to x(b,c2).
389
+
390
+ This class implements a classification head that transforms feature maps into class predictions.
391
+
392
+ Attributes:
393
+ export (bool): Export mode flag.
394
+ conv (Conv): Convolutional layer for feature transformation.
395
+ pool (nn.AdaptiveAvgPool2d): Global average pooling layer.
396
+ drop (nn.Dropout): Dropout layer for regularization.
397
+ linear (nn.Linear): Linear layer for final classification.
398
+
399
+ Methods:
400
+ forward: Perform forward pass of the YOLO model on input image data.
401
+
402
+ Examples:
403
+ Create a classification head
404
+ >>> classify = Classify(c1=1024, c2=1000)
405
+ >>> x = torch.randn(1, 1024, 20, 20)
406
+ >>> output = classify(x)
407
+ """
408
+
409
+ export = False # export mode
410
+
411
+ def __init__(self, c1: int, c2: int, k: int = 1, s: int = 1, p: int | None = None, g: int = 1):
412
+ """Initialize YOLO classification head to transform input tensor from (b,c1,20,20) to (b,c2) shape.
413
+
414
+ Args:
415
+ c1 (int): Number of input channels.
416
+ c2 (int): Number of output classes.
417
+ k (int, optional): Kernel size.
418
+ s (int, optional): Stride.
419
+ p (int, optional): Padding.
420
+ g (int, optional): Groups.
421
+ """
422
+ super().__init__()
423
+ c_ = 1280 # efficientnet_b0 size
424
+ self.conv = Conv(c1, c_, k, s, p, g)
425
+ self.pool = nn.AdaptiveAvgPool2d(1) # to x(b,c_,1,1)
426
+ self.drop = nn.Dropout(p=0.0, inplace=True)
427
+ self.linear = nn.Linear(c_, c2) # to x(b,c2)
428
+
429
+ def forward(self, x: list[torch.Tensor] | torch.Tensor) -> torch.Tensor | tuple:
430
+ """Perform forward pass of the YOLO model on input image data."""
431
+ if isinstance(x, list):
432
+ x = torch.cat(x, 1)
433
+ x = self.linear(self.drop(self.pool(self.conv(x)).flatten(1)))
434
+ if self.training:
435
+ return x
436
+ y = x.softmax(1) # get final output
437
+ return y if self.export else (y, x)
438
+
439
+
440
+ class WorldDetect(Detect):
441
+ """Head for integrating YOLO detection models with semantic understanding from text embeddings.
442
+
443
+ This class extends the standard Detect head to incorporate text embeddings for enhanced semantic understanding in
444
+ object detection tasks.
445
+
446
+ Attributes:
447
+ cv3 (nn.ModuleList): Convolution layers for embedding features.
448
+ cv4 (nn.ModuleList): Contrastive head layers for text-vision alignment.
449
+
450
+ Methods:
451
+ forward: Concatenate and return predicted bounding boxes and class probabilities.
452
+ bias_init: Initialize detection head biases.
453
+
454
+ Examples:
455
+ Create a WorldDetect head
456
+ >>> world_detect = WorldDetect(nc=80, embed=512, with_bn=False, ch=(256, 512, 1024))
457
+ >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)]
458
+ >>> text = torch.randn(1, 80, 512)
459
+ >>> outputs = world_detect(x, text)
460
+ """
461
+
462
+ def __init__(self, nc: int = 80, embed: int = 512, with_bn: bool = False, ch: tuple = ()):
463
+ """Initialize YOLO detection layer with nc classes and layer channels ch.
464
+
465
+ Args:
466
+ nc (int): Number of classes.
467
+ embed (int): Embedding dimension.
468
+ with_bn (bool): Whether to use batch normalization in contrastive head.
469
+ ch (tuple): Tuple of channel sizes from backbone feature maps.
470
+ """
471
+ super().__init__(nc, ch)
472
+ c3 = max(ch[0], min(self.nc, 100))
473
+ self.cv3 = nn.ModuleList(nn.Sequential(Conv(x, c3, 3), Conv(c3, c3, 3), nn.Conv2d(c3, embed, 1)) for x in ch)
474
+ self.cv4 = nn.ModuleList(BNContrastiveHead(embed) if with_bn else ContrastiveHead() for _ in ch)
475
+
476
+ def forward(self, x: list[torch.Tensor], text: torch.Tensor) -> list[torch.Tensor] | tuple:
477
+ """Concatenate and return predicted bounding boxes and class probabilities."""
478
+ for i in range(self.nl):
479
+ x[i] = torch.cat((self.cv2[i](x[i]), self.cv4[i](self.cv3[i](x[i]), text)), 1)
480
+ if self.training:
481
+ return x
482
+ self.no = self.nc + self.reg_max * 4 # self.nc could be changed when inference with different texts
483
+ y = self._inference(x)
484
+ return y if self.export else (y, x)
485
+
486
+ def bias_init(self):
487
+ """Initialize Detect() biases, WARNING: requires stride availability."""
488
+ m = self # self.model[-1] # Detect() module
489
+ # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1
490
+ # ncf = math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # nominal class frequency
491
+ for a, b, s in zip(m.cv2, m.cv3, m.stride): # from
492
+ a[-1].bias.data[:] = 1.0 # box
493
+ # b[-1].bias.data[:] = math.log(5 / m.nc / (640 / s) ** 2) # cls (.01 objects, 80 classes, 640 img)
494
+
495
+
496
+ class LRPCHead(nn.Module):
497
+ """Lightweight Region Proposal and Classification Head for efficient object detection.
498
+
499
+ This head combines region proposal filtering with classification to enable efficient detection with dynamic
500
+ vocabulary support.
501
+
502
+ Attributes:
503
+ vocab (nn.Module): Vocabulary/classification layer.
504
+ pf (nn.Module): Proposal filter module.
505
+ loc (nn.Module): Localization module.
506
+ enabled (bool): Whether the head is enabled.
507
+
508
+ Methods:
509
+ conv2linear: Convert a 1x1 convolutional layer to a linear layer.
510
+ forward: Process classification and localization features to generate detection proposals.
511
+
512
+ Examples:
513
+ Create an LRPC head
514
+ >>> vocab = nn.Conv2d(256, 80, 1)
515
+ >>> pf = nn.Conv2d(256, 1, 1)
516
+ >>> loc = nn.Conv2d(256, 4, 1)
517
+ >>> head = LRPCHead(vocab, pf, loc, enabled=True)
518
+ """
519
+
520
+ def __init__(self, vocab: nn.Module, pf: nn.Module, loc: nn.Module, enabled: bool = True):
521
+ """Initialize LRPCHead with vocabulary, proposal filter, and localization components.
522
+
523
+ Args:
524
+ vocab (nn.Module): Vocabulary/classification module.
525
+ pf (nn.Module): Proposal filter module.
526
+ loc (nn.Module): Localization module.
527
+ enabled (bool): Whether to enable the head functionality.
528
+ """
529
+ super().__init__()
530
+ self.vocab = self.conv2linear(vocab) if enabled else vocab
531
+ self.pf = pf
532
+ self.loc = loc
533
+ self.enabled = enabled
534
+
535
+ @staticmethod
536
+ def conv2linear(conv: nn.Conv2d) -> nn.Linear:
537
+ """Convert a 1x1 convolutional layer to a linear layer."""
538
+ assert isinstance(conv, nn.Conv2d) and conv.kernel_size == (1, 1)
539
+ linear = nn.Linear(conv.in_channels, conv.out_channels)
540
+ linear.weight.data = conv.weight.view(conv.out_channels, -1).data
541
+ linear.bias.data = conv.bias.data
542
+ return linear
543
+
544
+ def forward(self, cls_feat: torch.Tensor, loc_feat: torch.Tensor, conf: float) -> tuple[tuple, torch.Tensor]:
545
+ """Process classification and localization features to generate detection proposals."""
546
+ if self.enabled:
547
+ pf_score = self.pf(cls_feat)[0, 0].flatten(0)
548
+ mask = pf_score.sigmoid() > conf
549
+ cls_feat = cls_feat.flatten(2).transpose(-1, -2)
550
+ cls_feat = self.vocab(cls_feat[:, mask] if conf else cls_feat * mask.unsqueeze(-1).int())
551
+ return (self.loc(loc_feat), cls_feat.transpose(-1, -2)), mask
552
+ else:
553
+ cls_feat = self.vocab(cls_feat)
554
+ loc_feat = self.loc(loc_feat)
555
+ return (loc_feat, cls_feat.flatten(2)), torch.ones(
556
+ cls_feat.shape[2] * cls_feat.shape[3], device=cls_feat.device, dtype=torch.bool
557
+ )
558
+
559
+
560
+ class YOLOEDetect(Detect):
561
+ """Head for integrating YOLO detection models with semantic understanding from text embeddings.
562
+
563
+ This class extends the standard Detect head to support text-guided detection with enhanced semantic understanding
564
+ through text embeddings and visual prompt embeddings.
565
+
566
+ Attributes:
567
+ is_fused (bool): Whether the model is fused for inference.
568
+ cv3 (nn.ModuleList): Convolution layers for embedding features.
569
+ cv4 (nn.ModuleList): Contrastive head layers for text-vision alignment.
570
+ reprta (Residual): Residual block for text prompt embeddings.
571
+ savpe (SAVPE): Spatial-aware visual prompt embeddings module.
572
+ embed (int): Embedding dimension.
573
+
574
+ Methods:
575
+ fuse: Fuse text features with model weights for efficient inference.
576
+ get_tpe: Get text prompt embeddings with normalization.
577
+ get_vpe: Get visual prompt embeddings with spatial awareness.
578
+ forward_lrpc: Process features with fused text embeddings for prompt-free model.
579
+ forward: Process features with class prompt embeddings to generate detections.
580
+ bias_init: Initialize biases for detection heads.
581
+
582
+ Examples:
583
+ Create a YOLOEDetect head
584
+ >>> yoloe_detect = YOLOEDetect(nc=80, embed=512, with_bn=True, ch=(256, 512, 1024))
585
+ >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)]
586
+ >>> cls_pe = torch.randn(1, 80, 512)
587
+ >>> outputs = yoloe_detect(x, cls_pe)
588
+ """
589
+
590
+ is_fused = False
591
+
592
+ def __init__(self, nc: int = 80, embed: int = 512, with_bn: bool = False, ch: tuple = ()):
593
+ """Initialize YOLO detection layer with nc classes and layer channels ch.
594
+
595
+ Args:
596
+ nc (int): Number of classes.
597
+ embed (int): Embedding dimension.
598
+ with_bn (bool): Whether to use batch normalization in contrastive head.
599
+ ch (tuple): Tuple of channel sizes from backbone feature maps.
600
+ """
601
+ super().__init__(nc, ch)
602
+ c3 = max(ch[0], min(self.nc, 100))
603
+ assert c3 <= embed
604
+ assert with_bn
605
+ self.cv3 = (
606
+ nn.ModuleList(nn.Sequential(Conv(x, c3, 3), Conv(c3, c3, 3), nn.Conv2d(c3, embed, 1)) for x in ch)
607
+ if self.legacy
608
+ else nn.ModuleList(
609
+ nn.Sequential(
610
+ nn.Sequential(DWConv(x, x, 3), Conv(x, c3, 1)),
611
+ nn.Sequential(DWConv(c3, c3, 3), Conv(c3, c3, 1)),
612
+ nn.Conv2d(c3, embed, 1),
613
+ )
614
+ for x in ch
615
+ )
616
+ )
617
+
618
+ self.cv4 = nn.ModuleList(BNContrastiveHead(embed) if with_bn else ContrastiveHead() for _ in ch)
619
+
620
+ self.reprta = Residual(SwiGLUFFN(embed, embed))
621
+ self.savpe = SAVPE(ch, c3, embed)
622
+ self.embed = embed
623
+
624
+ @smart_inference_mode()
625
+ def fuse(self, txt_feats: torch.Tensor):
626
+ """Fuse text features with model weights for efficient inference."""
627
+ if self.is_fused:
628
+ return
629
+
630
+ assert not self.training
631
+ txt_feats = txt_feats.to(torch.float32).squeeze(0)
632
+ for cls_head, bn_head in zip(self.cv3, self.cv4):
633
+ assert isinstance(cls_head, nn.Sequential)
634
+ assert isinstance(bn_head, BNContrastiveHead)
635
+ conv = cls_head[-1]
636
+ assert isinstance(conv, nn.Conv2d)
637
+ logit_scale = bn_head.logit_scale
638
+ bias = bn_head.bias
639
+ norm = bn_head.norm
640
+
641
+ t = txt_feats * logit_scale.exp()
642
+ conv: nn.Conv2d = fuse_conv_and_bn(conv, norm)
643
+
644
+ w = conv.weight.data.squeeze(-1).squeeze(-1)
645
+ b = conv.bias.data
646
+
647
+ w = t @ w
648
+ b1 = (t @ b.reshape(-1).unsqueeze(-1)).squeeze(-1)
649
+ b2 = torch.ones_like(b1) * bias
650
+
651
+ conv = (
652
+ nn.Conv2d(
653
+ conv.in_channels,
654
+ w.shape[0],
655
+ kernel_size=1,
656
+ )
657
+ .requires_grad_(False)
658
+ .to(conv.weight.device)
659
+ )
660
+
661
+ conv.weight.data.copy_(w.unsqueeze(-1).unsqueeze(-1))
662
+ conv.bias.data.copy_(b1 + b2)
663
+ cls_head[-1] = conv
664
+
665
+ bn_head.fuse()
666
+
667
+ del self.reprta
668
+ self.reprta = nn.Identity()
669
+ self.is_fused = True
670
+
671
+ def get_tpe(self, tpe: torch.Tensor | None) -> torch.Tensor | None:
672
+ """Get text prompt embeddings with normalization."""
673
+ return None if tpe is None else F.normalize(self.reprta(tpe), dim=-1, p=2)
674
+
675
+ def get_vpe(self, x: list[torch.Tensor], vpe: torch.Tensor) -> torch.Tensor:
676
+ """Get visual prompt embeddings with spatial awareness."""
677
+ if vpe.shape[1] == 0: # no visual prompt embeddings
678
+ return torch.zeros(x[0].shape[0], 0, self.embed, device=x[0].device)
679
+ if vpe.ndim == 4: # (B, N, H, W)
680
+ vpe = self.savpe(x, vpe)
681
+ assert vpe.ndim == 3 # (B, N, D)
682
+ return vpe
683
+
684
+ def forward_lrpc(self, x: list[torch.Tensor], return_mask: bool = False) -> torch.Tensor | tuple:
685
+ """Process features with fused text embeddings to generate detections for prompt-free model."""
686
+ masks = []
687
+ assert self.is_fused, "Prompt-free inference requires model to be fused!"
688
+ for i in range(self.nl):
689
+ cls_feat = self.cv3[i](x[i])
690
+ loc_feat = self.cv2[i](x[i])
691
+ assert isinstance(self.lrpc[i], LRPCHead)
692
+ x[i], mask = self.lrpc[i](
693
+ cls_feat, loc_feat, 0 if self.export and not self.dynamic else getattr(self, "conf", 0.001)
694
+ )
695
+ masks.append(mask)
696
+ shape = x[0][0].shape
697
+ if self.dynamic or self.shape != shape:
698
+ self.anchors, self.strides = (x.transpose(0, 1) for x in make_anchors([b[0] for b in x], self.stride, 0.5))
699
+ self.shape = shape
700
+ box = torch.cat([xi[0].view(shape[0], self.reg_max * 4, -1) for xi in x], 2)
701
+ cls = torch.cat([xi[1] for xi in x], 2)
702
+
703
+ if self.export and self.format in {"tflite", "edgetpu"}:
704
+ # Precompute normalization factor to increase numerical stability
705
+ # See https://github.com/ultralytics/ultralytics/issues/7371
706
+ grid_h = shape[2]
707
+ grid_w = shape[3]
708
+ grid_size = torch.tensor([grid_w, grid_h, grid_w, grid_h], device=box.device).reshape(1, 4, 1)
709
+ norm = self.strides / (self.stride[0] * grid_size)
710
+ dbox = self.decode_bboxes(self.dfl(box) * norm, self.anchors.unsqueeze(0) * norm[:, :2])
711
+ else:
712
+ dbox = self.decode_bboxes(self.dfl(box), self.anchors.unsqueeze(0)) * self.strides
713
+
714
+ mask = torch.cat(masks)
715
+ y = torch.cat((dbox if self.export and not self.dynamic else dbox[..., mask], cls.sigmoid()), 1)
716
+
717
+ if return_mask:
718
+ return (y, mask) if self.export else ((y, x), mask)
719
+ else:
720
+ return y if self.export else (y, x)
721
+
722
+ def forward(self, x: list[torch.Tensor], cls_pe: torch.Tensor, return_mask: bool = False) -> torch.Tensor | tuple:
723
+ """Process features with class prompt embeddings to generate detections."""
724
+ if hasattr(self, "lrpc"): # for prompt-free inference
725
+ return self.forward_lrpc(x, return_mask)
726
+ for i in range(self.nl):
727
+ x[i] = torch.cat((self.cv2[i](x[i]), self.cv4[i](self.cv3[i](x[i]), cls_pe)), 1)
728
+ if self.training:
729
+ return x
730
+ self.no = self.nc + self.reg_max * 4 # self.nc could be changed when inference with different texts
731
+ y = self._inference(x)
732
+ return y if self.export else (y, x)
733
+
734
+ def bias_init(self):
735
+ """Initialize biases for detection heads."""
736
+ m = self # self.model[-1] # Detect() module
737
+ # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1
738
+ # ncf = math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # nominal class frequency
739
+ for a, b, c, s in zip(m.cv2, m.cv3, m.cv4, m.stride): # from
740
+ a[-1].bias.data[:] = 1.0 # box
741
+ # b[-1].bias.data[:] = math.log(5 / m.nc / (640 / s) ** 2) # cls (.01 objects, 80 classes, 640 img)
742
+ b[-1].bias.data[:] = 0.0
743
+ c.bias.data[:] = math.log(5 / m.nc / (640 / s) ** 2)
744
+
745
+
746
+ class YOLOESegment(YOLOEDetect):
747
+ """YOLO segmentation head with text embedding capabilities.
748
+
749
+ This class extends YOLOEDetect to include mask prediction capabilities for instance segmentation tasks with
750
+ text-guided semantic understanding.
751
+
752
+ Attributes:
753
+ nm (int): Number of masks.
754
+ npr (int): Number of protos.
755
+ proto (Proto): Prototype generation module.
756
+ cv5 (nn.ModuleList): Convolution layers for mask coefficients.
757
+
758
+ Methods:
759
+ forward: Return model outputs and mask coefficients.
760
+
761
+ Examples:
762
+ Create a YOLOESegment head
763
+ >>> yoloe_segment = YOLOESegment(nc=80, nm=32, npr=256, embed=512, with_bn=True, ch=(256, 512, 1024))
764
+ >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)]
765
+ >>> text = torch.randn(1, 80, 512)
766
+ >>> outputs = yoloe_segment(x, text)
767
+ """
768
+
769
+ def __init__(
770
+ self, nc: int = 80, nm: int = 32, npr: int = 256, embed: int = 512, with_bn: bool = False, ch: tuple = ()
771
+ ):
772
+ """Initialize YOLOESegment with class count, mask parameters, and embedding dimensions.
773
+
774
+ Args:
775
+ nc (int): Number of classes.
776
+ nm (int): Number of masks.
777
+ npr (int): Number of protos.
778
+ embed (int): Embedding dimension.
779
+ with_bn (bool): Whether to use batch normalization in contrastive head.
780
+ ch (tuple): Tuple of channel sizes from backbone feature maps.
781
+ """
782
+ super().__init__(nc, embed, with_bn, ch)
783
+ self.nm = nm
784
+ self.npr = npr
785
+ self.proto = Proto(ch[0], self.npr, self.nm)
786
+
787
+ c5 = max(ch[0] // 4, self.nm)
788
+ self.cv5 = nn.ModuleList(nn.Sequential(Conv(x, c5, 3), Conv(c5, c5, 3), nn.Conv2d(c5, self.nm, 1)) for x in ch)
789
+
790
+ def forward(self, x: list[torch.Tensor], text: torch.Tensor) -> tuple | torch.Tensor:
791
+ """Return model outputs and mask coefficients if training, otherwise return outputs and mask coefficients."""
792
+ p = self.proto(x[0]) # mask protos
793
+ bs = p.shape[0] # batch size
794
+
795
+ mc = torch.cat([self.cv5[i](x[i]).view(bs, self.nm, -1) for i in range(self.nl)], 2) # mask coefficients
796
+ has_lrpc = hasattr(self, "lrpc")
797
+
798
+ if not has_lrpc:
799
+ x = YOLOEDetect.forward(self, x, text)
800
+ else:
801
+ x, mask = YOLOEDetect.forward(self, x, text, return_mask=True)
802
+
803
+ if self.training:
804
+ return x, mc, p
805
+
806
+ if has_lrpc:
807
+ mc = (mc * mask.int()) if self.export and not self.dynamic else mc[..., mask]
808
+
809
+ return (torch.cat([x, mc], 1), p) if self.export else (torch.cat([x[0], mc], 1), (x[1], mc, p))
810
+
811
+
812
+ class RTDETRDecoder(nn.Module):
813
+ """Real-Time Deformable Transformer Decoder (RTDETRDecoder) module for object detection.
814
+
815
+ This decoder module utilizes Transformer architecture along with deformable convolutions to predict bounding boxes
816
+ and class labels for objects in an image. It integrates features from multiple layers and runs through a series of
817
+ Transformer decoder layers to output the final predictions.
818
+
819
+ Attributes:
820
+ export (bool): Export mode flag.
821
+ hidden_dim (int): Dimension of hidden layers.
822
+ nhead (int): Number of heads in multi-head attention.
823
+ nl (int): Number of feature levels.
824
+ nc (int): Number of classes.
825
+ num_queries (int): Number of query points.
826
+ num_decoder_layers (int): Number of decoder layers.
827
+ input_proj (nn.ModuleList): Input projection layers for backbone features.
828
+ decoder (DeformableTransformerDecoder): Transformer decoder module.
829
+ denoising_class_embed (nn.Embedding): Class embeddings for denoising.
830
+ num_denoising (int): Number of denoising queries.
831
+ label_noise_ratio (float): Label noise ratio for training.
832
+ box_noise_scale (float): Box noise scale for training.
833
+ learnt_init_query (bool): Whether to learn initial query embeddings.
834
+ tgt_embed (nn.Embedding): Target embeddings for queries.
835
+ query_pos_head (MLP): Query position head.
836
+ enc_output (nn.Sequential): Encoder output layers.
837
+ enc_score_head (nn.Linear): Encoder score prediction head.
838
+ enc_bbox_head (MLP): Encoder bbox prediction head.
839
+ dec_score_head (nn.ModuleList): Decoder score prediction heads.
840
+ dec_bbox_head (nn.ModuleList): Decoder bbox prediction heads.
841
+
842
+ Methods:
843
+ forward: Run forward pass and return bounding box and classification scores.
844
+
845
+ Examples:
846
+ Create an RTDETRDecoder
847
+ >>> decoder = RTDETRDecoder(nc=80, ch=(512, 1024, 2048), hd=256, nq=300)
848
+ >>> x = [torch.randn(1, 512, 64, 64), torch.randn(1, 1024, 32, 32), torch.randn(1, 2048, 16, 16)]
849
+ >>> outputs = decoder(x)
850
+ """
851
+
852
+ export = False # export mode
853
+ shapes = []
854
+ anchors = torch.empty(0)
855
+ valid_mask = torch.empty(0)
856
+ dynamic = False
857
+
858
+ def __init__(
859
+ self,
860
+ nc: int = 80,
861
+ ch: tuple = (512, 1024, 2048),
862
+ hd: int = 256, # hidden dim
863
+ nq: int = 300, # num queries
864
+ ndp: int = 4, # num decoder points
865
+ nh: int = 8, # num head
866
+ ndl: int = 6, # num decoder layers
867
+ d_ffn: int = 1024, # dim of feedforward
868
+ dropout: float = 0.0,
869
+ act: nn.Module = nn.ReLU(),
870
+ eval_idx: int = -1,
871
+ # Training args
872
+ nd: int = 100, # num denoising
873
+ label_noise_ratio: float = 0.5,
874
+ box_noise_scale: float = 1.0,
875
+ learnt_init_query: bool = False,
876
+ ):
877
+ """Initialize the RTDETRDecoder module with the given parameters.
878
+
879
+ Args:
880
+ nc (int): Number of classes.
881
+ ch (tuple): Channels in the backbone feature maps.
882
+ hd (int): Dimension of hidden layers.
883
+ nq (int): Number of query points.
884
+ ndp (int): Number of decoder points.
885
+ nh (int): Number of heads in multi-head attention.
886
+ ndl (int): Number of decoder layers.
887
+ d_ffn (int): Dimension of the feed-forward networks.
888
+ dropout (float): Dropout rate.
889
+ act (nn.Module): Activation function.
890
+ eval_idx (int): Evaluation index.
891
+ nd (int): Number of denoising.
892
+ label_noise_ratio (float): Label noise ratio.
893
+ box_noise_scale (float): Box noise scale.
894
+ learnt_init_query (bool): Whether to learn initial query embeddings.
895
+ """
896
+ super().__init__()
897
+ self.hidden_dim = hd
898
+ self.nhead = nh
899
+ self.nl = len(ch) # num level
900
+ self.nc = nc
901
+ self.num_queries = nq
902
+ self.num_decoder_layers = ndl
903
+
904
+ # Backbone feature projection
905
+ self.input_proj = nn.ModuleList(nn.Sequential(nn.Conv2d(x, hd, 1, bias=False), nn.BatchNorm2d(hd)) for x in ch)
906
+ # NOTE: simplified version but it's not consistent with .pt weights.
907
+ # self.input_proj = nn.ModuleList(Conv(x, hd, act=False) for x in ch)
908
+
909
+ # Transformer module
910
+ decoder_layer = DeformableTransformerDecoderLayer(hd, nh, d_ffn, dropout, act, self.nl, ndp)
911
+ self.decoder = DeformableTransformerDecoder(hd, decoder_layer, ndl, eval_idx)
912
+
913
+ # Denoising part
914
+ self.denoising_class_embed = nn.Embedding(nc, hd)
915
+ self.num_denoising = nd
916
+ self.label_noise_ratio = label_noise_ratio
917
+ self.box_noise_scale = box_noise_scale
918
+
919
+ # Decoder embedding
920
+ self.learnt_init_query = learnt_init_query
921
+ if learnt_init_query:
922
+ self.tgt_embed = nn.Embedding(nq, hd)
923
+ self.query_pos_head = MLP(4, 2 * hd, hd, num_layers=2)
924
+
925
+ # Encoder head
926
+ self.enc_output = nn.Sequential(nn.Linear(hd, hd), nn.LayerNorm(hd))
927
+ self.enc_score_head = nn.Linear(hd, nc)
928
+ self.enc_bbox_head = MLP(hd, hd, 4, num_layers=3)
929
+
930
+ # Decoder head
931
+ self.dec_score_head = nn.ModuleList([nn.Linear(hd, nc) for _ in range(ndl)])
932
+ self.dec_bbox_head = nn.ModuleList([MLP(hd, hd, 4, num_layers=3) for _ in range(ndl)])
933
+
934
+ self._reset_parameters()
935
+
936
+ def forward(self, x: list[torch.Tensor], batch: dict | None = None) -> tuple | torch.Tensor:
937
+ """Run the forward pass of the module, returning bounding box and classification scores for the input.
938
+
939
+ Args:
940
+ x (list[torch.Tensor]): List of feature maps from the backbone.
941
+ batch (dict, optional): Batch information for training.
942
+
943
+ Returns:
944
+ outputs (tuple | torch.Tensor): During training, returns a tuple of bounding boxes, scores, and other
945
+ metadata. During inference, returns a tensor of shape (bs, 300, 4+nc) containing bounding boxes and
946
+ class scores.
947
+ """
948
+ from ultralytics.models.utils.ops import get_cdn_group
949
+
950
+ # Input projection and embedding
951
+ feats, shapes = self._get_encoder_input(x)
952
+
953
+ # Prepare denoising training
954
+ dn_embed, dn_bbox, attn_mask, dn_meta = get_cdn_group(
955
+ batch,
956
+ self.nc,
957
+ self.num_queries,
958
+ self.denoising_class_embed.weight,
959
+ self.num_denoising,
960
+ self.label_noise_ratio,
961
+ self.box_noise_scale,
962
+ self.training,
963
+ )
964
+
965
+ embed, refer_bbox, enc_bboxes, enc_scores = self._get_decoder_input(feats, shapes, dn_embed, dn_bbox)
966
+
967
+ # Decoder
968
+ dec_bboxes, dec_scores = self.decoder(
969
+ embed,
970
+ refer_bbox,
971
+ feats,
972
+ shapes,
973
+ self.dec_bbox_head,
974
+ self.dec_score_head,
975
+ self.query_pos_head,
976
+ attn_mask=attn_mask,
977
+ )
978
+ x = dec_bboxes, dec_scores, enc_bboxes, enc_scores, dn_meta
979
+ if self.training:
980
+ return x
981
+ # (bs, 300, 4+nc)
982
+ y = torch.cat((dec_bboxes.squeeze(0), dec_scores.squeeze(0).sigmoid()), -1)
983
+ return y if self.export else (y, x)
984
+
985
+ @staticmethod
986
+ def _generate_anchors(
987
+ shapes: list[list[int]],
988
+ grid_size: float = 0.05,
989
+ dtype: torch.dtype = torch.float32,
990
+ device: str = "cpu",
991
+ eps: float = 1e-2,
992
+ ) -> tuple[torch.Tensor, torch.Tensor]:
993
+ """Generate anchor bounding boxes for given shapes with specific grid size and validate them.
994
+
995
+ Args:
996
+ shapes (list): List of feature map shapes.
997
+ grid_size (float, optional): Base size of grid cells.
998
+ dtype (torch.dtype, optional): Data type for tensors.
999
+ device (str, optional): Device to create tensors on.
1000
+ eps (float, optional): Small value for numerical stability.
1001
+
1002
+ Returns:
1003
+ anchors (torch.Tensor): Generated anchor boxes.
1004
+ valid_mask (torch.Tensor): Valid mask for anchors.
1005
+ """
1006
+ anchors = []
1007
+ for i, (h, w) in enumerate(shapes):
1008
+ sy = torch.arange(end=h, dtype=dtype, device=device)
1009
+ sx = torch.arange(end=w, dtype=dtype, device=device)
1010
+ grid_y, grid_x = torch.meshgrid(sy, sx, indexing="ij") if TORCH_1_11 else torch.meshgrid(sy, sx)
1011
+ grid_xy = torch.stack([grid_x, grid_y], -1) # (h, w, 2)
1012
+
1013
+ valid_WH = torch.tensor([w, h], dtype=dtype, device=device)
1014
+ grid_xy = (grid_xy.unsqueeze(0) + 0.5) / valid_WH # (1, h, w, 2)
1015
+ wh = torch.ones_like(grid_xy, dtype=dtype, device=device) * grid_size * (2.0**i)
1016
+ anchors.append(torch.cat([grid_xy, wh], -1).view(-1, h * w, 4)) # (1, h*w, 4)
1017
+
1018
+ anchors = torch.cat(anchors, 1) # (1, h*w*nl, 4)
1019
+ valid_mask = ((anchors > eps) & (anchors < 1 - eps)).all(-1, keepdim=True) # 1, h*w*nl, 1
1020
+ anchors = torch.log(anchors / (1 - anchors))
1021
+ anchors = anchors.masked_fill(~valid_mask, float("inf"))
1022
+ return anchors, valid_mask
1023
+
1024
+ def _get_encoder_input(self, x: list[torch.Tensor]) -> tuple[torch.Tensor, list[list[int]]]:
1025
+ """Process and return encoder inputs by getting projection features from input and concatenating them.
1026
+
1027
+ Args:
1028
+ x (list[torch.Tensor]): List of feature maps from the backbone.
1029
+
1030
+ Returns:
1031
+ feats (torch.Tensor): Processed features.
1032
+ shapes (list): List of feature map shapes.
1033
+ """
1034
+ # Get projection features
1035
+ x = [self.input_proj[i](feat) for i, feat in enumerate(x)]
1036
+ # Get encoder inputs
1037
+ feats = []
1038
+ shapes = []
1039
+ for feat in x:
1040
+ h, w = feat.shape[2:]
1041
+ # [b, c, h, w] -> [b, h*w, c]
1042
+ feats.append(feat.flatten(2).permute(0, 2, 1))
1043
+ # [nl, 2]
1044
+ shapes.append([h, w])
1045
+
1046
+ # [b, h*w, c]
1047
+ feats = torch.cat(feats, 1)
1048
+ return feats, shapes
1049
+
1050
+ def _get_decoder_input(
1051
+ self,
1052
+ feats: torch.Tensor,
1053
+ shapes: list[list[int]],
1054
+ dn_embed: torch.Tensor | None = None,
1055
+ dn_bbox: torch.Tensor | None = None,
1056
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
1057
+ """Generate and prepare the input required for the decoder from the provided features and shapes.
1058
+
1059
+ Args:
1060
+ feats (torch.Tensor): Processed features from encoder.
1061
+ shapes (list): List of feature map shapes.
1062
+ dn_embed (torch.Tensor, optional): Denoising embeddings.
1063
+ dn_bbox (torch.Tensor, optional): Denoising bounding boxes.
1064
+
1065
+ Returns:
1066
+ embeddings (torch.Tensor): Query embeddings for decoder.
1067
+ refer_bbox (torch.Tensor): Reference bounding boxes.
1068
+ enc_bboxes (torch.Tensor): Encoded bounding boxes.
1069
+ enc_scores (torch.Tensor): Encoded scores.
1070
+ """
1071
+ bs = feats.shape[0]
1072
+ if self.dynamic or self.shapes != shapes:
1073
+ self.anchors, self.valid_mask = self._generate_anchors(shapes, dtype=feats.dtype, device=feats.device)
1074
+ self.shapes = shapes
1075
+
1076
+ # Prepare input for decoder
1077
+ features = self.enc_output(self.valid_mask * feats) # bs, h*w, 256
1078
+ enc_outputs_scores = self.enc_score_head(features) # (bs, h*w, nc)
1079
+
1080
+ # Query selection
1081
+ # (bs, num_queries)
1082
+ topk_ind = torch.topk(enc_outputs_scores.max(-1).values, self.num_queries, dim=1).indices.view(-1)
1083
+ # (bs, num_queries)
1084
+ batch_ind = torch.arange(end=bs, dtype=topk_ind.dtype).unsqueeze(-1).repeat(1, self.num_queries).view(-1)
1085
+
1086
+ # (bs, num_queries, 256)
1087
+ top_k_features = features[batch_ind, topk_ind].view(bs, self.num_queries, -1)
1088
+ # (bs, num_queries, 4)
1089
+ top_k_anchors = self.anchors[:, topk_ind].view(bs, self.num_queries, -1)
1090
+
1091
+ # Dynamic anchors + static content
1092
+ refer_bbox = self.enc_bbox_head(top_k_features) + top_k_anchors
1093
+
1094
+ enc_bboxes = refer_bbox.sigmoid()
1095
+ if dn_bbox is not None:
1096
+ refer_bbox = torch.cat([dn_bbox, refer_bbox], 1)
1097
+ enc_scores = enc_outputs_scores[batch_ind, topk_ind].view(bs, self.num_queries, -1)
1098
+
1099
+ embeddings = self.tgt_embed.weight.unsqueeze(0).repeat(bs, 1, 1) if self.learnt_init_query else top_k_features
1100
+ if self.training:
1101
+ refer_bbox = refer_bbox.detach()
1102
+ if not self.learnt_init_query:
1103
+ embeddings = embeddings.detach()
1104
+ if dn_embed is not None:
1105
+ embeddings = torch.cat([dn_embed, embeddings], 1)
1106
+
1107
+ return embeddings, refer_bbox, enc_bboxes, enc_scores
1108
+
1109
+ def _reset_parameters(self):
1110
+ """Initialize or reset the parameters of the model's various components with predefined weights and biases."""
1111
+ # Class and bbox head init
1112
+ bias_cls = bias_init_with_prob(0.01) / 80 * self.nc
1113
+ # NOTE: the weight initialization in `linear_init` would cause NaN when training with custom datasets.
1114
+ # linear_init(self.enc_score_head)
1115
+ constant_(self.enc_score_head.bias, bias_cls)
1116
+ constant_(self.enc_bbox_head.layers[-1].weight, 0.0)
1117
+ constant_(self.enc_bbox_head.layers[-1].bias, 0.0)
1118
+ for cls_, reg_ in zip(self.dec_score_head, self.dec_bbox_head):
1119
+ # linear_init(cls_)
1120
+ constant_(cls_.bias, bias_cls)
1121
+ constant_(reg_.layers[-1].weight, 0.0)
1122
+ constant_(reg_.layers[-1].bias, 0.0)
1123
+
1124
+ linear_init(self.enc_output[0])
1125
+ xavier_uniform_(self.enc_output[0].weight)
1126
+ if self.learnt_init_query:
1127
+ xavier_uniform_(self.tgt_embed.weight)
1128
+ xavier_uniform_(self.query_pos_head.layers[0].weight)
1129
+ xavier_uniform_(self.query_pos_head.layers[1].weight)
1130
+ for layer in self.input_proj:
1131
+ xavier_uniform_(layer[0].weight)
1132
+
1133
+
1134
+ class v10Detect(Detect):
1135
+ """v10 Detection head from https://arxiv.org/pdf/2405.14458.
1136
+
1137
+ This class implements the YOLOv10 detection head with dual-assignment training and consistent dual predictions for
1138
+ improved efficiency and performance.
1139
+
1140
+ Attributes:
1141
+ end2end (bool): End-to-end detection mode.
1142
+ max_det (int): Maximum number of detections.
1143
+ cv3 (nn.ModuleList): Light classification head layers.
1144
+ one2one_cv3 (nn.ModuleList): One-to-one classification head layers.
1145
+
1146
+ Methods:
1147
+ __init__: Initialize the v10Detect object with specified number of classes and input channels.
1148
+ forward: Perform forward pass of the v10Detect module.
1149
+ bias_init: Initialize biases of the Detect module.
1150
+ fuse: Remove the one2many head for inference optimization.
1151
+
1152
+ Examples:
1153
+ Create a v10Detect head
1154
+ >>> v10_detect = v10Detect(nc=80, ch=(256, 512, 1024))
1155
+ >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)]
1156
+ >>> outputs = v10_detect(x)
1157
+ """
1158
+
1159
+ end2end = True
1160
+
1161
+ def __init__(self, nc: int = 80, ch: tuple = ()):
1162
+ """Initialize the v10Detect object with the specified number of classes and input channels.
1163
+
1164
+ Args:
1165
+ nc (int): Number of classes.
1166
+ ch (tuple): Tuple of channel sizes from backbone feature maps.
1167
+ """
1168
+ super().__init__(nc, ch)
1169
+ c3 = max(ch[0], min(self.nc, 100)) # channels
1170
+ # Light cls head
1171
+ self.cv3 = nn.ModuleList(
1172
+ nn.Sequential(
1173
+ nn.Sequential(Conv(x, x, 3, g=x), Conv(x, c3, 1)),
1174
+ nn.Sequential(Conv(c3, c3, 3, g=c3), Conv(c3, c3, 1)),
1175
+ nn.Conv2d(c3, self.nc, 1),
1176
+ )
1177
+ for x in ch
1178
+ )
1179
+ self.one2one_cv3 = copy.deepcopy(self.cv3)
1180
+
1181
+ def fuse(self):
1182
+ """Remove the one2many head for inference optimization."""
1183
+ self.cv2 = self.cv3 = nn.ModuleList([nn.Identity()] * self.nl)