dgenerate-ultralytics-headless 8.3.134__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 (272) hide show
  1. dgenerate_ultralytics_headless-8.3.134.dist-info/METADATA +400 -0
  2. dgenerate_ultralytics_headless-8.3.134.dist-info/RECORD +272 -0
  3. dgenerate_ultralytics_headless-8.3.134.dist-info/WHEEL +5 -0
  4. dgenerate_ultralytics_headless-8.3.134.dist-info/entry_points.txt +3 -0
  5. dgenerate_ultralytics_headless-8.3.134.dist-info/licenses/LICENSE +661 -0
  6. dgenerate_ultralytics_headless-8.3.134.dist-info/top_level.txt +1 -0
  7. tests/__init__.py +22 -0
  8. tests/conftest.py +83 -0
  9. tests/test_cli.py +138 -0
  10. tests/test_cuda.py +215 -0
  11. tests/test_engine.py +131 -0
  12. tests/test_exports.py +236 -0
  13. tests/test_integrations.py +154 -0
  14. tests/test_python.py +694 -0
  15. tests/test_solutions.py +187 -0
  16. ultralytics/__init__.py +30 -0
  17. ultralytics/assets/bus.jpg +0 -0
  18. ultralytics/assets/zidane.jpg +0 -0
  19. ultralytics/cfg/__init__.py +1023 -0
  20. ultralytics/cfg/datasets/Argoverse.yaml +77 -0
  21. ultralytics/cfg/datasets/DOTAv1.5.yaml +37 -0
  22. ultralytics/cfg/datasets/DOTAv1.yaml +36 -0
  23. ultralytics/cfg/datasets/GlobalWheat2020.yaml +68 -0
  24. ultralytics/cfg/datasets/HomeObjects-3K.yaml +33 -0
  25. ultralytics/cfg/datasets/ImageNet.yaml +2025 -0
  26. ultralytics/cfg/datasets/Objects365.yaml +443 -0
  27. ultralytics/cfg/datasets/SKU-110K.yaml +58 -0
  28. ultralytics/cfg/datasets/VOC.yaml +106 -0
  29. ultralytics/cfg/datasets/VisDrone.yaml +77 -0
  30. ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
  31. ultralytics/cfg/datasets/brain-tumor.yaml +23 -0
  32. ultralytics/cfg/datasets/carparts-seg.yaml +44 -0
  33. ultralytics/cfg/datasets/coco-pose.yaml +42 -0
  34. ultralytics/cfg/datasets/coco.yaml +118 -0
  35. ultralytics/cfg/datasets/coco128-seg.yaml +101 -0
  36. ultralytics/cfg/datasets/coco128.yaml +101 -0
  37. ultralytics/cfg/datasets/coco8-multispectral.yaml +104 -0
  38. ultralytics/cfg/datasets/coco8-pose.yaml +26 -0
  39. ultralytics/cfg/datasets/coco8-seg.yaml +101 -0
  40. ultralytics/cfg/datasets/coco8.yaml +101 -0
  41. ultralytics/cfg/datasets/crack-seg.yaml +22 -0
  42. ultralytics/cfg/datasets/dog-pose.yaml +24 -0
  43. ultralytics/cfg/datasets/dota8-multispectral.yaml +38 -0
  44. ultralytics/cfg/datasets/dota8.yaml +35 -0
  45. ultralytics/cfg/datasets/hand-keypoints.yaml +26 -0
  46. ultralytics/cfg/datasets/lvis.yaml +1240 -0
  47. ultralytics/cfg/datasets/medical-pills.yaml +22 -0
  48. ultralytics/cfg/datasets/open-images-v7.yaml +666 -0
  49. ultralytics/cfg/datasets/package-seg.yaml +22 -0
  50. ultralytics/cfg/datasets/signature.yaml +21 -0
  51. ultralytics/cfg/datasets/tiger-pose.yaml +25 -0
  52. ultralytics/cfg/datasets/xView.yaml +155 -0
  53. ultralytics/cfg/default.yaml +127 -0
  54. ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +17 -0
  55. ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
  56. ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
  57. ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
  58. ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
  59. ultralytics/cfg/models/11/yolo11.yaml +50 -0
  60. ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
  61. ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
  62. ultralytics/cfg/models/12/yolo12-cls.yaml +32 -0
  63. ultralytics/cfg/models/12/yolo12-obb.yaml +48 -0
  64. ultralytics/cfg/models/12/yolo12-pose.yaml +49 -0
  65. ultralytics/cfg/models/12/yolo12-seg.yaml +48 -0
  66. ultralytics/cfg/models/12/yolo12.yaml +48 -0
  67. ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +53 -0
  68. ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +45 -0
  69. ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +45 -0
  70. ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +57 -0
  71. ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
  72. ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
  73. ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
  74. ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
  75. ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
  76. ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
  77. ultralytics/cfg/models/v3/yolov3-spp.yaml +49 -0
  78. ultralytics/cfg/models/v3/yolov3-tiny.yaml +40 -0
  79. ultralytics/cfg/models/v3/yolov3.yaml +49 -0
  80. ultralytics/cfg/models/v5/yolov5-p6.yaml +62 -0
  81. ultralytics/cfg/models/v5/yolov5.yaml +51 -0
  82. ultralytics/cfg/models/v6/yolov6.yaml +56 -0
  83. ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +45 -0
  84. ultralytics/cfg/models/v8/yoloe-v8.yaml +45 -0
  85. ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +28 -0
  86. ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +28 -0
  87. ultralytics/cfg/models/v8/yolov8-cls.yaml +32 -0
  88. ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +58 -0
  89. ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +60 -0
  90. ultralytics/cfg/models/v8/yolov8-ghost.yaml +50 -0
  91. ultralytics/cfg/models/v8/yolov8-obb.yaml +49 -0
  92. ultralytics/cfg/models/v8/yolov8-p2.yaml +57 -0
  93. ultralytics/cfg/models/v8/yolov8-p6.yaml +59 -0
  94. ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +60 -0
  95. ultralytics/cfg/models/v8/yolov8-pose.yaml +50 -0
  96. ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +49 -0
  97. ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +59 -0
  98. ultralytics/cfg/models/v8/yolov8-seg.yaml +49 -0
  99. ultralytics/cfg/models/v8/yolov8-world.yaml +51 -0
  100. ultralytics/cfg/models/v8/yolov8-worldv2.yaml +49 -0
  101. ultralytics/cfg/models/v8/yolov8.yaml +49 -0
  102. ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
  103. ultralytics/cfg/models/v9/yolov9c.yaml +41 -0
  104. ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
  105. ultralytics/cfg/models/v9/yolov9e.yaml +64 -0
  106. ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
  107. ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
  108. ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
  109. ultralytics/cfg/trackers/botsort.yaml +22 -0
  110. ultralytics/cfg/trackers/bytetrack.yaml +14 -0
  111. ultralytics/data/__init__.py +26 -0
  112. ultralytics/data/annotator.py +66 -0
  113. ultralytics/data/augment.py +2945 -0
  114. ultralytics/data/base.py +438 -0
  115. ultralytics/data/build.py +258 -0
  116. ultralytics/data/converter.py +754 -0
  117. ultralytics/data/dataset.py +834 -0
  118. ultralytics/data/loaders.py +676 -0
  119. ultralytics/data/scripts/download_weights.sh +18 -0
  120. ultralytics/data/scripts/get_coco.sh +61 -0
  121. ultralytics/data/scripts/get_coco128.sh +18 -0
  122. ultralytics/data/scripts/get_imagenet.sh +52 -0
  123. ultralytics/data/split.py +125 -0
  124. ultralytics/data/split_dota.py +325 -0
  125. ultralytics/data/utils.py +777 -0
  126. ultralytics/engine/__init__.py +1 -0
  127. ultralytics/engine/exporter.py +1519 -0
  128. ultralytics/engine/model.py +1156 -0
  129. ultralytics/engine/predictor.py +502 -0
  130. ultralytics/engine/results.py +1840 -0
  131. ultralytics/engine/trainer.py +853 -0
  132. ultralytics/engine/tuner.py +243 -0
  133. ultralytics/engine/validator.py +377 -0
  134. ultralytics/hub/__init__.py +168 -0
  135. ultralytics/hub/auth.py +137 -0
  136. ultralytics/hub/google/__init__.py +176 -0
  137. ultralytics/hub/session.py +446 -0
  138. ultralytics/hub/utils.py +248 -0
  139. ultralytics/models/__init__.py +9 -0
  140. ultralytics/models/fastsam/__init__.py +7 -0
  141. ultralytics/models/fastsam/model.py +61 -0
  142. ultralytics/models/fastsam/predict.py +181 -0
  143. ultralytics/models/fastsam/utils.py +24 -0
  144. ultralytics/models/fastsam/val.py +40 -0
  145. ultralytics/models/nas/__init__.py +7 -0
  146. ultralytics/models/nas/model.py +102 -0
  147. ultralytics/models/nas/predict.py +58 -0
  148. ultralytics/models/nas/val.py +39 -0
  149. ultralytics/models/rtdetr/__init__.py +7 -0
  150. ultralytics/models/rtdetr/model.py +63 -0
  151. ultralytics/models/rtdetr/predict.py +84 -0
  152. ultralytics/models/rtdetr/train.py +85 -0
  153. ultralytics/models/rtdetr/val.py +191 -0
  154. ultralytics/models/sam/__init__.py +6 -0
  155. ultralytics/models/sam/amg.py +260 -0
  156. ultralytics/models/sam/build.py +358 -0
  157. ultralytics/models/sam/model.py +170 -0
  158. ultralytics/models/sam/modules/__init__.py +1 -0
  159. ultralytics/models/sam/modules/blocks.py +1129 -0
  160. ultralytics/models/sam/modules/decoders.py +515 -0
  161. ultralytics/models/sam/modules/encoders.py +854 -0
  162. ultralytics/models/sam/modules/memory_attention.py +299 -0
  163. ultralytics/models/sam/modules/sam.py +1006 -0
  164. ultralytics/models/sam/modules/tiny_encoder.py +1002 -0
  165. ultralytics/models/sam/modules/transformer.py +351 -0
  166. ultralytics/models/sam/modules/utils.py +394 -0
  167. ultralytics/models/sam/predict.py +1605 -0
  168. ultralytics/models/utils/__init__.py +1 -0
  169. ultralytics/models/utils/loss.py +455 -0
  170. ultralytics/models/utils/ops.py +268 -0
  171. ultralytics/models/yolo/__init__.py +7 -0
  172. ultralytics/models/yolo/classify/__init__.py +7 -0
  173. ultralytics/models/yolo/classify/predict.py +88 -0
  174. ultralytics/models/yolo/classify/train.py +233 -0
  175. ultralytics/models/yolo/classify/val.py +215 -0
  176. ultralytics/models/yolo/detect/__init__.py +7 -0
  177. ultralytics/models/yolo/detect/predict.py +124 -0
  178. ultralytics/models/yolo/detect/train.py +217 -0
  179. ultralytics/models/yolo/detect/val.py +451 -0
  180. ultralytics/models/yolo/model.py +354 -0
  181. ultralytics/models/yolo/obb/__init__.py +7 -0
  182. ultralytics/models/yolo/obb/predict.py +66 -0
  183. ultralytics/models/yolo/obb/train.py +81 -0
  184. ultralytics/models/yolo/obb/val.py +283 -0
  185. ultralytics/models/yolo/pose/__init__.py +7 -0
  186. ultralytics/models/yolo/pose/predict.py +79 -0
  187. ultralytics/models/yolo/pose/train.py +154 -0
  188. ultralytics/models/yolo/pose/val.py +394 -0
  189. ultralytics/models/yolo/segment/__init__.py +7 -0
  190. ultralytics/models/yolo/segment/predict.py +113 -0
  191. ultralytics/models/yolo/segment/train.py +123 -0
  192. ultralytics/models/yolo/segment/val.py +428 -0
  193. ultralytics/models/yolo/world/__init__.py +5 -0
  194. ultralytics/models/yolo/world/train.py +119 -0
  195. ultralytics/models/yolo/world/train_world.py +176 -0
  196. ultralytics/models/yolo/yoloe/__init__.py +22 -0
  197. ultralytics/models/yolo/yoloe/predict.py +169 -0
  198. ultralytics/models/yolo/yoloe/train.py +298 -0
  199. ultralytics/models/yolo/yoloe/train_seg.py +124 -0
  200. ultralytics/models/yolo/yoloe/val.py +191 -0
  201. ultralytics/nn/__init__.py +29 -0
  202. ultralytics/nn/autobackend.py +842 -0
  203. ultralytics/nn/modules/__init__.py +182 -0
  204. ultralytics/nn/modules/activation.py +53 -0
  205. ultralytics/nn/modules/block.py +1966 -0
  206. ultralytics/nn/modules/conv.py +712 -0
  207. ultralytics/nn/modules/head.py +880 -0
  208. ultralytics/nn/modules/transformer.py +713 -0
  209. ultralytics/nn/modules/utils.py +164 -0
  210. ultralytics/nn/tasks.py +1627 -0
  211. ultralytics/nn/text_model.py +351 -0
  212. ultralytics/solutions/__init__.py +41 -0
  213. ultralytics/solutions/ai_gym.py +116 -0
  214. ultralytics/solutions/analytics.py +252 -0
  215. ultralytics/solutions/config.py +106 -0
  216. ultralytics/solutions/distance_calculation.py +124 -0
  217. ultralytics/solutions/heatmap.py +127 -0
  218. ultralytics/solutions/instance_segmentation.py +84 -0
  219. ultralytics/solutions/object_blurrer.py +90 -0
  220. ultralytics/solutions/object_counter.py +195 -0
  221. ultralytics/solutions/object_cropper.py +84 -0
  222. ultralytics/solutions/parking_management.py +273 -0
  223. ultralytics/solutions/queue_management.py +93 -0
  224. ultralytics/solutions/region_counter.py +120 -0
  225. ultralytics/solutions/security_alarm.py +154 -0
  226. ultralytics/solutions/similarity_search.py +172 -0
  227. ultralytics/solutions/solutions.py +724 -0
  228. ultralytics/solutions/speed_estimation.py +110 -0
  229. ultralytics/solutions/streamlit_inference.py +196 -0
  230. ultralytics/solutions/templates/similarity-search.html +160 -0
  231. ultralytics/solutions/trackzone.py +88 -0
  232. ultralytics/solutions/vision_eye.py +68 -0
  233. ultralytics/trackers/__init__.py +7 -0
  234. ultralytics/trackers/basetrack.py +124 -0
  235. ultralytics/trackers/bot_sort.py +260 -0
  236. ultralytics/trackers/byte_tracker.py +480 -0
  237. ultralytics/trackers/track.py +125 -0
  238. ultralytics/trackers/utils/__init__.py +1 -0
  239. ultralytics/trackers/utils/gmc.py +376 -0
  240. ultralytics/trackers/utils/kalman_filter.py +493 -0
  241. ultralytics/trackers/utils/matching.py +157 -0
  242. ultralytics/utils/__init__.py +1435 -0
  243. ultralytics/utils/autobatch.py +106 -0
  244. ultralytics/utils/autodevice.py +174 -0
  245. ultralytics/utils/benchmarks.py +695 -0
  246. ultralytics/utils/callbacks/__init__.py +5 -0
  247. ultralytics/utils/callbacks/base.py +234 -0
  248. ultralytics/utils/callbacks/clearml.py +153 -0
  249. ultralytics/utils/callbacks/comet.py +552 -0
  250. ultralytics/utils/callbacks/dvc.py +205 -0
  251. ultralytics/utils/callbacks/hub.py +108 -0
  252. ultralytics/utils/callbacks/mlflow.py +138 -0
  253. ultralytics/utils/callbacks/neptune.py +140 -0
  254. ultralytics/utils/callbacks/raytune.py +43 -0
  255. ultralytics/utils/callbacks/tensorboard.py +132 -0
  256. ultralytics/utils/callbacks/wb.py +185 -0
  257. ultralytics/utils/checks.py +897 -0
  258. ultralytics/utils/dist.py +119 -0
  259. ultralytics/utils/downloads.py +499 -0
  260. ultralytics/utils/errors.py +43 -0
  261. ultralytics/utils/export.py +219 -0
  262. ultralytics/utils/files.py +221 -0
  263. ultralytics/utils/instance.py +499 -0
  264. ultralytics/utils/loss.py +813 -0
  265. ultralytics/utils/metrics.py +1356 -0
  266. ultralytics/utils/ops.py +885 -0
  267. ultralytics/utils/patches.py +143 -0
  268. ultralytics/utils/plotting.py +1011 -0
  269. ultralytics/utils/tal.py +416 -0
  270. ultralytics/utils/torch_utils.py +990 -0
  271. ultralytics/utils/triton.py +116 -0
  272. ultralytics/utils/tuner.py +159 -0
@@ -0,0 +1,880 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+ """Model head modules."""
3
+
4
+ import copy
5
+ import math
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+ from torch.nn.init import constant_, xavier_uniform_
11
+
12
+ from ultralytics.utils.tal import TORCH_1_10, dist2bbox, dist2rbox, make_anchors
13
+ from ultralytics.utils.torch_utils import fuse_conv_and_bn, smart_inference_mode
14
+
15
+ from .block import DFL, SAVPE, BNContrastiveHead, ContrastiveHead, Proto, Residual, SwiGLUFFN
16
+ from .conv import Conv, DWConv
17
+ from .transformer import MLP, DeformableTransformerDecoder, DeformableTransformerDecoderLayer
18
+ from .utils import bias_init_with_prob, linear_init
19
+
20
+ __all__ = "Detect", "Segment", "Pose", "Classify", "OBB", "RTDETRDecoder", "v10Detect", "YOLOEDetect", "YOLOESegment"
21
+
22
+
23
+ class Detect(nn.Module):
24
+ """YOLO Detect head for detection models."""
25
+
26
+ dynamic = False # force grid reconstruction
27
+ export = False # export mode
28
+ format = None # export format
29
+ end2end = False # end2end
30
+ max_det = 300 # max_det
31
+ shape = None
32
+ anchors = torch.empty(0) # init
33
+ strides = torch.empty(0) # init
34
+ legacy = False # backward compatibility for v3/v5/v8/v9 models
35
+ xyxy = False # xyxy or xywh output
36
+
37
+ def __init__(self, nc=80, ch=()):
38
+ """Initialize the YOLO detection layer with specified number of classes and channels."""
39
+ super().__init__()
40
+ self.nc = nc # number of classes
41
+ self.nl = len(ch) # number of detection layers
42
+ self.reg_max = 16 # DFL channels (ch[0] // 16 to scale 4/8/12/16/20 for n/s/m/l/x)
43
+ self.no = nc + self.reg_max * 4 # number of outputs per anchor
44
+ self.stride = torch.zeros(self.nl) # strides computed during build
45
+ c2, c3 = max((16, ch[0] // 4, self.reg_max * 4)), max(ch[0], min(self.nc, 100)) # channels
46
+ self.cv2 = nn.ModuleList(
47
+ nn.Sequential(Conv(x, c2, 3), Conv(c2, c2, 3), nn.Conv2d(c2, 4 * self.reg_max, 1)) for x in ch
48
+ )
49
+ self.cv3 = (
50
+ nn.ModuleList(nn.Sequential(Conv(x, c3, 3), Conv(c3, c3, 3), nn.Conv2d(c3, self.nc, 1)) for x in ch)
51
+ if self.legacy
52
+ else nn.ModuleList(
53
+ nn.Sequential(
54
+ nn.Sequential(DWConv(x, x, 3), Conv(x, c3, 1)),
55
+ nn.Sequential(DWConv(c3, c3, 3), Conv(c3, c3, 1)),
56
+ nn.Conv2d(c3, self.nc, 1),
57
+ )
58
+ for x in ch
59
+ )
60
+ )
61
+ self.dfl = DFL(self.reg_max) if self.reg_max > 1 else nn.Identity()
62
+
63
+ if self.end2end:
64
+ self.one2one_cv2 = copy.deepcopy(self.cv2)
65
+ self.one2one_cv3 = copy.deepcopy(self.cv3)
66
+
67
+ def forward(self, x):
68
+ """Concatenates and returns predicted bounding boxes and class probabilities."""
69
+ if self.end2end:
70
+ return self.forward_end2end(x)
71
+
72
+ for i in range(self.nl):
73
+ x[i] = torch.cat((self.cv2[i](x[i]), self.cv3[i](x[i])), 1)
74
+ if self.training: # Training path
75
+ return x
76
+ y = self._inference(x)
77
+ return y if self.export else (y, x)
78
+
79
+ def forward_end2end(self, x):
80
+ """
81
+ Performs forward pass of the v10Detect module.
82
+
83
+ Args:
84
+ x (List[torch.Tensor]): Input feature maps from different levels.
85
+
86
+ Returns:
87
+ (dict | tuple):
88
+
89
+ - If in training mode, returns a dictionary containing outputs of both one2many and one2one detections.
90
+ - If not in training mode, returns processed detections or a tuple with processed detections and raw outputs.
91
+ """
92
+ x_detach = [xi.detach() for xi in x]
93
+ one2one = [
94
+ torch.cat((self.one2one_cv2[i](x_detach[i]), self.one2one_cv3[i](x_detach[i])), 1) for i in range(self.nl)
95
+ ]
96
+ for i in range(self.nl):
97
+ x[i] = torch.cat((self.cv2[i](x[i]), self.cv3[i](x[i])), 1)
98
+ if self.training: # Training path
99
+ return {"one2many": x, "one2one": one2one}
100
+
101
+ y = self._inference(one2one)
102
+ y = self.postprocess(y.permute(0, 2, 1), self.max_det, self.nc)
103
+ return y if self.export else (y, {"one2many": x, "one2one": one2one})
104
+
105
+ def _inference(self, x):
106
+ """
107
+ Decode predicted bounding boxes and class probabilities based on multiple-level feature maps.
108
+
109
+ Args:
110
+ x (List[torch.Tensor]): List of feature maps from different detection layers.
111
+
112
+ Returns:
113
+ (torch.Tensor): Concatenated tensor of decoded bounding boxes and class probabilities.
114
+ """
115
+ # Inference path
116
+ shape = x[0].shape # BCHW
117
+ x_cat = torch.cat([xi.view(shape[0], self.no, -1) for xi in x], 2)
118
+ if self.format != "imx" and (self.dynamic or self.shape != shape):
119
+ self.anchors, self.strides = (x.transpose(0, 1) for x in make_anchors(x, self.stride, 0.5))
120
+ self.shape = shape
121
+
122
+ if self.export and self.format in {"saved_model", "pb", "tflite", "edgetpu", "tfjs"}: # avoid TF FlexSplitV ops
123
+ box = x_cat[:, : self.reg_max * 4]
124
+ cls = x_cat[:, self.reg_max * 4 :]
125
+ else:
126
+ box, cls = x_cat.split((self.reg_max * 4, self.nc), 1)
127
+
128
+ if self.export and self.format in {"tflite", "edgetpu"}:
129
+ # Precompute normalization factor to increase numerical stability
130
+ # See https://github.com/ultralytics/ultralytics/issues/7371
131
+ grid_h = shape[2]
132
+ grid_w = shape[3]
133
+ grid_size = torch.tensor([grid_w, grid_h, grid_w, grid_h], device=box.device).reshape(1, 4, 1)
134
+ norm = self.strides / (self.stride[0] * grid_size)
135
+ dbox = self.decode_bboxes(self.dfl(box) * norm, self.anchors.unsqueeze(0) * norm[:, :2])
136
+ elif self.export and self.format == "imx":
137
+ dbox = self.decode_bboxes(
138
+ self.dfl(box) * self.strides, self.anchors.unsqueeze(0) * self.strides, xywh=False
139
+ )
140
+ return dbox.transpose(1, 2), cls.sigmoid().permute(0, 2, 1)
141
+ else:
142
+ dbox = self.decode_bboxes(self.dfl(box), self.anchors.unsqueeze(0)) * self.strides
143
+
144
+ return torch.cat((dbox, cls.sigmoid()), 1)
145
+
146
+ def bias_init(self):
147
+ """Initialize Detect() biases, WARNING: requires stride availability."""
148
+ m = self # self.model[-1] # Detect() module
149
+ # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1
150
+ # ncf = math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # nominal class frequency
151
+ for a, b, s in zip(m.cv2, m.cv3, m.stride): # from
152
+ a[-1].bias.data[:] = 1.0 # box
153
+ b[-1].bias.data[: m.nc] = math.log(5 / m.nc / (640 / s) ** 2) # cls (.01 objects, 80 classes, 640 img)
154
+ if self.end2end:
155
+ for a, b, s in zip(m.one2one_cv2, m.one2one_cv3, m.stride): # from
156
+ a[-1].bias.data[:] = 1.0 # box
157
+ b[-1].bias.data[: m.nc] = math.log(5 / m.nc / (640 / s) ** 2) # cls (.01 objects, 80 classes, 640 img)
158
+
159
+ def decode_bboxes(self, bboxes, anchors, xywh=True):
160
+ """Decode bounding boxes."""
161
+ return dist2bbox(bboxes, anchors, xywh=xywh and not (self.end2end or self.xyxy), dim=1)
162
+
163
+ @staticmethod
164
+ def postprocess(preds: torch.Tensor, max_det: int, nc: int = 80):
165
+ """
166
+ Post-processes YOLO model predictions.
167
+
168
+ Args:
169
+ preds (torch.Tensor): Raw predictions with shape (batch_size, num_anchors, 4 + nc) with last dimension
170
+ format [x, y, w, h, class_probs].
171
+ max_det (int): Maximum detections per image.
172
+ nc (int, optional): Number of classes. Default: 80.
173
+
174
+ Returns:
175
+ (torch.Tensor): Processed predictions with shape (batch_size, min(max_det, num_anchors), 6) and last
176
+ dimension format [x, y, w, h, max_class_prob, class_index].
177
+ """
178
+ batch_size, anchors, _ = preds.shape # i.e. shape(16,8400,84)
179
+ boxes, scores = preds.split([4, nc], dim=-1)
180
+ index = scores.amax(dim=-1).topk(min(max_det, anchors))[1].unsqueeze(-1)
181
+ boxes = boxes.gather(dim=1, index=index.repeat(1, 1, 4))
182
+ scores = scores.gather(dim=1, index=index.repeat(1, 1, nc))
183
+ scores, index = scores.flatten(1).topk(min(max_det, anchors))
184
+ i = torch.arange(batch_size)[..., None] # batch indices
185
+ return torch.cat([boxes[i, index // nc], scores[..., None], (index % nc)[..., None].float()], dim=-1)
186
+
187
+
188
+ class Segment(Detect):
189
+ """YOLO Segment head for segmentation models."""
190
+
191
+ def __init__(self, nc=80, nm=32, npr=256, ch=()):
192
+ """Initialize the YOLO model attributes such as the number of masks, prototypes, and the convolution layers."""
193
+ super().__init__(nc, ch)
194
+ self.nm = nm # number of masks
195
+ self.npr = npr # number of protos
196
+ self.proto = Proto(ch[0], self.npr, self.nm) # protos
197
+
198
+ c4 = max(ch[0] // 4, self.nm)
199
+ self.cv4 = nn.ModuleList(nn.Sequential(Conv(x, c4, 3), Conv(c4, c4, 3), nn.Conv2d(c4, self.nm, 1)) for x in ch)
200
+
201
+ def forward(self, x):
202
+ """Return model outputs and mask coefficients if training, otherwise return outputs and mask coefficients."""
203
+ p = self.proto(x[0]) # mask protos
204
+ bs = p.shape[0] # batch size
205
+
206
+ mc = torch.cat([self.cv4[i](x[i]).view(bs, self.nm, -1) for i in range(self.nl)], 2) # mask coefficients
207
+ x = Detect.forward(self, x)
208
+ if self.training:
209
+ return x, mc, p
210
+ return (torch.cat([x, mc], 1), p) if self.export else (torch.cat([x[0], mc], 1), (x[1], mc, p))
211
+
212
+
213
+ class OBB(Detect):
214
+ """YOLO OBB detection head for detection with rotation models."""
215
+
216
+ def __init__(self, nc=80, ne=1, ch=()):
217
+ """Initialize OBB with number of classes `nc` and layer channels `ch`."""
218
+ super().__init__(nc, ch)
219
+ self.ne = ne # number of extra parameters
220
+
221
+ c4 = max(ch[0] // 4, self.ne)
222
+ self.cv4 = nn.ModuleList(nn.Sequential(Conv(x, c4, 3), Conv(c4, c4, 3), nn.Conv2d(c4, self.ne, 1)) for x in ch)
223
+
224
+ def forward(self, x):
225
+ """Concatenates and returns predicted bounding boxes and class probabilities."""
226
+ bs = x[0].shape[0] # batch size
227
+ angle = torch.cat([self.cv4[i](x[i]).view(bs, self.ne, -1) for i in range(self.nl)], 2) # OBB theta logits
228
+ # NOTE: set `angle` as an attribute so that `decode_bboxes` could use it.
229
+ angle = (angle.sigmoid() - 0.25) * math.pi # [-pi/4, 3pi/4]
230
+ # angle = angle.sigmoid() * math.pi / 2 # [0, pi/2]
231
+ if not self.training:
232
+ self.angle = angle
233
+ x = Detect.forward(self, x)
234
+ if self.training:
235
+ return x, angle
236
+ return torch.cat([x, angle], 1) if self.export else (torch.cat([x[0], angle], 1), (x[1], angle))
237
+
238
+ def decode_bboxes(self, bboxes, anchors):
239
+ """Decode rotated bounding boxes."""
240
+ return dist2rbox(bboxes, self.angle, anchors, dim=1)
241
+
242
+
243
+ class Pose(Detect):
244
+ """YOLO Pose head for keypoints models."""
245
+
246
+ def __init__(self, nc=80, kpt_shape=(17, 3), ch=()):
247
+ """Initialize YOLO network with default parameters and Convolutional Layers."""
248
+ super().__init__(nc, ch)
249
+ self.kpt_shape = kpt_shape # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible)
250
+ self.nk = kpt_shape[0] * kpt_shape[1] # number of keypoints total
251
+
252
+ c4 = max(ch[0] // 4, self.nk)
253
+ self.cv4 = nn.ModuleList(nn.Sequential(Conv(x, c4, 3), Conv(c4, c4, 3), nn.Conv2d(c4, self.nk, 1)) for x in ch)
254
+
255
+ def forward(self, x):
256
+ """Perform forward pass through YOLO model and return predictions."""
257
+ bs = x[0].shape[0] # batch size
258
+ 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)
259
+ x = Detect.forward(self, x)
260
+ if self.training:
261
+ return x, kpt
262
+ pred_kpt = self.kpts_decode(bs, kpt)
263
+ return torch.cat([x, pred_kpt], 1) if self.export else (torch.cat([x[0], pred_kpt], 1), (x[1], kpt))
264
+
265
+ def kpts_decode(self, bs, kpts):
266
+ """Decodes keypoints."""
267
+ ndim = self.kpt_shape[1]
268
+ if self.export:
269
+ if self.format in {
270
+ "tflite",
271
+ "edgetpu",
272
+ }: # required for TFLite export to avoid 'PLACEHOLDER_FOR_GREATER_OP_CODES' bug
273
+ # Precompute normalization factor to increase numerical stability
274
+ y = kpts.view(bs, *self.kpt_shape, -1)
275
+ grid_h, grid_w = self.shape[2], self.shape[3]
276
+ grid_size = torch.tensor([grid_w, grid_h], device=y.device).reshape(1, 2, 1)
277
+ norm = self.strides / (self.stride[0] * grid_size)
278
+ a = (y[:, :, :2] * 2.0 + (self.anchors - 0.5)) * norm
279
+ else:
280
+ # NCNN fix
281
+ y = kpts.view(bs, *self.kpt_shape, -1)
282
+ a = (y[:, :, :2] * 2.0 + (self.anchors - 0.5)) * self.strides
283
+ if ndim == 3:
284
+ a = torch.cat((a, y[:, :, 2:3].sigmoid()), 2)
285
+ return a.view(bs, self.nk, -1)
286
+ else:
287
+ y = kpts.clone()
288
+ if ndim == 3:
289
+ y[:, 2::ndim] = y[:, 2::ndim].sigmoid() # sigmoid (WARNING: inplace .sigmoid_() Apple MPS bug)
290
+ y[:, 0::ndim] = (y[:, 0::ndim] * 2.0 + (self.anchors[0] - 0.5)) * self.strides
291
+ y[:, 1::ndim] = (y[:, 1::ndim] * 2.0 + (self.anchors[1] - 0.5)) * self.strides
292
+ return y
293
+
294
+
295
+ class Classify(nn.Module):
296
+ """YOLO classification head, i.e. x(b,c1,20,20) to x(b,c2)."""
297
+
298
+ export = False # export mode
299
+
300
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1):
301
+ """Initializes YOLO classification head to transform input tensor from (b,c1,20,20) to (b,c2) shape."""
302
+ super().__init__()
303
+ c_ = 1280 # efficientnet_b0 size
304
+ self.conv = Conv(c1, c_, k, s, p, g)
305
+ self.pool = nn.AdaptiveAvgPool2d(1) # to x(b,c_,1,1)
306
+ self.drop = nn.Dropout(p=0.0, inplace=True)
307
+ self.linear = nn.Linear(c_, c2) # to x(b,c2)
308
+
309
+ def forward(self, x):
310
+ """Performs a forward pass of the YOLO model on input image data."""
311
+ if isinstance(x, list):
312
+ x = torch.cat(x, 1)
313
+ x = self.linear(self.drop(self.pool(self.conv(x)).flatten(1)))
314
+ if self.training:
315
+ return x
316
+ y = x.softmax(1) # get final output
317
+ return y if self.export else (y, x)
318
+
319
+
320
+ class WorldDetect(Detect):
321
+ """Head for integrating YOLO detection models with semantic understanding from text embeddings."""
322
+
323
+ def __init__(self, nc=80, embed=512, with_bn=False, ch=()):
324
+ """Initialize YOLO detection layer with nc classes and layer channels ch."""
325
+ super().__init__(nc, ch)
326
+ c3 = max(ch[0], min(self.nc, 100))
327
+ self.cv3 = nn.ModuleList(nn.Sequential(Conv(x, c3, 3), Conv(c3, c3, 3), nn.Conv2d(c3, embed, 1)) for x in ch)
328
+ self.cv4 = nn.ModuleList(BNContrastiveHead(embed) if with_bn else ContrastiveHead() for _ in ch)
329
+
330
+ def forward(self, x, text):
331
+ """Concatenates and returns predicted bounding boxes and class probabilities."""
332
+ for i in range(self.nl):
333
+ x[i] = torch.cat((self.cv2[i](x[i]), self.cv4[i](self.cv3[i](x[i]), text)), 1)
334
+ if self.training:
335
+ return x
336
+ self.no = self.nc + self.reg_max * 4 # self.nc could be changed when inference with different texts
337
+ y = self._inference(x)
338
+ return y if self.export else (y, x)
339
+
340
+ def bias_init(self):
341
+ """Initialize Detect() biases, WARNING: requires stride availability."""
342
+ m = self # self.model[-1] # Detect() module
343
+ # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1
344
+ # ncf = math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # nominal class frequency
345
+ for a, b, s in zip(m.cv2, m.cv3, m.stride): # from
346
+ a[-1].bias.data[:] = 1.0 # box
347
+ # b[-1].bias.data[:] = math.log(5 / m.nc / (640 / s) ** 2) # cls (.01 objects, 80 classes, 640 img)
348
+
349
+
350
+ class LRPCHead(nn.Module):
351
+ """Lightweight Region Proposal and Classification Head for efficient object detection."""
352
+
353
+ def __init__(self, vocab, pf, loc, enabled=True):
354
+ """Initialize LRPCHead with vocabulary, proposal filter, and localization components."""
355
+ super().__init__()
356
+ self.vocab = self.conv2linear(vocab) if enabled else vocab
357
+ self.pf = pf
358
+ self.loc = loc
359
+ self.enabled = enabled
360
+
361
+ def conv2linear(self, conv):
362
+ """Convert a 1x1 convolutional layer to a linear layer."""
363
+ assert isinstance(conv, nn.Conv2d) and conv.kernel_size == (1, 1)
364
+ linear = nn.Linear(conv.in_channels, conv.out_channels)
365
+ linear.weight.data = conv.weight.view(conv.out_channels, -1).data
366
+ linear.bias.data = conv.bias.data
367
+ return linear
368
+
369
+ def forward(self, cls_feat, loc_feat, conf):
370
+ """Process classification and localization features to generate detection proposals."""
371
+ if self.enabled:
372
+ pf_score = self.pf(cls_feat)[0, 0].flatten(0)
373
+ mask = pf_score.sigmoid() > conf
374
+ cls_feat = cls_feat.flatten(2).transpose(-1, -2)
375
+ cls_feat = self.vocab(cls_feat[:, mask] if conf else cls_feat * mask.unsqueeze(-1).int())
376
+ return (self.loc(loc_feat), cls_feat.transpose(-1, -2)), mask
377
+ else:
378
+ cls_feat = self.vocab(cls_feat)
379
+ loc_feat = self.loc(loc_feat)
380
+ return (loc_feat, cls_feat.flatten(2)), torch.ones(
381
+ cls_feat.shape[2] * cls_feat.shape[3], device=cls_feat.device, dtype=torch.bool
382
+ )
383
+
384
+
385
+ class YOLOEDetect(Detect):
386
+ """Head for integrating YOLO detection models with semantic understanding from text embeddings."""
387
+
388
+ is_fused = False
389
+
390
+ def __init__(self, nc=80, embed=512, with_bn=False, ch=()):
391
+ """Initialize YOLO detection layer with nc classes and layer channels ch."""
392
+ super().__init__(nc, ch)
393
+ c3 = max(ch[0], min(self.nc, 100))
394
+ assert c3 <= embed
395
+ assert with_bn is True
396
+ self.cv3 = (
397
+ nn.ModuleList(nn.Sequential(Conv(x, c3, 3), Conv(c3, c3, 3), nn.Conv2d(c3, embed, 1)) for x in ch)
398
+ if self.legacy
399
+ else nn.ModuleList(
400
+ nn.Sequential(
401
+ nn.Sequential(DWConv(x, x, 3), Conv(x, c3, 1)),
402
+ nn.Sequential(DWConv(c3, c3, 3), Conv(c3, c3, 1)),
403
+ nn.Conv2d(c3, embed, 1),
404
+ )
405
+ for x in ch
406
+ )
407
+ )
408
+
409
+ self.cv4 = nn.ModuleList(BNContrastiveHead(embed) if with_bn else ContrastiveHead() for _ in ch)
410
+
411
+ self.reprta = Residual(SwiGLUFFN(embed, embed))
412
+ self.savpe = SAVPE(ch, c3, embed)
413
+ self.embed = embed
414
+
415
+ @smart_inference_mode()
416
+ def fuse(self, txt_feats):
417
+ """Fuse text features with model weights for efficient inference."""
418
+ if self.is_fused:
419
+ return
420
+
421
+ assert not self.training
422
+ txt_feats = txt_feats.to(torch.float32).squeeze(0)
423
+ for cls_head, bn_head in zip(self.cv3, self.cv4):
424
+ assert isinstance(cls_head, nn.Sequential)
425
+ assert isinstance(bn_head, BNContrastiveHead)
426
+ conv = cls_head[-1]
427
+ assert isinstance(conv, nn.Conv2d)
428
+ logit_scale = bn_head.logit_scale
429
+ bias = bn_head.bias
430
+ norm = bn_head.norm
431
+
432
+ t = txt_feats * logit_scale.exp()
433
+ conv: nn.Conv2d = fuse_conv_and_bn(conv, norm)
434
+
435
+ w = conv.weight.data.squeeze(-1).squeeze(-1)
436
+ b = conv.bias.data
437
+
438
+ w = t @ w
439
+ b1 = (t @ b.reshape(-1).unsqueeze(-1)).squeeze(-1)
440
+ b2 = torch.ones_like(b1) * bias
441
+
442
+ conv = (
443
+ nn.Conv2d(
444
+ conv.in_channels,
445
+ w.shape[0],
446
+ kernel_size=1,
447
+ )
448
+ .requires_grad_(False)
449
+ .to(conv.weight.device)
450
+ )
451
+
452
+ conv.weight.data.copy_(w.unsqueeze(-1).unsqueeze(-1))
453
+ conv.bias.data.copy_(b1 + b2)
454
+ cls_head[-1] = conv
455
+
456
+ bn_head.fuse()
457
+
458
+ del self.reprta
459
+ self.reprta = nn.Identity()
460
+ self.is_fused = True
461
+
462
+ def get_tpe(self, tpe):
463
+ """Get text prompt embeddings with normalization."""
464
+ return None if tpe is None else F.normalize(self.reprta(tpe), dim=-1, p=2)
465
+
466
+ def get_vpe(self, x, vpe):
467
+ """Get visual prompt embeddings with spatial awareness."""
468
+ if vpe.shape[1] == 0: # no visual prompt embeddings
469
+ return torch.zeros(x[0].shape[0], 0, self.embed, device=x[0].device)
470
+ if vpe.ndim == 4: # (B, N, H, W)
471
+ vpe = self.savpe(x, vpe)
472
+ assert vpe.ndim == 3 # (B, N, D)
473
+ return vpe
474
+
475
+ def forward_lrpc(self, x, return_mask=False):
476
+ """Process features with fused text embeddings to generate detections for prompt-free model."""
477
+ masks = []
478
+ assert self.is_fused, "Prompt-free inference requires model to be fused!"
479
+ for i in range(self.nl):
480
+ cls_feat = self.cv3[i](x[i])
481
+ loc_feat = self.cv2[i](x[i])
482
+ assert isinstance(self.lrpc[i], LRPCHead)
483
+ x[i], mask = self.lrpc[i](
484
+ cls_feat, loc_feat, 0 if self.export and not self.dynamic else getattr(self, "conf", 0.001)
485
+ )
486
+ masks.append(mask)
487
+ shape = x[0][0].shape
488
+ if self.dynamic or self.shape != shape:
489
+ self.anchors, self.strides = (x.transpose(0, 1) for x in make_anchors([b[0] for b in x], self.stride, 0.5))
490
+ self.shape = shape
491
+ box = torch.cat([xi[0].view(shape[0], self.reg_max * 4, -1) for xi in x], 2)
492
+ cls = torch.cat([xi[1] for xi in x], 2)
493
+
494
+ if self.export and self.format in {"tflite", "edgetpu"}:
495
+ # Precompute normalization factor to increase numerical stability
496
+ # See https://github.com/ultralytics/ultralytics/issues/7371
497
+ grid_h = shape[2]
498
+ grid_w = shape[3]
499
+ grid_size = torch.tensor([grid_w, grid_h, grid_w, grid_h], device=box.device).reshape(1, 4, 1)
500
+ norm = self.strides / (self.stride[0] * grid_size)
501
+ dbox = self.decode_bboxes(self.dfl(box) * norm, self.anchors.unsqueeze(0) * norm[:, :2])
502
+ else:
503
+ dbox = self.decode_bboxes(self.dfl(box), self.anchors.unsqueeze(0)) * self.strides
504
+
505
+ mask = torch.cat(masks)
506
+ y = torch.cat((dbox if self.export and not self.dynamic else dbox[..., mask], cls.sigmoid()), 1)
507
+
508
+ if return_mask:
509
+ return (y, mask) if self.export else ((y, x), mask)
510
+ else:
511
+ return y if self.export else (y, x)
512
+
513
+ def forward(self, x, cls_pe, return_mask=False):
514
+ """Process features with class prompt embeddings to generate detections."""
515
+ if hasattr(self, "lrpc"): # for prompt-free inference
516
+ return self.forward_lrpc(x, return_mask)
517
+ for i in range(self.nl):
518
+ x[i] = torch.cat((self.cv2[i](x[i]), self.cv4[i](self.cv3[i](x[i]), cls_pe)), 1)
519
+ if self.training:
520
+ return x
521
+ self.no = self.nc + self.reg_max * 4 # self.nc could be changed when inference with different texts
522
+ y = self._inference(x)
523
+ return y if self.export else (y, x)
524
+
525
+ def bias_init(self):
526
+ """Initialize biases for detection heads."""
527
+ m = self # self.model[-1] # Detect() module
528
+ # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1
529
+ # ncf = math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # nominal class frequency
530
+ for a, b, c, s in zip(m.cv2, m.cv3, m.cv4, m.stride): # from
531
+ a[-1].bias.data[:] = 1.0 # box
532
+ # b[-1].bias.data[:] = math.log(5 / m.nc / (640 / s) ** 2) # cls (.01 objects, 80 classes, 640 img)
533
+ b[-1].bias.data[:] = 0.0
534
+ c.bias.data[:] = math.log(5 / m.nc / (640 / s) ** 2)
535
+
536
+
537
+ class YOLOESegment(YOLOEDetect):
538
+ """YOLO segmentation head with text embedding capabilities."""
539
+
540
+ def __init__(self, nc=80, nm=32, npr=256, embed=512, with_bn=False, ch=()):
541
+ """Initialize YOLOESegment with class count, mask parameters, and embedding dimensions."""
542
+ super().__init__(nc, embed, with_bn, ch)
543
+ self.nm = nm
544
+ self.npr = npr
545
+ self.proto = Proto(ch[0], self.npr, self.nm)
546
+
547
+ c5 = max(ch[0] // 4, self.nm)
548
+ self.cv5 = nn.ModuleList(nn.Sequential(Conv(x, c5, 3), Conv(c5, c5, 3), nn.Conv2d(c5, self.nm, 1)) for x in ch)
549
+
550
+ def forward(self, x, text):
551
+ """Return model outputs and mask coefficients if training, otherwise return outputs and mask coefficients."""
552
+ p = self.proto(x[0]) # mask protos
553
+ bs = p.shape[0] # batch size
554
+
555
+ mc = torch.cat([self.cv5[i](x[i]).view(bs, self.nm, -1) for i in range(self.nl)], 2) # mask coefficients
556
+ has_lrpc = hasattr(self, "lrpc")
557
+
558
+ if not has_lrpc:
559
+ x = YOLOEDetect.forward(self, x, text)
560
+ else:
561
+ x, mask = YOLOEDetect.forward(self, x, text, return_mask=True)
562
+
563
+ if self.training:
564
+ return x, mc, p
565
+
566
+ if has_lrpc:
567
+ mc = (mc * mask.int()) if self.export and not self.dynamic else mc[..., mask]
568
+
569
+ return (torch.cat([x, mc], 1), p) if self.export else (torch.cat([x[0], mc], 1), (x[1], mc, p))
570
+
571
+
572
+ class RTDETRDecoder(nn.Module):
573
+ """
574
+ Real-Time Deformable Transformer Decoder (RTDETRDecoder) module for object detection.
575
+
576
+ This decoder module utilizes Transformer architecture along with deformable convolutions to predict bounding boxes
577
+ and class labels for objects in an image. It integrates features from multiple layers and runs through a series of
578
+ Transformer decoder layers to output the final predictions.
579
+ """
580
+
581
+ export = False # export mode
582
+
583
+ def __init__(
584
+ self,
585
+ nc=80,
586
+ ch=(512, 1024, 2048),
587
+ hd=256, # hidden dim
588
+ nq=300, # num queries
589
+ ndp=4, # num decoder points
590
+ nh=8, # num head
591
+ ndl=6, # num decoder layers
592
+ d_ffn=1024, # dim of feedforward
593
+ dropout=0.0,
594
+ act=nn.ReLU(),
595
+ eval_idx=-1,
596
+ # Training args
597
+ nd=100, # num denoising
598
+ label_noise_ratio=0.5,
599
+ box_noise_scale=1.0,
600
+ learnt_init_query=False,
601
+ ):
602
+ """
603
+ Initializes the RTDETRDecoder module with the given parameters.
604
+
605
+ Args:
606
+ nc (int): Number of classes. Default is 80.
607
+ ch (tuple): Channels in the backbone feature maps. Default is (512, 1024, 2048).
608
+ hd (int): Dimension of hidden layers. Default is 256.
609
+ nq (int): Number of query points. Default is 300.
610
+ ndp (int): Number of decoder points. Default is 4.
611
+ nh (int): Number of heads in multi-head attention. Default is 8.
612
+ ndl (int): Number of decoder layers. Default is 6.
613
+ d_ffn (int): Dimension of the feed-forward networks. Default is 1024.
614
+ dropout (float): Dropout rate. Default is 0.0.
615
+ act (nn.Module): Activation function. Default is nn.ReLU.
616
+ eval_idx (int): Evaluation index. Default is -1.
617
+ nd (int): Number of denoising. Default is 100.
618
+ label_noise_ratio (float): Label noise ratio. Default is 0.5.
619
+ box_noise_scale (float): Box noise scale. Default is 1.0.
620
+ learnt_init_query (bool): Whether to learn initial query embeddings. Default is False.
621
+ """
622
+ super().__init__()
623
+ self.hidden_dim = hd
624
+ self.nhead = nh
625
+ self.nl = len(ch) # num level
626
+ self.nc = nc
627
+ self.num_queries = nq
628
+ self.num_decoder_layers = ndl
629
+
630
+ # Backbone feature projection
631
+ self.input_proj = nn.ModuleList(nn.Sequential(nn.Conv2d(x, hd, 1, bias=False), nn.BatchNorm2d(hd)) for x in ch)
632
+ # NOTE: simplified version but it's not consistent with .pt weights.
633
+ # self.input_proj = nn.ModuleList(Conv(x, hd, act=False) for x in ch)
634
+
635
+ # Transformer module
636
+ decoder_layer = DeformableTransformerDecoderLayer(hd, nh, d_ffn, dropout, act, self.nl, ndp)
637
+ self.decoder = DeformableTransformerDecoder(hd, decoder_layer, ndl, eval_idx)
638
+
639
+ # Denoising part
640
+ self.denoising_class_embed = nn.Embedding(nc, hd)
641
+ self.num_denoising = nd
642
+ self.label_noise_ratio = label_noise_ratio
643
+ self.box_noise_scale = box_noise_scale
644
+
645
+ # Decoder embedding
646
+ self.learnt_init_query = learnt_init_query
647
+ if learnt_init_query:
648
+ self.tgt_embed = nn.Embedding(nq, hd)
649
+ self.query_pos_head = MLP(4, 2 * hd, hd, num_layers=2)
650
+
651
+ # Encoder head
652
+ self.enc_output = nn.Sequential(nn.Linear(hd, hd), nn.LayerNorm(hd))
653
+ self.enc_score_head = nn.Linear(hd, nc)
654
+ self.enc_bbox_head = MLP(hd, hd, 4, num_layers=3)
655
+
656
+ # Decoder head
657
+ self.dec_score_head = nn.ModuleList([nn.Linear(hd, nc) for _ in range(ndl)])
658
+ self.dec_bbox_head = nn.ModuleList([MLP(hd, hd, 4, num_layers=3) for _ in range(ndl)])
659
+
660
+ self._reset_parameters()
661
+
662
+ def forward(self, x, batch=None):
663
+ """
664
+ Runs the forward pass of the module, returning bounding box and classification scores for the input.
665
+
666
+ Args:
667
+ x (List[torch.Tensor]): List of feature maps from the backbone.
668
+ batch (dict, optional): Batch information for training.
669
+
670
+ Returns:
671
+ (tuple | torch.Tensor): During training, returns a tuple of bounding boxes, scores, and other metadata.
672
+ During inference, returns a tensor of shape (bs, 300, 4+nc) containing bounding boxes and class scores.
673
+ """
674
+ from ultralytics.models.utils.ops import get_cdn_group
675
+
676
+ # Input projection and embedding
677
+ feats, shapes = self._get_encoder_input(x)
678
+
679
+ # Prepare denoising training
680
+ dn_embed, dn_bbox, attn_mask, dn_meta = get_cdn_group(
681
+ batch,
682
+ self.nc,
683
+ self.num_queries,
684
+ self.denoising_class_embed.weight,
685
+ self.num_denoising,
686
+ self.label_noise_ratio,
687
+ self.box_noise_scale,
688
+ self.training,
689
+ )
690
+
691
+ embed, refer_bbox, enc_bboxes, enc_scores = self._get_decoder_input(feats, shapes, dn_embed, dn_bbox)
692
+
693
+ # Decoder
694
+ dec_bboxes, dec_scores = self.decoder(
695
+ embed,
696
+ refer_bbox,
697
+ feats,
698
+ shapes,
699
+ self.dec_bbox_head,
700
+ self.dec_score_head,
701
+ self.query_pos_head,
702
+ attn_mask=attn_mask,
703
+ )
704
+ x = dec_bboxes, dec_scores, enc_bboxes, enc_scores, dn_meta
705
+ if self.training:
706
+ return x
707
+ # (bs, 300, 4+nc)
708
+ y = torch.cat((dec_bboxes.squeeze(0), dec_scores.squeeze(0).sigmoid()), -1)
709
+ return y if self.export else (y, x)
710
+
711
+ def _generate_anchors(self, shapes, grid_size=0.05, dtype=torch.float32, device="cpu", eps=1e-2):
712
+ """
713
+ Generates anchor bounding boxes for given shapes with specific grid size and validates them.
714
+
715
+ Args:
716
+ shapes (list): List of feature map shapes.
717
+ grid_size (float, optional): Base size of grid cells. Default is 0.05.
718
+ dtype (torch.dtype, optional): Data type for tensors. Default is torch.float32.
719
+ device (str, optional): Device to create tensors on. Default is "cpu".
720
+ eps (float, optional): Small value for numerical stability. Default is 1e-2.
721
+
722
+ Returns:
723
+ (tuple): Tuple containing anchors and valid mask tensors.
724
+ """
725
+ anchors = []
726
+ for i, (h, w) in enumerate(shapes):
727
+ sy = torch.arange(end=h, dtype=dtype, device=device)
728
+ sx = torch.arange(end=w, dtype=dtype, device=device)
729
+ grid_y, grid_x = torch.meshgrid(sy, sx, indexing="ij") if TORCH_1_10 else torch.meshgrid(sy, sx)
730
+ grid_xy = torch.stack([grid_x, grid_y], -1) # (h, w, 2)
731
+
732
+ valid_WH = torch.tensor([w, h], dtype=dtype, device=device)
733
+ grid_xy = (grid_xy.unsqueeze(0) + 0.5) / valid_WH # (1, h, w, 2)
734
+ wh = torch.ones_like(grid_xy, dtype=dtype, device=device) * grid_size * (2.0**i)
735
+ anchors.append(torch.cat([grid_xy, wh], -1).view(-1, h * w, 4)) # (1, h*w, 4)
736
+
737
+ anchors = torch.cat(anchors, 1) # (1, h*w*nl, 4)
738
+ valid_mask = ((anchors > eps) & (anchors < 1 - eps)).all(-1, keepdim=True) # 1, h*w*nl, 1
739
+ anchors = torch.log(anchors / (1 - anchors))
740
+ anchors = anchors.masked_fill(~valid_mask, float("inf"))
741
+ return anchors, valid_mask
742
+
743
+ def _get_encoder_input(self, x):
744
+ """
745
+ Processes and returns encoder inputs by getting projection features from input and concatenating them.
746
+
747
+ Args:
748
+ x (List[torch.Tensor]): List of feature maps from the backbone.
749
+
750
+ Returns:
751
+ (tuple): Tuple containing processed features and their shapes.
752
+ """
753
+ # Get projection features
754
+ x = [self.input_proj[i](feat) for i, feat in enumerate(x)]
755
+ # Get encoder inputs
756
+ feats = []
757
+ shapes = []
758
+ for feat in x:
759
+ h, w = feat.shape[2:]
760
+ # [b, c, h, w] -> [b, h*w, c]
761
+ feats.append(feat.flatten(2).permute(0, 2, 1))
762
+ # [nl, 2]
763
+ shapes.append([h, w])
764
+
765
+ # [b, h*w, c]
766
+ feats = torch.cat(feats, 1)
767
+ return feats, shapes
768
+
769
+ def _get_decoder_input(self, feats, shapes, dn_embed=None, dn_bbox=None):
770
+ """
771
+ Generates and prepares the input required for the decoder from the provided features and shapes.
772
+
773
+ Args:
774
+ feats (torch.Tensor): Processed features from encoder.
775
+ shapes (list): List of feature map shapes.
776
+ dn_embed (torch.Tensor, optional): Denoising embeddings. Default is None.
777
+ dn_bbox (torch.Tensor, optional): Denoising bounding boxes. Default is None.
778
+
779
+ Returns:
780
+ (tuple): Tuple containing embeddings, reference bounding boxes, encoded bounding boxes, and scores.
781
+ """
782
+ bs = feats.shape[0]
783
+ # Prepare input for decoder
784
+ anchors, valid_mask = self._generate_anchors(shapes, dtype=feats.dtype, device=feats.device)
785
+ features = self.enc_output(valid_mask * feats) # bs, h*w, 256
786
+
787
+ enc_outputs_scores = self.enc_score_head(features) # (bs, h*w, nc)
788
+
789
+ # Query selection
790
+ # (bs, num_queries)
791
+ topk_ind = torch.topk(enc_outputs_scores.max(-1).values, self.num_queries, dim=1).indices.view(-1)
792
+ # (bs, num_queries)
793
+ batch_ind = torch.arange(end=bs, dtype=topk_ind.dtype).unsqueeze(-1).repeat(1, self.num_queries).view(-1)
794
+
795
+ # (bs, num_queries, 256)
796
+ top_k_features = features[batch_ind, topk_ind].view(bs, self.num_queries, -1)
797
+ # (bs, num_queries, 4)
798
+ top_k_anchors = anchors[:, topk_ind].view(bs, self.num_queries, -1)
799
+
800
+ # Dynamic anchors + static content
801
+ refer_bbox = self.enc_bbox_head(top_k_features) + top_k_anchors
802
+
803
+ enc_bboxes = refer_bbox.sigmoid()
804
+ if dn_bbox is not None:
805
+ refer_bbox = torch.cat([dn_bbox, refer_bbox], 1)
806
+ enc_scores = enc_outputs_scores[batch_ind, topk_ind].view(bs, self.num_queries, -1)
807
+
808
+ embeddings = self.tgt_embed.weight.unsqueeze(0).repeat(bs, 1, 1) if self.learnt_init_query else top_k_features
809
+ if self.training:
810
+ refer_bbox = refer_bbox.detach()
811
+ if not self.learnt_init_query:
812
+ embeddings = embeddings.detach()
813
+ if dn_embed is not None:
814
+ embeddings = torch.cat([dn_embed, embeddings], 1)
815
+
816
+ return embeddings, refer_bbox, enc_bboxes, enc_scores
817
+
818
+ def _reset_parameters(self):
819
+ """Initializes or resets the parameters of the model's various components with predefined weights and biases."""
820
+ # Class and bbox head init
821
+ bias_cls = bias_init_with_prob(0.01) / 80 * self.nc
822
+ # NOTE: the weight initialization in `linear_init` would cause NaN when training with custom datasets.
823
+ # linear_init(self.enc_score_head)
824
+ constant_(self.enc_score_head.bias, bias_cls)
825
+ constant_(self.enc_bbox_head.layers[-1].weight, 0.0)
826
+ constant_(self.enc_bbox_head.layers[-1].bias, 0.0)
827
+ for cls_, reg_ in zip(self.dec_score_head, self.dec_bbox_head):
828
+ # linear_init(cls_)
829
+ constant_(cls_.bias, bias_cls)
830
+ constant_(reg_.layers[-1].weight, 0.0)
831
+ constant_(reg_.layers[-1].bias, 0.0)
832
+
833
+ linear_init(self.enc_output[0])
834
+ xavier_uniform_(self.enc_output[0].weight)
835
+ if self.learnt_init_query:
836
+ xavier_uniform_(self.tgt_embed.weight)
837
+ xavier_uniform_(self.query_pos_head.layers[0].weight)
838
+ xavier_uniform_(self.query_pos_head.layers[1].weight)
839
+ for layer in self.input_proj:
840
+ xavier_uniform_(layer[0].weight)
841
+
842
+
843
+ class v10Detect(Detect):
844
+ """
845
+ v10 Detection head from https://arxiv.org/pdf/2405.14458.
846
+
847
+ Args:
848
+ nc (int): Number of classes.
849
+ ch (tuple): Tuple of channel sizes.
850
+
851
+ Attributes:
852
+ max_det (int): Maximum number of detections.
853
+
854
+ Methods:
855
+ __init__(self, nc=80, ch=()): Initializes the v10Detect object.
856
+ forward(self, x): Performs forward pass of the v10Detect module.
857
+ bias_init(self): Initializes biases of the Detect module.
858
+
859
+ """
860
+
861
+ end2end = True
862
+
863
+ def __init__(self, nc=80, ch=()):
864
+ """Initializes the v10Detect object with the specified number of classes and input channels."""
865
+ super().__init__(nc, ch)
866
+ c3 = max(ch[0], min(self.nc, 100)) # channels
867
+ # Light cls head
868
+ self.cv3 = nn.ModuleList(
869
+ nn.Sequential(
870
+ nn.Sequential(Conv(x, x, 3, g=x), Conv(x, c3, 1)),
871
+ nn.Sequential(Conv(c3, c3, 3, g=c3), Conv(c3, c3, 1)),
872
+ nn.Conv2d(c3, self.nc, 1),
873
+ )
874
+ for x in ch
875
+ )
876
+ self.one2one_cv3 = copy.deepcopy(self.cv3)
877
+
878
+ def fuse(self):
879
+ """Removes the one2many head."""
880
+ self.cv2 = self.cv3 = nn.ModuleList([nn.Identity()] * self.nl)