dgenerate-ultralytics-headless 8.3.143__py3-none-any.whl → 8.3.144__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 (148) hide show
  1. {dgenerate_ultralytics_headless-8.3.143.dist-info → dgenerate_ultralytics_headless-8.3.144.dist-info}/METADATA +1 -1
  2. dgenerate_ultralytics_headless-8.3.144.dist-info/RECORD +272 -0
  3. tests/conftest.py +7 -24
  4. tests/test_cli.py +1 -1
  5. tests/test_cuda.py +7 -2
  6. tests/test_engine.py +7 -8
  7. tests/test_exports.py +16 -16
  8. tests/test_integrations.py +1 -1
  9. tests/test_solutions.py +11 -11
  10. ultralytics/__init__.py +1 -1
  11. ultralytics/cfg/__init__.py +16 -13
  12. ultralytics/data/annotator.py +6 -5
  13. ultralytics/data/augment.py +127 -126
  14. ultralytics/data/base.py +54 -51
  15. ultralytics/data/build.py +47 -23
  16. ultralytics/data/converter.py +47 -43
  17. ultralytics/data/dataset.py +51 -50
  18. ultralytics/data/loaders.py +77 -44
  19. ultralytics/data/split.py +22 -9
  20. ultralytics/data/split_dota.py +63 -39
  21. ultralytics/data/utils.py +59 -39
  22. ultralytics/engine/exporter.py +79 -27
  23. ultralytics/engine/model.py +39 -39
  24. ultralytics/engine/predictor.py +37 -28
  25. ultralytics/engine/results.py +187 -157
  26. ultralytics/engine/trainer.py +36 -19
  27. ultralytics/engine/tuner.py +12 -9
  28. ultralytics/engine/validator.py +7 -9
  29. ultralytics/hub/__init__.py +11 -13
  30. ultralytics/hub/auth.py +22 -2
  31. ultralytics/hub/google/__init__.py +19 -19
  32. ultralytics/hub/session.py +37 -51
  33. ultralytics/hub/utils.py +19 -5
  34. ultralytics/models/fastsam/model.py +30 -12
  35. ultralytics/models/fastsam/predict.py +5 -6
  36. ultralytics/models/fastsam/utils.py +3 -3
  37. ultralytics/models/fastsam/val.py +10 -6
  38. ultralytics/models/nas/model.py +9 -5
  39. ultralytics/models/nas/predict.py +6 -6
  40. ultralytics/models/nas/val.py +3 -3
  41. ultralytics/models/rtdetr/model.py +7 -6
  42. ultralytics/models/rtdetr/predict.py +14 -7
  43. ultralytics/models/rtdetr/train.py +10 -4
  44. ultralytics/models/rtdetr/val.py +36 -9
  45. ultralytics/models/sam/amg.py +30 -12
  46. ultralytics/models/sam/build.py +22 -22
  47. ultralytics/models/sam/model.py +10 -9
  48. ultralytics/models/sam/modules/blocks.py +76 -80
  49. ultralytics/models/sam/modules/decoders.py +6 -8
  50. ultralytics/models/sam/modules/encoders.py +23 -26
  51. ultralytics/models/sam/modules/memory_attention.py +13 -1
  52. ultralytics/models/sam/modules/sam.py +57 -26
  53. ultralytics/models/sam/modules/tiny_encoder.py +232 -237
  54. ultralytics/models/sam/modules/transformer.py +13 -13
  55. ultralytics/models/sam/modules/utils.py +11 -19
  56. ultralytics/models/sam/predict.py +114 -101
  57. ultralytics/models/utils/loss.py +98 -77
  58. ultralytics/models/utils/ops.py +116 -67
  59. ultralytics/models/yolo/classify/predict.py +5 -5
  60. ultralytics/models/yolo/classify/train.py +32 -28
  61. ultralytics/models/yolo/classify/val.py +7 -8
  62. ultralytics/models/yolo/detect/predict.py +1 -0
  63. ultralytics/models/yolo/detect/train.py +15 -14
  64. ultralytics/models/yolo/detect/val.py +37 -36
  65. ultralytics/models/yolo/model.py +106 -23
  66. ultralytics/models/yolo/obb/predict.py +3 -4
  67. ultralytics/models/yolo/obb/train.py +14 -6
  68. ultralytics/models/yolo/obb/val.py +29 -23
  69. ultralytics/models/yolo/pose/predict.py +9 -8
  70. ultralytics/models/yolo/pose/train.py +24 -16
  71. ultralytics/models/yolo/pose/val.py +44 -26
  72. ultralytics/models/yolo/segment/predict.py +5 -5
  73. ultralytics/models/yolo/segment/train.py +11 -7
  74. ultralytics/models/yolo/segment/val.py +2 -2
  75. ultralytics/models/yolo/world/train.py +33 -23
  76. ultralytics/models/yolo/world/train_world.py +11 -3
  77. ultralytics/models/yolo/yoloe/predict.py +11 -11
  78. ultralytics/models/yolo/yoloe/train.py +73 -21
  79. ultralytics/models/yolo/yoloe/train_seg.py +10 -7
  80. ultralytics/models/yolo/yoloe/val.py +42 -18
  81. ultralytics/nn/autobackend.py +59 -15
  82. ultralytics/nn/modules/__init__.py +4 -4
  83. ultralytics/nn/modules/activation.py +4 -1
  84. ultralytics/nn/modules/block.py +178 -111
  85. ultralytics/nn/modules/conv.py +6 -5
  86. ultralytics/nn/modules/head.py +469 -121
  87. ultralytics/nn/modules/transformer.py +147 -58
  88. ultralytics/nn/tasks.py +227 -20
  89. ultralytics/nn/text_model.py +30 -33
  90. ultralytics/solutions/ai_gym.py +1 -1
  91. ultralytics/solutions/analytics.py +7 -4
  92. ultralytics/solutions/config.py +10 -10
  93. ultralytics/solutions/distance_calculation.py +11 -10
  94. ultralytics/solutions/heatmap.py +1 -1
  95. ultralytics/solutions/instance_segmentation.py +6 -3
  96. ultralytics/solutions/object_blurrer.py +3 -3
  97. ultralytics/solutions/object_counter.py +15 -7
  98. ultralytics/solutions/object_cropper.py +3 -2
  99. ultralytics/solutions/parking_management.py +29 -28
  100. ultralytics/solutions/queue_management.py +6 -6
  101. ultralytics/solutions/region_counter.py +10 -3
  102. ultralytics/solutions/security_alarm.py +3 -3
  103. ultralytics/solutions/similarity_search.py +85 -24
  104. ultralytics/solutions/solutions.py +184 -75
  105. ultralytics/solutions/speed_estimation.py +28 -22
  106. ultralytics/solutions/streamlit_inference.py +17 -12
  107. ultralytics/solutions/trackzone.py +4 -4
  108. ultralytics/trackers/basetrack.py +16 -23
  109. ultralytics/trackers/bot_sort.py +30 -20
  110. ultralytics/trackers/byte_tracker.py +70 -64
  111. ultralytics/trackers/track.py +4 -8
  112. ultralytics/trackers/utils/gmc.py +31 -58
  113. ultralytics/trackers/utils/kalman_filter.py +37 -37
  114. ultralytics/trackers/utils/matching.py +1 -1
  115. ultralytics/utils/__init__.py +105 -89
  116. ultralytics/utils/autobatch.py +16 -3
  117. ultralytics/utils/autodevice.py +54 -24
  118. ultralytics/utils/benchmarks.py +42 -28
  119. ultralytics/utils/callbacks/base.py +3 -3
  120. ultralytics/utils/callbacks/clearml.py +9 -9
  121. ultralytics/utils/callbacks/comet.py +67 -25
  122. ultralytics/utils/callbacks/dvc.py +7 -10
  123. ultralytics/utils/callbacks/mlflow.py +2 -5
  124. ultralytics/utils/callbacks/neptune.py +7 -13
  125. ultralytics/utils/callbacks/raytune.py +1 -1
  126. ultralytics/utils/callbacks/tensorboard.py +5 -6
  127. ultralytics/utils/callbacks/wb.py +14 -14
  128. ultralytics/utils/checks.py +14 -13
  129. ultralytics/utils/dist.py +5 -5
  130. ultralytics/utils/downloads.py +94 -67
  131. ultralytics/utils/errors.py +5 -5
  132. ultralytics/utils/export.py +61 -47
  133. ultralytics/utils/files.py +23 -22
  134. ultralytics/utils/instance.py +48 -52
  135. ultralytics/utils/loss.py +78 -40
  136. ultralytics/utils/metrics.py +186 -130
  137. ultralytics/utils/ops.py +186 -190
  138. ultralytics/utils/patches.py +15 -17
  139. ultralytics/utils/plotting.py +71 -27
  140. ultralytics/utils/tal.py +21 -15
  141. ultralytics/utils/torch_utils.py +53 -50
  142. ultralytics/utils/triton.py +5 -4
  143. ultralytics/utils/tuner.py +5 -5
  144. dgenerate_ultralytics_headless-8.3.143.dist-info/RECORD +0 -272
  145. {dgenerate_ultralytics_headless-8.3.143.dist-info → dgenerate_ultralytics_headless-8.3.144.dist-info}/WHEEL +0 -0
  146. {dgenerate_ultralytics_headless-8.3.143.dist-info → dgenerate_ultralytics_headless-8.3.144.dist-info}/entry_points.txt +0 -0
  147. {dgenerate_ultralytics_headless-8.3.143.dist-info → dgenerate_ultralytics_headless-8.3.144.dist-info}/licenses/LICENSE +0 -0
  148. {dgenerate_ultralytics_headless-8.3.143.dist-info → dgenerate_ultralytics_headless-8.3.144.dist-info}/top_level.txt +0 -0
@@ -3,6 +3,7 @@
3
3
 
4
4
  import copy
5
5
  import math
6
+ from typing import List, Optional, Tuple, Union
6
7
 
7
8
  import torch
8
9
  import torch.nn as nn
@@ -21,7 +22,47 @@ __all__ = "Detect", "Segment", "Pose", "Classify", "OBB", "RTDETRDecoder", "v10D
21
22
 
22
23
 
23
24
  class Detect(nn.Module):
24
- """YOLO Detect head for detection models."""
25
+ """
26
+ YOLO Detect head for object detection models.
27
+
28
+ This class implements the detection head used in YOLO models for predicting bounding boxes and class probabilities.
29
+ It supports both training and inference modes, with optional end-to-end detection capabilities.
30
+
31
+ Attributes:
32
+ dynamic (bool): Force grid reconstruction.
33
+ export (bool): Export mode flag.
34
+ format (str): Export format.
35
+ end2end (bool): End-to-end detection mode.
36
+ max_det (int): Maximum detections per image.
37
+ shape (tuple): Input shape.
38
+ anchors (torch.Tensor): Anchor points.
39
+ strides (torch.Tensor): Feature map strides.
40
+ legacy (bool): Backward compatibility for v3/v5/v8/v9 models.
41
+ xyxy (bool): Output format, xyxy or xywh.
42
+ nc (int): Number of classes.
43
+ nl (int): Number of detection layers.
44
+ reg_max (int): DFL channels.
45
+ no (int): Number of outputs per anchor.
46
+ stride (torch.Tensor): Strides computed during build.
47
+ cv2 (nn.ModuleList): Convolution layers for box regression.
48
+ cv3 (nn.ModuleList): Convolution layers for classification.
49
+ dfl (nn.Module): Distribution Focal Loss layer.
50
+ one2one_cv2 (nn.ModuleList): One-to-one convolution layers for box regression.
51
+ one2one_cv3 (nn.ModuleList): One-to-one convolution layers for classification.
52
+
53
+ Methods:
54
+ forward: Perform forward pass and return predictions.
55
+ forward_end2end: Perform forward pass for end-to-end detection.
56
+ bias_init: Initialize detection head biases.
57
+ decode_bboxes: Decode bounding boxes from predictions.
58
+ postprocess: Post-process model predictions.
59
+
60
+ Examples:
61
+ Create a detection head for 80 classes
62
+ >>> detect = Detect(nc=80, ch=(256, 512, 1024))
63
+ >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)]
64
+ >>> outputs = detect(x)
65
+ """
25
66
 
26
67
  dynamic = False # force grid reconstruction
27
68
  export = False # export mode
@@ -34,8 +75,14 @@ class Detect(nn.Module):
34
75
  legacy = False # backward compatibility for v3/v5/v8/v9 models
35
76
  xyxy = False # xyxy or xywh output
36
77
 
37
- def __init__(self, nc=80, ch=()):
38
- """Initialize the YOLO detection layer with specified number of classes and channels."""
78
+ def __init__(self, nc: int = 80, ch: Tuple = ()):
79
+ """
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
+ """
39
86
  super().__init__()
40
87
  self.nc = nc # number of classes
41
88
  self.nl = len(ch) # number of detection layers
@@ -64,8 +111,8 @@ class Detect(nn.Module):
64
111
  self.one2one_cv2 = copy.deepcopy(self.cv2)
65
112
  self.one2one_cv3 = copy.deepcopy(self.cv3)
66
113
 
67
- def forward(self, x):
68
- """Concatenates and returns predicted bounding boxes and class probabilities."""
114
+ def forward(self, x: List[torch.Tensor]) -> Union[List[torch.Tensor], Tuple]:
115
+ """Concatenate and return predicted bounding boxes and class probabilities."""
69
116
  if self.end2end:
70
117
  return self.forward_end2end(x)
71
118
 
@@ -76,18 +123,16 @@ class Detect(nn.Module):
76
123
  y = self._inference(x)
77
124
  return y if self.export else (y, x)
78
125
 
79
- def forward_end2end(self, x):
126
+ def forward_end2end(self, x: List[torch.Tensor]) -> Union[dict, Tuple]:
80
127
  """
81
- Performs forward pass of the v10Detect module.
128
+ Perform forward pass of the v10Detect module.
82
129
 
83
130
  Args:
84
131
  x (List[torch.Tensor]): Input feature maps from different levels.
85
132
 
86
133
  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.
134
+ outputs (dict | tuple): Training mode returns dict with one2many and one2one outputs.
135
+ Inference mode returns processed detections or tuple with detections and raw outputs.
91
136
  """
92
137
  x_detach = [xi.detach() for xi in x]
93
138
  one2one = [
@@ -102,7 +147,7 @@ class Detect(nn.Module):
102
147
  y = self.postprocess(y.permute(0, 2, 1), self.max_det, self.nc)
103
148
  return y if self.export else (y, {"one2many": x, "one2one": one2one})
104
149
 
105
- def _inference(self, x):
150
+ def _inference(self, x: List[torch.Tensor]) -> torch.Tensor:
106
151
  """
107
152
  Decode predicted bounding boxes and class probabilities based on multiple-level feature maps.
108
153
 
@@ -156,20 +201,20 @@ class Detect(nn.Module):
156
201
  a[-1].bias.data[:] = 1.0 # box
157
202
  b[-1].bias.data[: m.nc] = math.log(5 / m.nc / (640 / s) ** 2) # cls (.01 objects, 80 classes, 640 img)
158
203
 
159
- def decode_bboxes(self, bboxes, anchors, xywh=True):
160
- """Decode bounding boxes."""
204
+ def decode_bboxes(self, bboxes: torch.Tensor, anchors: torch.Tensor, xywh: bool = True) -> torch.Tensor:
205
+ """Decode bounding boxes from predictions."""
161
206
  return dist2bbox(bboxes, anchors, xywh=xywh and not (self.end2end or self.xyxy), dim=1)
162
207
 
163
208
  @staticmethod
164
- def postprocess(preds: torch.Tensor, max_det: int, nc: int = 80):
209
+ def postprocess(preds: torch.Tensor, max_det: int, nc: int = 80) -> torch.Tensor:
165
210
  """
166
- Post-processes YOLO model predictions.
211
+ Post-process YOLO model predictions.
167
212
 
168
213
  Args:
169
214
  preds (torch.Tensor): Raw predictions with shape (batch_size, num_anchors, 4 + nc) with last dimension
170
215
  format [x, y, w, h, class_probs].
171
216
  max_det (int): Maximum detections per image.
172
- nc (int, optional): Number of classes. Default: 80.
217
+ nc (int, optional): Number of classes.
173
218
 
174
219
  Returns:
175
220
  (torch.Tensor): Processed predictions with shape (batch_size, min(max_det, num_anchors), 6) and last
@@ -186,10 +231,37 @@ class Detect(nn.Module):
186
231
 
187
232
 
188
233
  class Segment(Detect):
189
- """YOLO Segment head for segmentation models."""
234
+ """
235
+ YOLO Segment head for segmentation models.
236
+
237
+ This class extends the Detect head to include mask prediction capabilities for instance segmentation tasks.
190
238
 
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."""
239
+ Attributes:
240
+ nm (int): Number of masks.
241
+ npr (int): Number of protos.
242
+ proto (Proto): Prototype generation module.
243
+ cv4 (nn.ModuleList): Convolution layers for mask coefficients.
244
+
245
+ Methods:
246
+ forward: Return model outputs and mask coefficients.
247
+
248
+ Examples:
249
+ Create a segmentation head
250
+ >>> segment = Segment(nc=80, nm=32, npr=256, ch=(256, 512, 1024))
251
+ >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)]
252
+ >>> outputs = segment(x)
253
+ """
254
+
255
+ def __init__(self, nc: int = 80, nm: int = 32, npr: int = 256, ch: Tuple = ()):
256
+ """
257
+ Initialize the YOLO model attributes such as the number of masks, prototypes, and the convolution layers.
258
+
259
+ Args:
260
+ nc (int): Number of classes.
261
+ nm (int): Number of masks.
262
+ npr (int): Number of protos.
263
+ ch (tuple): Tuple of channel sizes from backbone feature maps.
264
+ """
193
265
  super().__init__(nc, ch)
194
266
  self.nm = nm # number of masks
195
267
  self.npr = npr # number of protos
@@ -198,7 +270,7 @@ class Segment(Detect):
198
270
  c4 = max(ch[0] // 4, self.nm)
199
271
  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
272
 
201
- def forward(self, x):
273
+ def forward(self, x: List[torch.Tensor]) -> Union[Tuple, List[torch.Tensor]]:
202
274
  """Return model outputs and mask coefficients if training, otherwise return outputs and mask coefficients."""
203
275
  p = self.proto(x[0]) # mask protos
204
276
  bs = p.shape[0] # batch size
@@ -211,18 +283,44 @@ class Segment(Detect):
211
283
 
212
284
 
213
285
  class OBB(Detect):
214
- """YOLO OBB detection head for detection with rotation models."""
286
+ """
287
+ YOLO OBB detection head for detection with rotation models.
288
+
289
+ This class extends the Detect head to include oriented bounding box prediction with rotation angles.
290
+
291
+ Attributes:
292
+ ne (int): Number of extra parameters.
293
+ cv4 (nn.ModuleList): Convolution layers for angle prediction.
294
+ angle (torch.Tensor): Predicted rotation angles.
295
+
296
+ Methods:
297
+ forward: Concatenate and return predicted bounding boxes and class probabilities.
298
+ decode_bboxes: Decode rotated bounding boxes.
299
+
300
+ Examples:
301
+ Create an OBB detection head
302
+ >>> obb = OBB(nc=80, ne=1, ch=(256, 512, 1024))
303
+ >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)]
304
+ >>> outputs = obb(x)
305
+ """
306
+
307
+ def __init__(self, nc: int = 80, ne: int = 1, ch: Tuple = ()):
308
+ """
309
+ Initialize OBB with number of classes `nc` and layer channels `ch`.
215
310
 
216
- def __init__(self, nc=80, ne=1, ch=()):
217
- """Initialize OBB with number of classes `nc` and layer channels `ch`."""
311
+ Args:
312
+ nc (int): Number of classes.
313
+ ne (int): Number of extra parameters.
314
+ ch (tuple): Tuple of channel sizes from backbone feature maps.
315
+ """
218
316
  super().__init__(nc, ch)
219
317
  self.ne = ne # number of extra parameters
220
318
 
221
319
  c4 = max(ch[0] // 4, self.ne)
222
320
  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
321
 
224
- def forward(self, x):
225
- """Concatenates and returns predicted bounding boxes and class probabilities."""
322
+ def forward(self, x: List[torch.Tensor]) -> Union[torch.Tensor, Tuple]:
323
+ """Concatenate and return predicted bounding boxes and class probabilities."""
226
324
  bs = x[0].shape[0] # batch size
227
325
  angle = torch.cat([self.cv4[i](x[i]).view(bs, self.ne, -1) for i in range(self.nl)], 2) # OBB theta logits
228
326
  # NOTE: set `angle` as an attribute so that `decode_bboxes` could use it.
@@ -235,16 +333,42 @@ class OBB(Detect):
235
333
  return x, angle
236
334
  return torch.cat([x, angle], 1) if self.export else (torch.cat([x[0], angle], 1), (x[1], angle))
237
335
 
238
- def decode_bboxes(self, bboxes, anchors):
336
+ def decode_bboxes(self, bboxes: torch.Tensor, anchors: torch.Tensor) -> torch.Tensor:
239
337
  """Decode rotated bounding boxes."""
240
338
  return dist2rbox(bboxes, self.angle, anchors, dim=1)
241
339
 
242
340
 
243
341
  class Pose(Detect):
244
- """YOLO Pose head for keypoints models."""
342
+ """
343
+ YOLO Pose head for keypoints models.
344
+
345
+ This class extends the Detect head to include keypoint prediction capabilities for pose estimation tasks.
346
+
347
+ Attributes:
348
+ kpt_shape (tuple): Number of keypoints and dimensions (2 for x,y or 3 for x,y,visible).
349
+ nk (int): Total number of keypoint values.
350
+ cv4 (nn.ModuleList): Convolution layers for keypoint prediction.
351
+
352
+ Methods:
353
+ forward: Perform forward pass through YOLO model and return predictions.
354
+ kpts_decode: Decode keypoints from predictions.
355
+
356
+ Examples:
357
+ Create a pose detection head
358
+ >>> pose = Pose(nc=80, kpt_shape=(17, 3), ch=(256, 512, 1024))
359
+ >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)]
360
+ >>> outputs = pose(x)
361
+ """
362
+
363
+ def __init__(self, nc: int = 80, kpt_shape: Tuple = (17, 3), ch: Tuple = ()):
364
+ """
365
+ Initialize YOLO network with default parameters and Convolutional Layers.
245
366
 
246
- def __init__(self, nc=80, kpt_shape=(17, 3), ch=()):
247
- """Initialize YOLO network with default parameters and Convolutional Layers."""
367
+ Args:
368
+ nc (int): Number of classes.
369
+ kpt_shape (tuple): Number of keypoints, number of dims (2 for x,y or 3 for x,y,visible).
370
+ ch (tuple): Tuple of channel sizes from backbone feature maps.
371
+ """
248
372
  super().__init__(nc, ch)
249
373
  self.kpt_shape = kpt_shape # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible)
250
374
  self.nk = kpt_shape[0] * kpt_shape[1] # number of keypoints total
@@ -252,7 +376,7 @@ class Pose(Detect):
252
376
  c4 = max(ch[0] // 4, self.nk)
253
377
  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
378
 
255
- def forward(self, x):
379
+ def forward(self, x: List[torch.Tensor]) -> Union[torch.Tensor, Tuple]:
256
380
  """Perform forward pass through YOLO model and return predictions."""
257
381
  bs = x[0].shape[0] # batch size
258
382
  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)
@@ -262,8 +386,8 @@ class Pose(Detect):
262
386
  pred_kpt = self.kpts_decode(bs, kpt)
263
387
  return torch.cat([x, pred_kpt], 1) if self.export else (torch.cat([x[0], pred_kpt], 1), (x[1], kpt))
264
388
 
265
- def kpts_decode(self, bs, kpts):
266
- """Decodes keypoints."""
389
+ def kpts_decode(self, bs: int, kpts: torch.Tensor) -> torch.Tensor:
390
+ """Decode keypoints from predictions."""
267
391
  ndim = self.kpt_shape[1]
268
392
  if self.export:
269
393
  if self.format in {
@@ -293,12 +417,42 @@ class Pose(Detect):
293
417
 
294
418
 
295
419
  class Classify(nn.Module):
296
- """YOLO classification head, i.e. x(b,c1,20,20) to x(b,c2)."""
420
+ """
421
+ YOLO classification head, i.e. x(b,c1,20,20) to x(b,c2).
422
+
423
+ This class implements a classification head that transforms feature maps into class predictions.
424
+
425
+ Attributes:
426
+ export (bool): Export mode flag.
427
+ conv (Conv): Convolutional layer for feature transformation.
428
+ pool (nn.AdaptiveAvgPool2d): Global average pooling layer.
429
+ drop (nn.Dropout): Dropout layer for regularization.
430
+ linear (nn.Linear): Linear layer for final classification.
431
+
432
+ Methods:
433
+ forward: Perform forward pass of the YOLO model on input image data.
434
+
435
+ Examples:
436
+ Create a classification head
437
+ >>> classify = Classify(c1=1024, c2=1000)
438
+ >>> x = torch.randn(1, 1024, 20, 20)
439
+ >>> output = classify(x)
440
+ """
297
441
 
298
442
  export = False # export mode
299
443
 
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."""
444
+ def __init__(self, c1: int, c2: int, k: int = 1, s: int = 1, p: Optional[int] = None, g: int = 1):
445
+ """
446
+ Initialize YOLO classification head to transform input tensor from (b,c1,20,20) to (b,c2) shape.
447
+
448
+ Args:
449
+ c1 (int): Number of input channels.
450
+ c2 (int): Number of output classes.
451
+ k (int, optional): Kernel size.
452
+ s (int, optional): Stride.
453
+ p (int, optional): Padding.
454
+ g (int, optional): Groups.
455
+ """
302
456
  super().__init__()
303
457
  c_ = 1280 # efficientnet_b0 size
304
458
  self.conv = Conv(c1, c_, k, s, p, g)
@@ -306,8 +460,8 @@ class Classify(nn.Module):
306
460
  self.drop = nn.Dropout(p=0.0, inplace=True)
307
461
  self.linear = nn.Linear(c_, c2) # to x(b,c2)
308
462
 
309
- def forward(self, x):
310
- """Performs a forward pass of the YOLO model on input image data."""
463
+ def forward(self, x: Union[List[torch.Tensor], torch.Tensor]) -> Union[torch.Tensor, Tuple]:
464
+ """Perform forward pass of the YOLO model on input image data."""
311
465
  if isinstance(x, list):
312
466
  x = torch.cat(x, 1)
313
467
  x = self.linear(self.drop(self.pool(self.conv(x)).flatten(1)))
@@ -318,17 +472,45 @@ class Classify(nn.Module):
318
472
 
319
473
 
320
474
  class WorldDetect(Detect):
321
- """Head for integrating YOLO detection models with semantic understanding from text embeddings."""
475
+ """
476
+ Head for integrating YOLO detection models with semantic understanding from text embeddings.
322
477
 
323
- def __init__(self, nc=80, embed=512, with_bn=False, ch=()):
324
- """Initialize YOLO detection layer with nc classes and layer channels ch."""
478
+ This class extends the standard Detect head to incorporate text embeddings for enhanced semantic understanding
479
+ in object detection tasks.
480
+
481
+ Attributes:
482
+ cv3 (nn.ModuleList): Convolution layers for embedding features.
483
+ cv4 (nn.ModuleList): Contrastive head layers for text-vision alignment.
484
+
485
+ Methods:
486
+ forward: Concatenate and return predicted bounding boxes and class probabilities.
487
+ bias_init: Initialize detection head biases.
488
+
489
+ Examples:
490
+ Create a WorldDetect head
491
+ >>> world_detect = WorldDetect(nc=80, embed=512, with_bn=False, ch=(256, 512, 1024))
492
+ >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)]
493
+ >>> text = torch.randn(1, 80, 512)
494
+ >>> outputs = world_detect(x, text)
495
+ """
496
+
497
+ def __init__(self, nc: int = 80, embed: int = 512, with_bn: bool = False, ch: Tuple = ()):
498
+ """
499
+ Initialize YOLO detection layer with nc classes and layer channels ch.
500
+
501
+ Args:
502
+ nc (int): Number of classes.
503
+ embed (int): Embedding dimension.
504
+ with_bn (bool): Whether to use batch normalization in contrastive head.
505
+ ch (tuple): Tuple of channel sizes from backbone feature maps.
506
+ """
325
507
  super().__init__(nc, ch)
326
508
  c3 = max(ch[0], min(self.nc, 100))
327
509
  self.cv3 = nn.ModuleList(nn.Sequential(Conv(x, c3, 3), Conv(c3, c3, 3), nn.Conv2d(c3, embed, 1)) for x in ch)
328
510
  self.cv4 = nn.ModuleList(BNContrastiveHead(embed) if with_bn else ContrastiveHead() for _ in ch)
329
511
 
330
- def forward(self, x, text):
331
- """Concatenates and returns predicted bounding boxes and class probabilities."""
512
+ def forward(self, x: List[torch.Tensor], text: torch.Tensor) -> Union[List[torch.Tensor], Tuple]:
513
+ """Concatenate and return predicted bounding boxes and class probabilities."""
332
514
  for i in range(self.nl):
333
515
  x[i] = torch.cat((self.cv2[i](x[i]), self.cv4[i](self.cv3[i](x[i]), text)), 1)
334
516
  if self.training:
@@ -348,17 +530,47 @@ class WorldDetect(Detect):
348
530
 
349
531
 
350
532
  class LRPCHead(nn.Module):
351
- """Lightweight Region Proposal and Classification Head for efficient object detection."""
533
+ """
534
+ Lightweight Region Proposal and Classification Head for efficient object detection.
535
+
536
+ This head combines region proposal filtering with classification to enable efficient detection with
537
+ dynamic vocabulary support.
538
+
539
+ Attributes:
540
+ vocab (nn.Module): Vocabulary/classification layer.
541
+ pf (nn.Module): Proposal filter module.
542
+ loc (nn.Module): Localization module.
543
+ enabled (bool): Whether the head is enabled.
544
+
545
+ Methods:
546
+ conv2linear: Convert a 1x1 convolutional layer to a linear layer.
547
+ forward: Process classification and localization features to generate detection proposals.
548
+
549
+ Examples:
550
+ Create an LRPC head
551
+ >>> vocab = nn.Conv2d(256, 80, 1)
552
+ >>> pf = nn.Conv2d(256, 1, 1)
553
+ >>> loc = nn.Conv2d(256, 4, 1)
554
+ >>> head = LRPCHead(vocab, pf, loc, enabled=True)
555
+ """
556
+
557
+ def __init__(self, vocab: nn.Module, pf: nn.Module, loc: nn.Module, enabled: bool = True):
558
+ """
559
+ Initialize LRPCHead with vocabulary, proposal filter, and localization components.
352
560
 
353
- def __init__(self, vocab, pf, loc, enabled=True):
354
- """Initialize LRPCHead with vocabulary, proposal filter, and localization components."""
561
+ Args:
562
+ vocab (nn.Module): Vocabulary/classification module.
563
+ pf (nn.Module): Proposal filter module.
564
+ loc (nn.Module): Localization module.
565
+ enabled (bool): Whether to enable the head functionality.
566
+ """
355
567
  super().__init__()
356
568
  self.vocab = self.conv2linear(vocab) if enabled else vocab
357
569
  self.pf = pf
358
570
  self.loc = loc
359
571
  self.enabled = enabled
360
572
 
361
- def conv2linear(self, conv):
573
+ def conv2linear(self, conv: nn.Conv2d) -> nn.Linear:
362
574
  """Convert a 1x1 convolutional layer to a linear layer."""
363
575
  assert isinstance(conv, nn.Conv2d) and conv.kernel_size == (1, 1)
364
576
  linear = nn.Linear(conv.in_channels, conv.out_channels)
@@ -366,7 +578,7 @@ class LRPCHead(nn.Module):
366
578
  linear.bias.data = conv.bias.data
367
579
  return linear
368
580
 
369
- def forward(self, cls_feat, loc_feat, conf):
581
+ def forward(self, cls_feat: torch.Tensor, loc_feat: torch.Tensor, conf: float) -> Tuple[Tuple, torch.Tensor]:
370
582
  """Process classification and localization features to generate detection proposals."""
371
583
  if self.enabled:
372
584
  pf_score = self.pf(cls_feat)[0, 0].flatten(0)
@@ -383,12 +595,48 @@ class LRPCHead(nn.Module):
383
595
 
384
596
 
385
597
  class YOLOEDetect(Detect):
386
- """Head for integrating YOLO detection models with semantic understanding from text embeddings."""
598
+ """
599
+ Head for integrating YOLO detection models with semantic understanding from text embeddings.
600
+
601
+ This class extends the standard Detect head to support text-guided detection with enhanced semantic understanding
602
+ through text embeddings and visual prompt embeddings.
603
+
604
+ Attributes:
605
+ is_fused (bool): Whether the model is fused for inference.
606
+ cv3 (nn.ModuleList): Convolution layers for embedding features.
607
+ cv4 (nn.ModuleList): Contrastive head layers for text-vision alignment.
608
+ reprta (Residual): Residual block for text prompt embeddings.
609
+ savpe (SAVPE): Spatial-aware visual prompt embeddings module.
610
+ embed (int): Embedding dimension.
611
+
612
+ Methods:
613
+ fuse: Fuse text features with model weights for efficient inference.
614
+ get_tpe: Get text prompt embeddings with normalization.
615
+ get_vpe: Get visual prompt embeddings with spatial awareness.
616
+ forward_lrpc: Process features with fused text embeddings for prompt-free model.
617
+ forward: Process features with class prompt embeddings to generate detections.
618
+ bias_init: Initialize biases for detection heads.
619
+
620
+ Examples:
621
+ Create a YOLOEDetect head
622
+ >>> yoloe_detect = YOLOEDetect(nc=80, embed=512, with_bn=True, ch=(256, 512, 1024))
623
+ >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)]
624
+ >>> cls_pe = torch.randn(1, 80, 512)
625
+ >>> outputs = yoloe_detect(x, cls_pe)
626
+ """
387
627
 
388
628
  is_fused = False
389
629
 
390
- def __init__(self, nc=80, embed=512, with_bn=False, ch=()):
391
- """Initialize YOLO detection layer with nc classes and layer channels ch."""
630
+ def __init__(self, nc: int = 80, embed: int = 512, with_bn: bool = False, ch: Tuple = ()):
631
+ """
632
+ Initialize YOLO detection layer with nc classes and layer channels ch.
633
+
634
+ Args:
635
+ nc (int): Number of classes.
636
+ embed (int): Embedding dimension.
637
+ with_bn (bool): Whether to use batch normalization in contrastive head.
638
+ ch (tuple): Tuple of channel sizes from backbone feature maps.
639
+ """
392
640
  super().__init__(nc, ch)
393
641
  c3 = max(ch[0], min(self.nc, 100))
394
642
  assert c3 <= embed
@@ -413,7 +661,7 @@ class YOLOEDetect(Detect):
413
661
  self.embed = embed
414
662
 
415
663
  @smart_inference_mode()
416
- def fuse(self, txt_feats):
664
+ def fuse(self, txt_feats: torch.Tensor):
417
665
  """Fuse text features with model weights for efficient inference."""
418
666
  if self.is_fused:
419
667
  return
@@ -459,11 +707,11 @@ class YOLOEDetect(Detect):
459
707
  self.reprta = nn.Identity()
460
708
  self.is_fused = True
461
709
 
462
- def get_tpe(self, tpe):
710
+ def get_tpe(self, tpe: Optional[torch.Tensor]) -> Optional[torch.Tensor]:
463
711
  """Get text prompt embeddings with normalization."""
464
712
  return None if tpe is None else F.normalize(self.reprta(tpe), dim=-1, p=2)
465
713
 
466
- def get_vpe(self, x, vpe):
714
+ def get_vpe(self, x: List[torch.Tensor], vpe: torch.Tensor) -> torch.Tensor:
467
715
  """Get visual prompt embeddings with spatial awareness."""
468
716
  if vpe.shape[1] == 0: # no visual prompt embeddings
469
717
  return torch.zeros(x[0].shape[0], 0, self.embed, device=x[0].device)
@@ -472,7 +720,7 @@ class YOLOEDetect(Detect):
472
720
  assert vpe.ndim == 3 # (B, N, D)
473
721
  return vpe
474
722
 
475
- def forward_lrpc(self, x, return_mask=False):
723
+ def forward_lrpc(self, x: List[torch.Tensor], return_mask: bool = False) -> Union[torch.Tensor, Tuple]:
476
724
  """Process features with fused text embeddings to generate detections for prompt-free model."""
477
725
  masks = []
478
726
  assert self.is_fused, "Prompt-free inference requires model to be fused!"
@@ -510,7 +758,9 @@ class YOLOEDetect(Detect):
510
758
  else:
511
759
  return y if self.export else (y, x)
512
760
 
513
- def forward(self, x, cls_pe, return_mask=False):
761
+ def forward(
762
+ self, x: List[torch.Tensor], cls_pe: torch.Tensor, return_mask: bool = False
763
+ ) -> Union[torch.Tensor, Tuple]:
514
764
  """Process features with class prompt embeddings to generate detections."""
515
765
  if hasattr(self, "lrpc"): # for prompt-free inference
516
766
  return self.forward_lrpc(x, return_mask)
@@ -535,10 +785,43 @@ class YOLOEDetect(Detect):
535
785
 
536
786
 
537
787
  class YOLOESegment(YOLOEDetect):
538
- """YOLO segmentation head with text embedding capabilities."""
788
+ """
789
+ YOLO segmentation head with text embedding capabilities.
790
+
791
+ This class extends YOLOEDetect to include mask prediction capabilities for instance segmentation tasks
792
+ with text-guided semantic understanding.
539
793
 
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."""
794
+ Attributes:
795
+ nm (int): Number of masks.
796
+ npr (int): Number of protos.
797
+ proto (Proto): Prototype generation module.
798
+ cv5 (nn.ModuleList): Convolution layers for mask coefficients.
799
+
800
+ Methods:
801
+ forward: Return model outputs and mask coefficients.
802
+
803
+ Examples:
804
+ Create a YOLOESegment head
805
+ >>> yoloe_segment = YOLOESegment(nc=80, nm=32, npr=256, embed=512, with_bn=True, ch=(256, 512, 1024))
806
+ >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)]
807
+ >>> text = torch.randn(1, 80, 512)
808
+ >>> outputs = yoloe_segment(x, text)
809
+ """
810
+
811
+ def __init__(
812
+ self, nc: int = 80, nm: int = 32, npr: int = 256, embed: int = 512, with_bn: bool = False, ch: Tuple = ()
813
+ ):
814
+ """
815
+ Initialize YOLOESegment with class count, mask parameters, and embedding dimensions.
816
+
817
+ Args:
818
+ nc (int): Number of classes.
819
+ nm (int): Number of masks.
820
+ npr (int): Number of protos.
821
+ embed (int): Embedding dimension.
822
+ with_bn (bool): Whether to use batch normalization in contrastive head.
823
+ ch (tuple): Tuple of channel sizes from backbone feature maps.
824
+ """
542
825
  super().__init__(nc, embed, with_bn, ch)
543
826
  self.nm = nm
544
827
  self.npr = npr
@@ -547,7 +830,7 @@ class YOLOESegment(YOLOEDetect):
547
830
  c5 = max(ch[0] // 4, self.nm)
548
831
  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
832
 
550
- def forward(self, x, text):
833
+ def forward(self, x: List[torch.Tensor], text: torch.Tensor) -> Union[Tuple, torch.Tensor]:
551
834
  """Return model outputs and mask coefficients if training, otherwise return outputs and mask coefficients."""
552
835
  p = self.proto(x[0]) # mask protos
553
836
  bs = p.shape[0] # batch size
@@ -576,48 +859,80 @@ class RTDETRDecoder(nn.Module):
576
859
  This decoder module utilizes Transformer architecture along with deformable convolutions to predict bounding boxes
577
860
  and class labels for objects in an image. It integrates features from multiple layers and runs through a series of
578
861
  Transformer decoder layers to output the final predictions.
862
+
863
+ Attributes:
864
+ export (bool): Export mode flag.
865
+ hidden_dim (int): Dimension of hidden layers.
866
+ nhead (int): Number of heads in multi-head attention.
867
+ nl (int): Number of feature levels.
868
+ nc (int): Number of classes.
869
+ num_queries (int): Number of query points.
870
+ num_decoder_layers (int): Number of decoder layers.
871
+ input_proj (nn.ModuleList): Input projection layers for backbone features.
872
+ decoder (DeformableTransformerDecoder): Transformer decoder module.
873
+ denoising_class_embed (nn.Embedding): Class embeddings for denoising.
874
+ num_denoising (int): Number of denoising queries.
875
+ label_noise_ratio (float): Label noise ratio for training.
876
+ box_noise_scale (float): Box noise scale for training.
877
+ learnt_init_query (bool): Whether to learn initial query embeddings.
878
+ tgt_embed (nn.Embedding): Target embeddings for queries.
879
+ query_pos_head (MLP): Query position head.
880
+ enc_output (nn.Sequential): Encoder output layers.
881
+ enc_score_head (nn.Linear): Encoder score prediction head.
882
+ enc_bbox_head (MLP): Encoder bbox prediction head.
883
+ dec_score_head (nn.ModuleList): Decoder score prediction heads.
884
+ dec_bbox_head (nn.ModuleList): Decoder bbox prediction heads.
885
+
886
+ Methods:
887
+ forward: Run forward pass and return bounding box and classification scores.
888
+
889
+ Examples:
890
+ Create an RTDETRDecoder
891
+ >>> decoder = RTDETRDecoder(nc=80, ch=(512, 1024, 2048), hd=256, nq=300)
892
+ >>> x = [torch.randn(1, 512, 64, 64), torch.randn(1, 1024, 32, 32), torch.randn(1, 2048, 16, 16)]
893
+ >>> outputs = decoder(x)
579
894
  """
580
895
 
581
896
  export = False # export mode
582
897
 
583
898
  def __init__(
584
899
  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,
900
+ nc: int = 80,
901
+ ch: Tuple = (512, 1024, 2048),
902
+ hd: int = 256, # hidden dim
903
+ nq: int = 300, # num queries
904
+ ndp: int = 4, # num decoder points
905
+ nh: int = 8, # num head
906
+ ndl: int = 6, # num decoder layers
907
+ d_ffn: int = 1024, # dim of feedforward
908
+ dropout: float = 0.0,
909
+ act: nn.Module = nn.ReLU(),
910
+ eval_idx: int = -1,
596
911
  # Training args
597
- nd=100, # num denoising
598
- label_noise_ratio=0.5,
599
- box_noise_scale=1.0,
600
- learnt_init_query=False,
912
+ nd: int = 100, # num denoising
913
+ label_noise_ratio: float = 0.5,
914
+ box_noise_scale: float = 1.0,
915
+ learnt_init_query: bool = False,
601
916
  ):
602
917
  """
603
- Initializes the RTDETRDecoder module with the given parameters.
918
+ Initialize the RTDETRDecoder module with the given parameters.
604
919
 
605
920
  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.
921
+ nc (int): Number of classes.
922
+ ch (tuple): Channels in the backbone feature maps.
923
+ hd (int): Dimension of hidden layers.
924
+ nq (int): Number of query points.
925
+ ndp (int): Number of decoder points.
926
+ nh (int): Number of heads in multi-head attention.
927
+ ndl (int): Number of decoder layers.
928
+ d_ffn (int): Dimension of the feed-forward networks.
929
+ dropout (float): Dropout rate.
930
+ act (nn.Module): Activation function.
931
+ eval_idx (int): Evaluation index.
932
+ nd (int): Number of denoising.
933
+ label_noise_ratio (float): Label noise ratio.
934
+ box_noise_scale (float): Box noise scale.
935
+ learnt_init_query (bool): Whether to learn initial query embeddings.
621
936
  """
622
937
  super().__init__()
623
938
  self.hidden_dim = hd
@@ -659,17 +974,18 @@ class RTDETRDecoder(nn.Module):
659
974
 
660
975
  self._reset_parameters()
661
976
 
662
- def forward(self, x, batch=None):
977
+ def forward(self, x: List[torch.Tensor], batch: Optional[dict] = None) -> Union[Tuple, torch.Tensor]:
663
978
  """
664
- Runs the forward pass of the module, returning bounding box and classification scores for the input.
979
+ Run the forward pass of the module, returning bounding box and classification scores for the input.
665
980
 
666
981
  Args:
667
982
  x (List[torch.Tensor]): List of feature maps from the backbone.
668
983
  batch (dict, optional): Batch information for training.
669
984
 
670
985
  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.
986
+ outputs (tuple | torch.Tensor): During training, returns a tuple of bounding boxes, scores, and other
987
+ metadata. During inference, returns a tensor of shape (bs, 300, 4+nc) containing bounding boxes and
988
+ class scores.
673
989
  """
674
990
  from ultralytics.models.utils.ops import get_cdn_group
675
991
 
@@ -708,19 +1024,27 @@ class RTDETRDecoder(nn.Module):
708
1024
  y = torch.cat((dec_bboxes.squeeze(0), dec_scores.squeeze(0).sigmoid()), -1)
709
1025
  return y if self.export else (y, x)
710
1026
 
711
- def _generate_anchors(self, shapes, grid_size=0.05, dtype=torch.float32, device="cpu", eps=1e-2):
1027
+ def _generate_anchors(
1028
+ self,
1029
+ shapes: List[List[int]],
1030
+ grid_size: float = 0.05,
1031
+ dtype: torch.dtype = torch.float32,
1032
+ device: str = "cpu",
1033
+ eps: float = 1e-2,
1034
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
712
1035
  """
713
- Generates anchor bounding boxes for given shapes with specific grid size and validates them.
1036
+ Generate anchor bounding boxes for given shapes with specific grid size and validate them.
714
1037
 
715
1038
  Args:
716
1039
  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.
1040
+ grid_size (float, optional): Base size of grid cells.
1041
+ dtype (torch.dtype, optional): Data type for tensors.
1042
+ device (str, optional): Device to create tensors on.
1043
+ eps (float, optional): Small value for numerical stability.
721
1044
 
722
1045
  Returns:
723
- (tuple): Tuple containing anchors and valid mask tensors.
1046
+ anchors (torch.Tensor): Generated anchor boxes.
1047
+ valid_mask (torch.Tensor): Valid mask for anchors.
724
1048
  """
725
1049
  anchors = []
726
1050
  for i, (h, w) in enumerate(shapes):
@@ -740,15 +1064,16 @@ class RTDETRDecoder(nn.Module):
740
1064
  anchors = anchors.masked_fill(~valid_mask, float("inf"))
741
1065
  return anchors, valid_mask
742
1066
 
743
- def _get_encoder_input(self, x):
1067
+ def _get_encoder_input(self, x: List[torch.Tensor]) -> Tuple[torch.Tensor, List[List[int]]]:
744
1068
  """
745
- Processes and returns encoder inputs by getting projection features from input and concatenating them.
1069
+ Process and return encoder inputs by getting projection features from input and concatenating them.
746
1070
 
747
1071
  Args:
748
1072
  x (List[torch.Tensor]): List of feature maps from the backbone.
749
1073
 
750
1074
  Returns:
751
- (tuple): Tuple containing processed features and their shapes.
1075
+ feats (torch.Tensor): Processed features.
1076
+ shapes (list): List of feature map shapes.
752
1077
  """
753
1078
  # Get projection features
754
1079
  x = [self.input_proj[i](feat) for i, feat in enumerate(x)]
@@ -766,18 +1091,27 @@ class RTDETRDecoder(nn.Module):
766
1091
  feats = torch.cat(feats, 1)
767
1092
  return feats, shapes
768
1093
 
769
- def _get_decoder_input(self, feats, shapes, dn_embed=None, dn_bbox=None):
1094
+ def _get_decoder_input(
1095
+ self,
1096
+ feats: torch.Tensor,
1097
+ shapes: List[List[int]],
1098
+ dn_embed: Optional[torch.Tensor] = None,
1099
+ dn_bbox: Optional[torch.Tensor] = None,
1100
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
770
1101
  """
771
- Generates and prepares the input required for the decoder from the provided features and shapes.
1102
+ Generate and prepare the input required for the decoder from the provided features and shapes.
772
1103
 
773
1104
  Args:
774
1105
  feats (torch.Tensor): Processed features from encoder.
775
1106
  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.
1107
+ dn_embed (torch.Tensor, optional): Denoising embeddings.
1108
+ dn_bbox (torch.Tensor, optional): Denoising bounding boxes.
778
1109
 
779
1110
  Returns:
780
- (tuple): Tuple containing embeddings, reference bounding boxes, encoded bounding boxes, and scores.
1111
+ embeddings (torch.Tensor): Query embeddings for decoder.
1112
+ refer_bbox (torch.Tensor): Reference bounding boxes.
1113
+ enc_bboxes (torch.Tensor): Encoded bounding boxes.
1114
+ enc_scores (torch.Tensor): Encoded scores.
781
1115
  """
782
1116
  bs = feats.shape[0]
783
1117
  # Prepare input for decoder
@@ -816,7 +1150,7 @@ class RTDETRDecoder(nn.Module):
816
1150
  return embeddings, refer_bbox, enc_bboxes, enc_scores
817
1151
 
818
1152
  def _reset_parameters(self):
819
- """Initializes or resets the parameters of the model's various components with predefined weights and biases."""
1153
+ """Initialize or reset the parameters of the model's various components with predefined weights and biases."""
820
1154
  # Class and bbox head init
821
1155
  bias_cls = bias_init_with_prob(0.01) / 80 * self.nc
822
1156
  # NOTE: the weight initialization in `linear_init` would cause NaN when training with custom datasets.
@@ -844,24 +1178,38 @@ class v10Detect(Detect):
844
1178
  """
845
1179
  v10 Detection head from https://arxiv.org/pdf/2405.14458.
846
1180
 
847
- Args:
848
- nc (int): Number of classes.
849
- ch (tuple): Tuple of channel sizes.
1181
+ This class implements the YOLOv10 detection head with dual-assignment training and consistent dual predictions
1182
+ for improved efficiency and performance.
850
1183
 
851
1184
  Attributes:
1185
+ end2end (bool): End-to-end detection mode.
852
1186
  max_det (int): Maximum number of detections.
1187
+ cv3 (nn.ModuleList): Light classification head layers.
1188
+ one2one_cv3 (nn.ModuleList): One-to-one classification head layers.
853
1189
 
854
1190
  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
-
1191
+ __init__: Initialize the v10Detect object with specified number of classes and input channels.
1192
+ forward: Perform forward pass of the v10Detect module.
1193
+ bias_init: Initialize biases of the Detect module.
1194
+ fuse: Remove the one2many head for inference optimization.
1195
+
1196
+ Examples:
1197
+ Create a v10Detect head
1198
+ >>> v10_detect = v10Detect(nc=80, ch=(256, 512, 1024))
1199
+ >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)]
1200
+ >>> outputs = v10_detect(x)
859
1201
  """
860
1202
 
861
1203
  end2end = True
862
1204
 
863
- def __init__(self, nc=80, ch=()):
864
- """Initializes the v10Detect object with the specified number of classes and input channels."""
1205
+ def __init__(self, nc: int = 80, ch: Tuple = ()):
1206
+ """
1207
+ Initialize the v10Detect object with the specified number of classes and input channels.
1208
+
1209
+ Args:
1210
+ nc (int): Number of classes.
1211
+ ch (tuple): Tuple of channel sizes from backbone feature maps.
1212
+ """
865
1213
  super().__init__(nc, ch)
866
1214
  c3 = max(ch[0], min(self.nc, 100)) # channels
867
1215
  # Light cls head
@@ -876,5 +1224,5 @@ class v10Detect(Detect):
876
1224
  self.one2one_cv3 = copy.deepcopy(self.cv3)
877
1225
 
878
1226
  def fuse(self):
879
- """Removes the one2many head."""
1227
+ """Remove the one2many head for inference optimization."""
880
1228
  self.cv2 = self.cv3 = nn.ModuleList([nn.Identity()] * self.nl)