dgenerate-ultralytics-headless 8.3.253__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 (299) hide show
  1. dgenerate_ultralytics_headless-8.3.253.dist-info/METADATA +405 -0
  2. dgenerate_ultralytics_headless-8.3.253.dist-info/RECORD +299 -0
  3. dgenerate_ultralytics_headless-8.3.253.dist-info/WHEEL +5 -0
  4. dgenerate_ultralytics_headless-8.3.253.dist-info/entry_points.txt +3 -0
  5. dgenerate_ultralytics_headless-8.3.253.dist-info/licenses/LICENSE +661 -0
  6. dgenerate_ultralytics_headless-8.3.253.dist-info/top_level.txt +1 -0
  7. tests/__init__.py +23 -0
  8. tests/conftest.py +59 -0
  9. tests/test_cli.py +131 -0
  10. tests/test_cuda.py +216 -0
  11. tests/test_engine.py +157 -0
  12. tests/test_exports.py +309 -0
  13. tests/test_integrations.py +151 -0
  14. tests/test_python.py +777 -0
  15. tests/test_solutions.py +371 -0
  16. ultralytics/__init__.py +48 -0
  17. ultralytics/assets/bus.jpg +0 -0
  18. ultralytics/assets/zidane.jpg +0 -0
  19. ultralytics/cfg/__init__.py +1028 -0
  20. ultralytics/cfg/datasets/Argoverse.yaml +78 -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 +32 -0
  25. ultralytics/cfg/datasets/ImageNet.yaml +2025 -0
  26. ultralytics/cfg/datasets/Objects365.yaml +447 -0
  27. ultralytics/cfg/datasets/SKU-110K.yaml +58 -0
  28. ultralytics/cfg/datasets/TT100K.yaml +346 -0
  29. ultralytics/cfg/datasets/VOC.yaml +102 -0
  30. ultralytics/cfg/datasets/VisDrone.yaml +87 -0
  31. ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
  32. ultralytics/cfg/datasets/brain-tumor.yaml +22 -0
  33. ultralytics/cfg/datasets/carparts-seg.yaml +44 -0
  34. ultralytics/cfg/datasets/coco-pose.yaml +64 -0
  35. ultralytics/cfg/datasets/coco.yaml +118 -0
  36. ultralytics/cfg/datasets/coco128-seg.yaml +101 -0
  37. ultralytics/cfg/datasets/coco128.yaml +101 -0
  38. ultralytics/cfg/datasets/coco8-grayscale.yaml +103 -0
  39. ultralytics/cfg/datasets/coco8-multispectral.yaml +104 -0
  40. ultralytics/cfg/datasets/coco8-pose.yaml +47 -0
  41. ultralytics/cfg/datasets/coco8-seg.yaml +101 -0
  42. ultralytics/cfg/datasets/coco8.yaml +101 -0
  43. ultralytics/cfg/datasets/construction-ppe.yaml +32 -0
  44. ultralytics/cfg/datasets/crack-seg.yaml +22 -0
  45. ultralytics/cfg/datasets/dog-pose.yaml +52 -0
  46. ultralytics/cfg/datasets/dota8-multispectral.yaml +38 -0
  47. ultralytics/cfg/datasets/dota8.yaml +35 -0
  48. ultralytics/cfg/datasets/hand-keypoints.yaml +50 -0
  49. ultralytics/cfg/datasets/kitti.yaml +27 -0
  50. ultralytics/cfg/datasets/lvis.yaml +1240 -0
  51. ultralytics/cfg/datasets/medical-pills.yaml +21 -0
  52. ultralytics/cfg/datasets/open-images-v7.yaml +663 -0
  53. ultralytics/cfg/datasets/package-seg.yaml +22 -0
  54. ultralytics/cfg/datasets/signature.yaml +21 -0
  55. ultralytics/cfg/datasets/tiger-pose.yaml +41 -0
  56. ultralytics/cfg/datasets/xView.yaml +155 -0
  57. ultralytics/cfg/default.yaml +130 -0
  58. ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +17 -0
  59. ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
  60. ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
  61. ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
  62. ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
  63. ultralytics/cfg/models/11/yolo11.yaml +50 -0
  64. ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
  65. ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
  66. ultralytics/cfg/models/12/yolo12-cls.yaml +32 -0
  67. ultralytics/cfg/models/12/yolo12-obb.yaml +48 -0
  68. ultralytics/cfg/models/12/yolo12-pose.yaml +49 -0
  69. ultralytics/cfg/models/12/yolo12-seg.yaml +48 -0
  70. ultralytics/cfg/models/12/yolo12.yaml +48 -0
  71. ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +53 -0
  72. ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +45 -0
  73. ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +45 -0
  74. ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +57 -0
  75. ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
  76. ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
  77. ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
  78. ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
  79. ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
  80. ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
  81. ultralytics/cfg/models/v3/yolov3-spp.yaml +49 -0
  82. ultralytics/cfg/models/v3/yolov3-tiny.yaml +40 -0
  83. ultralytics/cfg/models/v3/yolov3.yaml +49 -0
  84. ultralytics/cfg/models/v5/yolov5-p6.yaml +62 -0
  85. ultralytics/cfg/models/v5/yolov5.yaml +51 -0
  86. ultralytics/cfg/models/v6/yolov6.yaml +56 -0
  87. ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +48 -0
  88. ultralytics/cfg/models/v8/yoloe-v8.yaml +48 -0
  89. ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +28 -0
  90. ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +28 -0
  91. ultralytics/cfg/models/v8/yolov8-cls.yaml +32 -0
  92. ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +58 -0
  93. ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +60 -0
  94. ultralytics/cfg/models/v8/yolov8-ghost.yaml +50 -0
  95. ultralytics/cfg/models/v8/yolov8-obb.yaml +49 -0
  96. ultralytics/cfg/models/v8/yolov8-p2.yaml +57 -0
  97. ultralytics/cfg/models/v8/yolov8-p6.yaml +59 -0
  98. ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +60 -0
  99. ultralytics/cfg/models/v8/yolov8-pose.yaml +50 -0
  100. ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +49 -0
  101. ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +59 -0
  102. ultralytics/cfg/models/v8/yolov8-seg.yaml +49 -0
  103. ultralytics/cfg/models/v8/yolov8-world.yaml +51 -0
  104. ultralytics/cfg/models/v8/yolov8-worldv2.yaml +49 -0
  105. ultralytics/cfg/models/v8/yolov8.yaml +49 -0
  106. ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
  107. ultralytics/cfg/models/v9/yolov9c.yaml +41 -0
  108. ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
  109. ultralytics/cfg/models/v9/yolov9e.yaml +64 -0
  110. ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
  111. ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
  112. ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
  113. ultralytics/cfg/trackers/botsort.yaml +21 -0
  114. ultralytics/cfg/trackers/bytetrack.yaml +12 -0
  115. ultralytics/data/__init__.py +26 -0
  116. ultralytics/data/annotator.py +66 -0
  117. ultralytics/data/augment.py +2801 -0
  118. ultralytics/data/base.py +435 -0
  119. ultralytics/data/build.py +437 -0
  120. ultralytics/data/converter.py +855 -0
  121. ultralytics/data/dataset.py +834 -0
  122. ultralytics/data/loaders.py +704 -0
  123. ultralytics/data/scripts/download_weights.sh +18 -0
  124. ultralytics/data/scripts/get_coco.sh +61 -0
  125. ultralytics/data/scripts/get_coco128.sh +18 -0
  126. ultralytics/data/scripts/get_imagenet.sh +52 -0
  127. ultralytics/data/split.py +138 -0
  128. ultralytics/data/split_dota.py +344 -0
  129. ultralytics/data/utils.py +798 -0
  130. ultralytics/engine/__init__.py +1 -0
  131. ultralytics/engine/exporter.py +1580 -0
  132. ultralytics/engine/model.py +1125 -0
  133. ultralytics/engine/predictor.py +508 -0
  134. ultralytics/engine/results.py +1522 -0
  135. ultralytics/engine/trainer.py +977 -0
  136. ultralytics/engine/tuner.py +449 -0
  137. ultralytics/engine/validator.py +387 -0
  138. ultralytics/hub/__init__.py +166 -0
  139. ultralytics/hub/auth.py +151 -0
  140. ultralytics/hub/google/__init__.py +174 -0
  141. ultralytics/hub/session.py +422 -0
  142. ultralytics/hub/utils.py +162 -0
  143. ultralytics/models/__init__.py +9 -0
  144. ultralytics/models/fastsam/__init__.py +7 -0
  145. ultralytics/models/fastsam/model.py +79 -0
  146. ultralytics/models/fastsam/predict.py +169 -0
  147. ultralytics/models/fastsam/utils.py +23 -0
  148. ultralytics/models/fastsam/val.py +38 -0
  149. ultralytics/models/nas/__init__.py +7 -0
  150. ultralytics/models/nas/model.py +98 -0
  151. ultralytics/models/nas/predict.py +56 -0
  152. ultralytics/models/nas/val.py +38 -0
  153. ultralytics/models/rtdetr/__init__.py +7 -0
  154. ultralytics/models/rtdetr/model.py +63 -0
  155. ultralytics/models/rtdetr/predict.py +88 -0
  156. ultralytics/models/rtdetr/train.py +89 -0
  157. ultralytics/models/rtdetr/val.py +216 -0
  158. ultralytics/models/sam/__init__.py +25 -0
  159. ultralytics/models/sam/amg.py +275 -0
  160. ultralytics/models/sam/build.py +365 -0
  161. ultralytics/models/sam/build_sam3.py +377 -0
  162. ultralytics/models/sam/model.py +169 -0
  163. ultralytics/models/sam/modules/__init__.py +1 -0
  164. ultralytics/models/sam/modules/blocks.py +1067 -0
  165. ultralytics/models/sam/modules/decoders.py +495 -0
  166. ultralytics/models/sam/modules/encoders.py +794 -0
  167. ultralytics/models/sam/modules/memory_attention.py +298 -0
  168. ultralytics/models/sam/modules/sam.py +1160 -0
  169. ultralytics/models/sam/modules/tiny_encoder.py +979 -0
  170. ultralytics/models/sam/modules/transformer.py +344 -0
  171. ultralytics/models/sam/modules/utils.py +512 -0
  172. ultralytics/models/sam/predict.py +3940 -0
  173. ultralytics/models/sam/sam3/__init__.py +3 -0
  174. ultralytics/models/sam/sam3/decoder.py +546 -0
  175. ultralytics/models/sam/sam3/encoder.py +529 -0
  176. ultralytics/models/sam/sam3/geometry_encoders.py +415 -0
  177. ultralytics/models/sam/sam3/maskformer_segmentation.py +286 -0
  178. ultralytics/models/sam/sam3/model_misc.py +199 -0
  179. ultralytics/models/sam/sam3/necks.py +129 -0
  180. ultralytics/models/sam/sam3/sam3_image.py +339 -0
  181. ultralytics/models/sam/sam3/text_encoder_ve.py +307 -0
  182. ultralytics/models/sam/sam3/vitdet.py +547 -0
  183. ultralytics/models/sam/sam3/vl_combiner.py +160 -0
  184. ultralytics/models/utils/__init__.py +1 -0
  185. ultralytics/models/utils/loss.py +466 -0
  186. ultralytics/models/utils/ops.py +315 -0
  187. ultralytics/models/yolo/__init__.py +7 -0
  188. ultralytics/models/yolo/classify/__init__.py +7 -0
  189. ultralytics/models/yolo/classify/predict.py +90 -0
  190. ultralytics/models/yolo/classify/train.py +202 -0
  191. ultralytics/models/yolo/classify/val.py +216 -0
  192. ultralytics/models/yolo/detect/__init__.py +7 -0
  193. ultralytics/models/yolo/detect/predict.py +122 -0
  194. ultralytics/models/yolo/detect/train.py +227 -0
  195. ultralytics/models/yolo/detect/val.py +507 -0
  196. ultralytics/models/yolo/model.py +430 -0
  197. ultralytics/models/yolo/obb/__init__.py +7 -0
  198. ultralytics/models/yolo/obb/predict.py +56 -0
  199. ultralytics/models/yolo/obb/train.py +79 -0
  200. ultralytics/models/yolo/obb/val.py +302 -0
  201. ultralytics/models/yolo/pose/__init__.py +7 -0
  202. ultralytics/models/yolo/pose/predict.py +65 -0
  203. ultralytics/models/yolo/pose/train.py +110 -0
  204. ultralytics/models/yolo/pose/val.py +248 -0
  205. ultralytics/models/yolo/segment/__init__.py +7 -0
  206. ultralytics/models/yolo/segment/predict.py +109 -0
  207. ultralytics/models/yolo/segment/train.py +69 -0
  208. ultralytics/models/yolo/segment/val.py +307 -0
  209. ultralytics/models/yolo/world/__init__.py +5 -0
  210. ultralytics/models/yolo/world/train.py +173 -0
  211. ultralytics/models/yolo/world/train_world.py +178 -0
  212. ultralytics/models/yolo/yoloe/__init__.py +22 -0
  213. ultralytics/models/yolo/yoloe/predict.py +162 -0
  214. ultralytics/models/yolo/yoloe/train.py +287 -0
  215. ultralytics/models/yolo/yoloe/train_seg.py +122 -0
  216. ultralytics/models/yolo/yoloe/val.py +206 -0
  217. ultralytics/nn/__init__.py +27 -0
  218. ultralytics/nn/autobackend.py +964 -0
  219. ultralytics/nn/modules/__init__.py +182 -0
  220. ultralytics/nn/modules/activation.py +54 -0
  221. ultralytics/nn/modules/block.py +1947 -0
  222. ultralytics/nn/modules/conv.py +669 -0
  223. ultralytics/nn/modules/head.py +1183 -0
  224. ultralytics/nn/modules/transformer.py +793 -0
  225. ultralytics/nn/modules/utils.py +159 -0
  226. ultralytics/nn/tasks.py +1768 -0
  227. ultralytics/nn/text_model.py +356 -0
  228. ultralytics/py.typed +1 -0
  229. ultralytics/solutions/__init__.py +41 -0
  230. ultralytics/solutions/ai_gym.py +108 -0
  231. ultralytics/solutions/analytics.py +264 -0
  232. ultralytics/solutions/config.py +107 -0
  233. ultralytics/solutions/distance_calculation.py +123 -0
  234. ultralytics/solutions/heatmap.py +125 -0
  235. ultralytics/solutions/instance_segmentation.py +86 -0
  236. ultralytics/solutions/object_blurrer.py +89 -0
  237. ultralytics/solutions/object_counter.py +190 -0
  238. ultralytics/solutions/object_cropper.py +87 -0
  239. ultralytics/solutions/parking_management.py +280 -0
  240. ultralytics/solutions/queue_management.py +93 -0
  241. ultralytics/solutions/region_counter.py +133 -0
  242. ultralytics/solutions/security_alarm.py +151 -0
  243. ultralytics/solutions/similarity_search.py +219 -0
  244. ultralytics/solutions/solutions.py +828 -0
  245. ultralytics/solutions/speed_estimation.py +114 -0
  246. ultralytics/solutions/streamlit_inference.py +260 -0
  247. ultralytics/solutions/templates/similarity-search.html +156 -0
  248. ultralytics/solutions/trackzone.py +88 -0
  249. ultralytics/solutions/vision_eye.py +67 -0
  250. ultralytics/trackers/__init__.py +7 -0
  251. ultralytics/trackers/basetrack.py +115 -0
  252. ultralytics/trackers/bot_sort.py +257 -0
  253. ultralytics/trackers/byte_tracker.py +469 -0
  254. ultralytics/trackers/track.py +116 -0
  255. ultralytics/trackers/utils/__init__.py +1 -0
  256. ultralytics/trackers/utils/gmc.py +339 -0
  257. ultralytics/trackers/utils/kalman_filter.py +482 -0
  258. ultralytics/trackers/utils/matching.py +154 -0
  259. ultralytics/utils/__init__.py +1450 -0
  260. ultralytics/utils/autobatch.py +118 -0
  261. ultralytics/utils/autodevice.py +205 -0
  262. ultralytics/utils/benchmarks.py +728 -0
  263. ultralytics/utils/callbacks/__init__.py +5 -0
  264. ultralytics/utils/callbacks/base.py +233 -0
  265. ultralytics/utils/callbacks/clearml.py +146 -0
  266. ultralytics/utils/callbacks/comet.py +625 -0
  267. ultralytics/utils/callbacks/dvc.py +197 -0
  268. ultralytics/utils/callbacks/hub.py +110 -0
  269. ultralytics/utils/callbacks/mlflow.py +134 -0
  270. ultralytics/utils/callbacks/neptune.py +126 -0
  271. ultralytics/utils/callbacks/platform.py +453 -0
  272. ultralytics/utils/callbacks/raytune.py +42 -0
  273. ultralytics/utils/callbacks/tensorboard.py +123 -0
  274. ultralytics/utils/callbacks/wb.py +188 -0
  275. ultralytics/utils/checks.py +1020 -0
  276. ultralytics/utils/cpu.py +85 -0
  277. ultralytics/utils/dist.py +123 -0
  278. ultralytics/utils/downloads.py +529 -0
  279. ultralytics/utils/errors.py +35 -0
  280. ultralytics/utils/events.py +113 -0
  281. ultralytics/utils/export/__init__.py +7 -0
  282. ultralytics/utils/export/engine.py +237 -0
  283. ultralytics/utils/export/imx.py +325 -0
  284. ultralytics/utils/export/tensorflow.py +231 -0
  285. ultralytics/utils/files.py +219 -0
  286. ultralytics/utils/git.py +137 -0
  287. ultralytics/utils/instance.py +484 -0
  288. ultralytics/utils/logger.py +506 -0
  289. ultralytics/utils/loss.py +849 -0
  290. ultralytics/utils/metrics.py +1563 -0
  291. ultralytics/utils/nms.py +337 -0
  292. ultralytics/utils/ops.py +664 -0
  293. ultralytics/utils/patches.py +201 -0
  294. ultralytics/utils/plotting.py +1047 -0
  295. ultralytics/utils/tal.py +404 -0
  296. ultralytics/utils/torch_utils.py +984 -0
  297. ultralytics/utils/tqdm.py +443 -0
  298. ultralytics/utils/triton.py +112 -0
  299. ultralytics/utils/tuner.py +168 -0
@@ -0,0 +1,344 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+
7
+ import torch
8
+ from torch import Tensor, nn
9
+
10
+ from ultralytics.nn.modules import MLPBlock
11
+
12
+
13
+ class TwoWayTransformer(nn.Module):
14
+ """A Two-Way Transformer module for simultaneous attention to image and query points.
15
+
16
+ This class implements a specialized transformer decoder that attends to an input image using queries with supplied
17
+ positional embeddings. It's useful for tasks like object detection, image segmentation, and point cloud processing.
18
+
19
+ Attributes:
20
+ depth (int): Number of layers in the transformer.
21
+ embedding_dim (int): Channel dimension for input embeddings.
22
+ num_heads (int): Number of heads for multihead attention.
23
+ mlp_dim (int): Internal channel dimension for the MLP block.
24
+ layers (nn.ModuleList): List of TwoWayAttentionBlock layers composing the transformer.
25
+ final_attn_token_to_image (Attention): Final attention layer from queries to image.
26
+ norm_final_attn (nn.LayerNorm): Layer normalization applied to final queries.
27
+
28
+ Methods:
29
+ forward: Process image and point embeddings through the transformer.
30
+
31
+ Examples:
32
+ >>> transformer = TwoWayTransformer(depth=6, embedding_dim=256, num_heads=8, mlp_dim=2048)
33
+ >>> image_embedding = torch.randn(1, 256, 32, 32)
34
+ >>> image_pe = torch.randn(1, 256, 32, 32)
35
+ >>> point_embedding = torch.randn(1, 100, 256)
36
+ >>> output_queries, output_image = transformer(image_embedding, image_pe, point_embedding)
37
+ >>> print(output_queries.shape, output_image.shape)
38
+ """
39
+
40
+ def __init__(
41
+ self,
42
+ depth: int,
43
+ embedding_dim: int,
44
+ num_heads: int,
45
+ mlp_dim: int,
46
+ activation: type[nn.Module] = nn.ReLU,
47
+ attention_downsample_rate: int = 2,
48
+ ) -> None:
49
+ """Initialize a Two-Way Transformer for simultaneous attention to image and query points.
50
+
51
+ Args:
52
+ depth (int): Number of layers in the transformer.
53
+ embedding_dim (int): Channel dimension for input embeddings.
54
+ num_heads (int): Number of heads for multihead attention. Must divide embedding_dim.
55
+ mlp_dim (int): Internal channel dimension for the MLP block.
56
+ activation (Type[nn.Module], optional): Activation function to use in the MLP block.
57
+ attention_downsample_rate (int, optional): Downsampling rate for attention mechanism.
58
+ """
59
+ super().__init__()
60
+ self.depth = depth
61
+ self.embedding_dim = embedding_dim
62
+ self.num_heads = num_heads
63
+ self.mlp_dim = mlp_dim
64
+ self.layers = nn.ModuleList()
65
+
66
+ for i in range(depth):
67
+ self.layers.append(
68
+ TwoWayAttentionBlock(
69
+ embedding_dim=embedding_dim,
70
+ num_heads=num_heads,
71
+ mlp_dim=mlp_dim,
72
+ activation=activation,
73
+ attention_downsample_rate=attention_downsample_rate,
74
+ skip_first_layer_pe=(i == 0),
75
+ )
76
+ )
77
+
78
+ self.final_attn_token_to_image = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate)
79
+ self.norm_final_attn = nn.LayerNorm(embedding_dim)
80
+
81
+ def forward(
82
+ self,
83
+ image_embedding: torch.Tensor,
84
+ image_pe: torch.Tensor,
85
+ point_embedding: torch.Tensor,
86
+ ) -> tuple[torch.Tensor, torch.Tensor]:
87
+ """Process image and point embeddings through the Two-Way Transformer.
88
+
89
+ Args:
90
+ image_embedding (torch.Tensor): Image to attend to, with shape (B, embedding_dim, H, W).
91
+ image_pe (torch.Tensor): Positional encoding to add to the image, with same shape as image_embedding.
92
+ point_embedding (torch.Tensor): Embedding to add to query points, with shape (B, N_points, embedding_dim).
93
+
94
+ Returns:
95
+ queries (torch.Tensor): Processed point embeddings with shape (B, N_points, embedding_dim).
96
+ keys (torch.Tensor): Processed image embeddings with shape (B, H*W, embedding_dim).
97
+ """
98
+ # BxCxHxW -> BxHWxC == B x N_image_tokens x C
99
+ image_embedding = image_embedding.flatten(2).permute(0, 2, 1)
100
+ image_pe = image_pe.flatten(2).permute(0, 2, 1)
101
+
102
+ # Prepare queries
103
+ queries = point_embedding
104
+ keys = image_embedding
105
+
106
+ # Apply transformer blocks and final layernorm
107
+ for layer in self.layers:
108
+ queries, keys = layer(
109
+ queries=queries,
110
+ keys=keys,
111
+ query_pe=point_embedding,
112
+ key_pe=image_pe,
113
+ )
114
+
115
+ # Apply the final attention layer from the points to the image
116
+ q = queries + point_embedding
117
+ k = keys + image_pe
118
+ attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys)
119
+ queries = queries + attn_out
120
+ queries = self.norm_final_attn(queries)
121
+
122
+ return queries, keys
123
+
124
+
125
+ class TwoWayAttentionBlock(nn.Module):
126
+ """A two-way attention block for simultaneous attention to image and query points.
127
+
128
+ This class implements a specialized transformer block with four main layers: self-attention on sparse inputs,
129
+ cross-attention of sparse inputs to dense inputs, MLP block on sparse inputs, and cross-attention of dense inputs to
130
+ sparse inputs.
131
+
132
+ Attributes:
133
+ self_attn (Attention): Self-attention layer for queries.
134
+ norm1 (nn.LayerNorm): Layer normalization after self-attention.
135
+ cross_attn_token_to_image (Attention): Cross-attention layer from queries to keys.
136
+ norm2 (nn.LayerNorm): Layer normalization after token-to-image attention.
137
+ mlp (MLPBlock): MLP block for transforming query embeddings.
138
+ norm3 (nn.LayerNorm): Layer normalization after MLP block.
139
+ norm4 (nn.LayerNorm): Layer normalization after image-to-token attention.
140
+ cross_attn_image_to_token (Attention): Cross-attention layer from keys to queries.
141
+ skip_first_layer_pe (bool): Whether to skip positional encoding in the first layer.
142
+
143
+ Methods:
144
+ forward: Apply self-attention and cross-attention to queries and keys.
145
+
146
+ Examples:
147
+ >>> embedding_dim, num_heads = 256, 8
148
+ >>> block = TwoWayAttentionBlock(embedding_dim, num_heads)
149
+ >>> queries = torch.randn(1, 100, embedding_dim)
150
+ >>> keys = torch.randn(1, 1000, embedding_dim)
151
+ >>> query_pe = torch.randn(1, 100, embedding_dim)
152
+ >>> key_pe = torch.randn(1, 1000, embedding_dim)
153
+ >>> processed_queries, processed_keys = block(queries, keys, query_pe, key_pe)
154
+ """
155
+
156
+ def __init__(
157
+ self,
158
+ embedding_dim: int,
159
+ num_heads: int,
160
+ mlp_dim: int = 2048,
161
+ activation: type[nn.Module] = nn.ReLU,
162
+ attention_downsample_rate: int = 2,
163
+ skip_first_layer_pe: bool = False,
164
+ ) -> None:
165
+ """Initialize a TwoWayAttentionBlock for simultaneous attention to image and query points.
166
+
167
+ This block implements a specialized transformer layer with four main components: self-attention on sparse
168
+ inputs, cross-attention of sparse inputs to dense inputs, MLP block on sparse inputs, and cross-attention of
169
+ dense inputs to sparse inputs.
170
+
171
+ Args:
172
+ embedding_dim (int): Channel dimension of the embeddings.
173
+ num_heads (int): Number of attention heads in the attention layers.
174
+ mlp_dim (int, optional): Hidden dimension of the MLP block.
175
+ activation (Type[nn.Module], optional): Activation function for the MLP block.
176
+ attention_downsample_rate (int, optional): Downsampling rate for the attention mechanism.
177
+ skip_first_layer_pe (bool, optional): Whether to skip positional encoding in the first layer.
178
+ """
179
+ super().__init__()
180
+ self.self_attn = Attention(embedding_dim, num_heads)
181
+ self.norm1 = nn.LayerNorm(embedding_dim)
182
+
183
+ self.cross_attn_token_to_image = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate)
184
+ self.norm2 = nn.LayerNorm(embedding_dim)
185
+
186
+ self.mlp = MLPBlock(embedding_dim, mlp_dim, activation)
187
+ self.norm3 = nn.LayerNorm(embedding_dim)
188
+
189
+ self.norm4 = nn.LayerNorm(embedding_dim)
190
+ self.cross_attn_image_to_token = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate)
191
+
192
+ self.skip_first_layer_pe = skip_first_layer_pe
193
+
194
+ def forward(
195
+ self, queries: torch.Tensor, keys: torch.Tensor, query_pe: torch.Tensor, key_pe: torch.Tensor
196
+ ) -> tuple[torch.Tensor, torch.Tensor]:
197
+ """Apply two-way attention to process query and key embeddings in a transformer block.
198
+
199
+ Args:
200
+ queries (torch.Tensor): Query embeddings with shape (B, N_queries, embedding_dim).
201
+ keys (torch.Tensor): Key embeddings with shape (B, N_keys, embedding_dim).
202
+ query_pe (torch.Tensor): Positional encodings for queries with same shape as queries.
203
+ key_pe (torch.Tensor): Positional encodings for keys with same shape as keys.
204
+
205
+ Returns:
206
+ queries (torch.Tensor): Processed query embeddings with shape (B, N_queries, embedding_dim).
207
+ keys (torch.Tensor): Processed key embeddings with shape (B, N_keys, embedding_dim).
208
+ """
209
+ # Self attention block
210
+ if self.skip_first_layer_pe:
211
+ queries = self.self_attn(q=queries, k=queries, v=queries)
212
+ else:
213
+ q = queries + query_pe
214
+ attn_out = self.self_attn(q=q, k=q, v=queries)
215
+ queries = queries + attn_out
216
+ queries = self.norm1(queries)
217
+
218
+ # Cross attention block, tokens attending to image embedding
219
+ q = queries + query_pe
220
+ k = keys + key_pe
221
+ attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys)
222
+ queries = queries + attn_out
223
+ queries = self.norm2(queries)
224
+
225
+ # MLP block
226
+ mlp_out = self.mlp(queries)
227
+ queries = queries + mlp_out
228
+ queries = self.norm3(queries)
229
+
230
+ # Cross attention block, image embedding attending to tokens
231
+ q = queries + query_pe
232
+ k = keys + key_pe
233
+ attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries)
234
+ keys = keys + attn_out
235
+ keys = self.norm4(keys)
236
+
237
+ return queries, keys
238
+
239
+
240
+ class Attention(nn.Module):
241
+ """An attention layer with downscaling capability for embedding size after projection.
242
+
243
+ This class implements a multi-head attention mechanism with the option to downsample the internal dimension of
244
+ queries, keys, and values.
245
+
246
+ Attributes:
247
+ embedding_dim (int): Dimensionality of input embeddings.
248
+ kv_in_dim (int): Dimensionality of key and value inputs.
249
+ internal_dim (int): Internal dimension after downsampling.
250
+ num_heads (int): Number of attention heads.
251
+ q_proj (nn.Linear): Linear projection for queries.
252
+ k_proj (nn.Linear): Linear projection for keys.
253
+ v_proj (nn.Linear): Linear projection for values.
254
+ out_proj (nn.Linear): Linear projection for output.
255
+
256
+ Methods:
257
+ _separate_heads: Separate input tensor into attention heads.
258
+ _recombine_heads: Recombine separated attention heads.
259
+ forward: Compute attention output for given query, key, and value tensors.
260
+
261
+ Examples:
262
+ >>> attn = Attention(embedding_dim=256, num_heads=8, downsample_rate=2)
263
+ >>> q = torch.randn(1, 100, 256)
264
+ >>> k = v = torch.randn(1, 50, 256)
265
+ >>> output = attn(q, k, v)
266
+ >>> print(output.shape)
267
+ torch.Size([1, 100, 256])
268
+ """
269
+
270
+ def __init__(
271
+ self,
272
+ embedding_dim: int,
273
+ num_heads: int,
274
+ downsample_rate: int = 1,
275
+ kv_in_dim: int | None = None,
276
+ ) -> None:
277
+ """Initialize the Attention module with specified dimensions and settings.
278
+
279
+ Args:
280
+ embedding_dim (int): Dimensionality of input embeddings.
281
+ num_heads (int): Number of attention heads.
282
+ downsample_rate (int, optional): Factor by which internal dimensions are downsampled.
283
+ kv_in_dim (int | None, optional): Dimensionality of key and value inputs. If None, uses embedding_dim.
284
+
285
+ Raises:
286
+ AssertionError: If num_heads does not evenly divide the internal dim (embedding_dim / downsample_rate).
287
+ """
288
+ super().__init__()
289
+ self.embedding_dim = embedding_dim
290
+ self.kv_in_dim = kv_in_dim if kv_in_dim is not None else embedding_dim
291
+ self.internal_dim = embedding_dim // downsample_rate
292
+ self.num_heads = num_heads
293
+ assert self.internal_dim % num_heads == 0, "num_heads must divide embedding_dim."
294
+
295
+ self.q_proj = nn.Linear(embedding_dim, self.internal_dim)
296
+ self.k_proj = nn.Linear(self.kv_in_dim, self.internal_dim)
297
+ self.v_proj = nn.Linear(self.kv_in_dim, self.internal_dim)
298
+ self.out_proj = nn.Linear(self.internal_dim, embedding_dim)
299
+
300
+ @staticmethod
301
+ def _separate_heads(x: torch.Tensor, num_heads: int) -> torch.Tensor:
302
+ """Separate the input tensor into the specified number of attention heads."""
303
+ b, n, c = x.shape
304
+ x = x.reshape(b, n, num_heads, c // num_heads)
305
+ return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head
306
+
307
+ @staticmethod
308
+ def _recombine_heads(x: Tensor) -> Tensor:
309
+ """Recombine separated attention heads into a single tensor."""
310
+ b, n_heads, n_tokens, c_per_head = x.shape
311
+ x = x.transpose(1, 2)
312
+ return x.reshape(b, n_tokens, n_heads * c_per_head) # B x N_tokens x C
313
+
314
+ def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
315
+ """Apply multi-head attention to query, key, and value tensors with optional downsampling.
316
+
317
+ Args:
318
+ q (torch.Tensor): Query tensor with shape (B, N_q, embedding_dim).
319
+ k (torch.Tensor): Key tensor with shape (B, N_k, embedding_dim).
320
+ v (torch.Tensor): Value tensor with shape (B, N_k, embedding_dim).
321
+
322
+ Returns:
323
+ (torch.Tensor): Output tensor after attention with shape (B, N_q, embedding_dim).
324
+ """
325
+ # Input projections
326
+ q = self.q_proj(q)
327
+ k = self.k_proj(k)
328
+ v = self.v_proj(v)
329
+
330
+ # Separate into heads
331
+ q = self._separate_heads(q, self.num_heads)
332
+ k = self._separate_heads(k, self.num_heads)
333
+ v = self._separate_heads(v, self.num_heads)
334
+
335
+ # Attention
336
+ _, _, _, c_per_head = q.shape
337
+ attn = q @ k.permute(0, 1, 3, 2) # B x N_heads x N_tokens x N_tokens
338
+ attn = attn / math.sqrt(c_per_head)
339
+ attn = torch.softmax(attn, dim=-1)
340
+
341
+ # Get output
342
+ out = attn @ v
343
+ out = self._recombine_heads(out)
344
+ return self.out_proj(out)