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,794 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ from __future__ import annotations
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
+
9
+ from ultralytics.nn.modules import LayerNorm2d
10
+
11
+ from .blocks import (
12
+ Block,
13
+ CXBlock,
14
+ Fuser,
15
+ MaskDownSampler,
16
+ MultiScaleBlock,
17
+ PatchEmbed,
18
+ PositionEmbeddingRandom,
19
+ PositionEmbeddingSine,
20
+ )
21
+
22
+
23
+ class ImageEncoderViT(nn.Module):
24
+ """An image encoder using Vision Transformer (ViT) architecture for encoding images into a compact latent space.
25
+
26
+ This class processes images by splitting them into patches, applying transformer blocks, and generating a final
27
+ encoded representation through a neck module.
28
+
29
+ Attributes:
30
+ img_size (int): Dimension of input images, assumed to be square.
31
+ patch_embed (PatchEmbed): Module for patch embedding.
32
+ pos_embed (nn.Parameter | None): Absolute positional embedding for patches.
33
+ blocks (nn.ModuleList): List of transformer blocks for processing patch embeddings.
34
+ neck (nn.Sequential): Neck module to further process the output.
35
+
36
+ Methods:
37
+ forward: Process input through patch embedding, positional embedding, blocks, and neck.
38
+
39
+ Examples:
40
+ >>> import torch
41
+ >>> encoder = ImageEncoderViT(img_size=224, patch_size=16, embed_dim=768, depth=12, num_heads=12)
42
+ >>> input_image = torch.randn(1, 3, 224, 224)
43
+ >>> output = encoder(input_image)
44
+ >>> print(output.shape)
45
+ """
46
+
47
+ def __init__(
48
+ self,
49
+ img_size: int = 1024,
50
+ patch_size: int = 16,
51
+ in_chans: int = 3,
52
+ embed_dim: int = 768,
53
+ depth: int = 12,
54
+ num_heads: int = 12,
55
+ mlp_ratio: float = 4.0,
56
+ out_chans: int = 256,
57
+ qkv_bias: bool = True,
58
+ norm_layer: type[nn.Module] = nn.LayerNorm,
59
+ act_layer: type[nn.Module] = nn.GELU,
60
+ use_abs_pos: bool = True,
61
+ use_rel_pos: bool = False,
62
+ rel_pos_zero_init: bool = True,
63
+ window_size: int = 0,
64
+ global_attn_indexes: tuple[int, ...] = (),
65
+ ) -> None:
66
+ """Initialize an ImageEncoderViT instance for encoding images using Vision Transformer architecture.
67
+
68
+ Args:
69
+ img_size (int): Input image size, assumed to be square.
70
+ patch_size (int): Size of image patches.
71
+ in_chans (int): Number of input image channels.
72
+ embed_dim (int): Dimension of patch embeddings.
73
+ depth (int): Number of transformer blocks.
74
+ num_heads (int): Number of attention heads in each block.
75
+ mlp_ratio (float): Ratio of MLP hidden dimension to embedding dimension.
76
+ out_chans (int): Number of output channels from the neck module.
77
+ qkv_bias (bool): If True, adds learnable bias to query, key, value projections.
78
+ norm_layer (Type[nn.Module]): Type of normalization layer to use.
79
+ act_layer (Type[nn.Module]): Type of activation layer to use.
80
+ use_abs_pos (bool): If True, uses absolute positional embeddings.
81
+ use_rel_pos (bool): If True, adds relative positional embeddings to attention maps.
82
+ rel_pos_zero_init (bool): If True, initializes relative positional parameters to zero.
83
+ window_size (int): Size of attention window for windowed attention blocks.
84
+ global_attn_indexes (tuple[int, ...]): Indices of blocks that use global attention.
85
+ """
86
+ super().__init__()
87
+ self.img_size = img_size
88
+
89
+ self.patch_embed = PatchEmbed(
90
+ kernel_size=(patch_size, patch_size),
91
+ stride=(patch_size, patch_size),
92
+ in_chans=in_chans,
93
+ embed_dim=embed_dim,
94
+ )
95
+
96
+ self.pos_embed: nn.Parameter | None = None
97
+ if use_abs_pos:
98
+ # Initialize absolute positional embedding with pretrain image size
99
+ self.pos_embed = nn.Parameter(torch.zeros(1, img_size // patch_size, img_size // patch_size, embed_dim))
100
+
101
+ self.blocks = nn.ModuleList()
102
+ for i in range(depth):
103
+ block = Block(
104
+ dim=embed_dim,
105
+ num_heads=num_heads,
106
+ mlp_ratio=mlp_ratio,
107
+ qkv_bias=qkv_bias,
108
+ norm_layer=norm_layer,
109
+ act_layer=act_layer,
110
+ use_rel_pos=use_rel_pos,
111
+ rel_pos_zero_init=rel_pos_zero_init,
112
+ window_size=window_size if i not in global_attn_indexes else 0,
113
+ input_size=(img_size // patch_size, img_size // patch_size),
114
+ )
115
+ self.blocks.append(block)
116
+
117
+ self.neck = nn.Sequential(
118
+ nn.Conv2d(
119
+ embed_dim,
120
+ out_chans,
121
+ kernel_size=1,
122
+ bias=False,
123
+ ),
124
+ LayerNorm2d(out_chans),
125
+ nn.Conv2d(
126
+ out_chans,
127
+ out_chans,
128
+ kernel_size=3,
129
+ padding=1,
130
+ bias=False,
131
+ ),
132
+ LayerNorm2d(out_chans),
133
+ )
134
+
135
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
136
+ """Process input through patch embedding, positional embedding, transformer blocks, and neck module."""
137
+ x = self.patch_embed(x)
138
+ if self.pos_embed is not None:
139
+ pos_embed = (
140
+ F.interpolate(self.pos_embed.permute(0, 3, 1, 2), scale_factor=self.img_size / 1024).permute(0, 2, 3, 1)
141
+ if self.img_size != 1024
142
+ else self.pos_embed
143
+ )
144
+ x = x + pos_embed
145
+ for blk in self.blocks:
146
+ x = blk(x)
147
+ return self.neck(x.permute(0, 3, 1, 2))
148
+
149
+
150
+ class PromptEncoder(nn.Module):
151
+ """Encode different types of prompts for input to SAM's mask decoder, producing sparse and dense embeddings.
152
+
153
+ Attributes:
154
+ embed_dim (int): Dimension of the embeddings.
155
+ input_image_size (tuple[int, int]): Size of the input image as (H, W).
156
+ image_embedding_size (tuple[int, int]): Spatial size of the image embedding as (H, W).
157
+ pe_layer (PositionEmbeddingRandom): Module for random position embedding.
158
+ num_point_embeddings (int): Number of point embeddings for different types of points.
159
+ point_embeddings (nn.ModuleList): List of point embeddings.
160
+ not_a_point_embed (nn.Embedding): Embedding for points that are not part of any label.
161
+ mask_input_size (tuple[int, int]): Size of the input mask.
162
+ mask_downscaling (nn.Sequential): Neural network for downscaling the mask.
163
+ no_mask_embed (nn.Embedding): Embedding for cases where no mask is provided.
164
+
165
+ Methods:
166
+ get_dense_pe: Return the positional encoding used to encode point prompts.
167
+ forward: Embed different types of prompts, returning both sparse and dense embeddings.
168
+
169
+ Examples:
170
+ >>> prompt_encoder = PromptEncoder(256, (64, 64), (1024, 1024), 16)
171
+ >>> points = (torch.rand(1, 5, 2), torch.randint(0, 4, (1, 5)))
172
+ >>> boxes = torch.rand(1, 2, 2)
173
+ >>> masks = torch.rand(1, 1, 256, 256)
174
+ >>> sparse_embeddings, dense_embeddings = prompt_encoder(points, boxes, masks)
175
+ >>> print(sparse_embeddings.shape, dense_embeddings.shape)
176
+ torch.Size([1, 7, 256]) torch.Size([1, 256, 64, 64])
177
+ """
178
+
179
+ def __init__(
180
+ self,
181
+ embed_dim: int,
182
+ image_embedding_size: tuple[int, int],
183
+ input_image_size: tuple[int, int],
184
+ mask_in_chans: int,
185
+ activation: type[nn.Module] = nn.GELU,
186
+ ) -> None:
187
+ """Initialize the PromptEncoder module for encoding various types of prompts.
188
+
189
+ Args:
190
+ embed_dim (int): The dimension of the embeddings.
191
+ image_embedding_size (tuple[int, int]): The spatial size of the image embedding as (H, W).
192
+ input_image_size (tuple[int, int]): The padded size of the input image as (H, W).
193
+ mask_in_chans (int): The number of hidden channels used for encoding input masks.
194
+ activation (Type[nn.Module]): The activation function to use when encoding input masks.
195
+ """
196
+ super().__init__()
197
+ self.embed_dim = embed_dim
198
+ self.input_image_size = input_image_size
199
+ self.image_embedding_size = image_embedding_size
200
+ self.pe_layer = PositionEmbeddingRandom(embed_dim // 2)
201
+
202
+ self.num_point_embeddings: int = 4 # pos/neg point + 2 box corners
203
+ point_embeddings = [nn.Embedding(1, embed_dim) for _ in range(self.num_point_embeddings)]
204
+ self.point_embeddings = nn.ModuleList(point_embeddings)
205
+ self.not_a_point_embed = nn.Embedding(1, embed_dim)
206
+
207
+ self.mask_input_size = (4 * image_embedding_size[0], 4 * image_embedding_size[1])
208
+ self.mask_downscaling = nn.Sequential(
209
+ nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2),
210
+ LayerNorm2d(mask_in_chans // 4),
211
+ activation(),
212
+ nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2),
213
+ LayerNorm2d(mask_in_chans),
214
+ activation(),
215
+ nn.Conv2d(mask_in_chans, embed_dim, kernel_size=1),
216
+ )
217
+ self.no_mask_embed = nn.Embedding(1, embed_dim)
218
+
219
+ def get_dense_pe(self) -> torch.Tensor:
220
+ """Return the dense positional encoding used for encoding point prompts.
221
+
222
+ Generate a positional encoding for a dense set of points matching the shape of the image
223
+ encoding. The encoding is used to provide spatial information to the model when processing point prompts.
224
+
225
+ Returns:
226
+ (torch.Tensor): Positional encoding tensor with shape (1, embed_dim, H, W), where H and W are the height and
227
+ width of the image embedding size, respectively.
228
+
229
+ Examples:
230
+ >>> prompt_encoder = PromptEncoder(256, (64, 64), (1024, 1024), 16)
231
+ >>> dense_pe = prompt_encoder.get_dense_pe()
232
+ >>> print(dense_pe.shape)
233
+ torch.Size([1, 256, 64, 64])
234
+ """
235
+ return self.pe_layer(self.image_embedding_size).unsqueeze(0)
236
+
237
+ def _embed_points(self, points: torch.Tensor, labels: torch.Tensor, pad: bool) -> torch.Tensor:
238
+ """Embed point prompts by applying positional encoding and label-specific embeddings."""
239
+ points = points + 0.5 # Shift to center of pixel
240
+ if pad:
241
+ padding_point = torch.zeros((points.shape[0], 1, 2), dtype=points.dtype, device=points.device)
242
+ padding_label = -torch.ones((labels.shape[0], 1), dtype=labels.dtype, device=labels.device)
243
+ points = torch.cat([points, padding_point], dim=1)
244
+ labels = torch.cat([labels, padding_label], dim=1)
245
+ point_embedding = self.pe_layer.forward_with_coords(points, self.input_image_size)
246
+ point_embedding[labels == -1] = 0.0
247
+ point_embedding[labels == -1] += self.not_a_point_embed.weight
248
+ point_embedding[labels == 0] += self.point_embeddings[0].weight
249
+ point_embedding[labels == 1] += self.point_embeddings[1].weight
250
+ point_embedding[labels == 2] += self.point_embeddings[2].weight
251
+ point_embedding[labels == 3] += self.point_embeddings[3].weight
252
+ return point_embedding
253
+
254
+ def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor:
255
+ """Embed box prompts by applying positional encoding and adding corner embeddings."""
256
+ boxes = boxes + 0.5 # Shift to center of pixel
257
+ coords = boxes.reshape(-1, 2, 2)
258
+ corner_embedding = self.pe_layer.forward_with_coords(coords, self.input_image_size)
259
+ corner_embedding[:, 0, :] += self.point_embeddings[2].weight
260
+ corner_embedding[:, 1, :] += self.point_embeddings[3].weight
261
+ return corner_embedding
262
+
263
+ def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor:
264
+ """Embed mask inputs by downscaling and processing through convolutional layers."""
265
+ return self.mask_downscaling(masks)
266
+
267
+ @staticmethod
268
+ def _get_batch_size(
269
+ points: tuple[torch.Tensor, torch.Tensor] | None,
270
+ boxes: torch.Tensor | None,
271
+ masks: torch.Tensor | None,
272
+ ) -> int:
273
+ """Get the batch size of the output given the batch size of the input prompts."""
274
+ if points is not None:
275
+ return points[0].shape[0]
276
+ elif boxes is not None:
277
+ return boxes.shape[0]
278
+ elif masks is not None:
279
+ return masks.shape[0]
280
+ else:
281
+ return 1
282
+
283
+ def forward(
284
+ self,
285
+ points: tuple[torch.Tensor, torch.Tensor] | None,
286
+ boxes: torch.Tensor | None,
287
+ masks: torch.Tensor | None,
288
+ ) -> tuple[torch.Tensor, torch.Tensor]:
289
+ """Embed different types of prompts, returning both sparse and dense embeddings.
290
+
291
+ Args:
292
+ points (tuple[torch.Tensor, torch.Tensor] | None): Point coordinates and labels to embed. The first tensor
293
+ contains coordinates of shape (B, N, 2), and the second tensor contains labels of shape (B, N).
294
+ boxes (torch.Tensor | None): Boxes to embed with shape (B, M, 2, 2), where M is the number of boxes.
295
+ masks (torch.Tensor | None): Masks to embed with shape (B, 1, H, W).
296
+
297
+ Returns:
298
+ sparse_embeddings (torch.Tensor): Sparse embeddings for points and boxes with shape (B, N, embed_dim).
299
+ dense_embeddings (torch.Tensor): Dense embeddings for masks of shape (B, embed_dim, embed_H, embed_W).
300
+
301
+ Examples:
302
+ >>> encoder = PromptEncoder(256, (64, 64), (1024, 1024), 16)
303
+ >>> points = (torch.rand(1, 5, 2), torch.randint(0, 4, (1, 5)))
304
+ >>> boxes = torch.rand(1, 2, 2, 2)
305
+ >>> masks = torch.rand(1, 1, 256, 256)
306
+ >>> sparse_emb, dense_emb = encoder(points, boxes, masks)
307
+ >>> print(sparse_emb.shape, dense_emb.shape)
308
+ torch.Size([1, 7, 256]) torch.Size([1, 256, 64, 64])
309
+ """
310
+ bs = self._get_batch_size(points, boxes, masks)
311
+ sparse_embeddings = torch.empty(
312
+ (bs, 0, self.embed_dim),
313
+ dtype=self.point_embeddings[0].weight.dtype,
314
+ device=self.point_embeddings[0].weight.device,
315
+ )
316
+ if points is not None:
317
+ coords, labels = points
318
+ point_embeddings = self._embed_points(coords, labels, pad=(boxes is None))
319
+ sparse_embeddings = torch.cat([sparse_embeddings, point_embeddings], dim=1)
320
+ if boxes is not None:
321
+ box_embeddings = self._embed_boxes(boxes)
322
+ sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=1)
323
+
324
+ if masks is not None:
325
+ dense_embeddings = self._embed_masks(masks)
326
+ else:
327
+ dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).expand(
328
+ bs, -1, self.image_embedding_size[0], self.image_embedding_size[1]
329
+ )
330
+
331
+ return sparse_embeddings, dense_embeddings
332
+
333
+
334
+ class MemoryEncoder(nn.Module):
335
+ """Encode pixel features and masks into a memory representation for efficient image segmentation.
336
+
337
+ This class processes pixel-level features and masks, fusing them to generate encoded memory representations suitable
338
+ for downstream tasks in image segmentation models like SAM (Segment Anything Model).
339
+
340
+ Attributes:
341
+ mask_downsampler (MaskDownSampler): Module for downsampling input masks.
342
+ pix_feat_proj (nn.Conv2d): Convolutional layer for projecting pixel features.
343
+ fuser (Fuser): Module for fusing pixel features and masks.
344
+ position_encoding (PositionEmbeddingSine): Module for adding positional encoding to features.
345
+ out_proj (nn.Module): Output projection layer, either nn.Identity or nn.Conv2d.
346
+
347
+ Methods:
348
+ forward: Process input pixel features and masks to generate encoded memory representations.
349
+
350
+ Examples:
351
+ >>> import torch
352
+ >>> encoder = MemoryEncoder(out_dim=256, in_dim=256)
353
+ >>> pix_feat = torch.randn(1, 256, 64, 64)
354
+ >>> masks = torch.randn(1, 1, 64, 64)
355
+ >>> encoded_feat, pos = encoder(pix_feat, masks)
356
+ >>> print(encoded_feat.shape, pos.shape)
357
+ torch.Size([1, 256, 64, 64]) torch.Size([1, 128, 64, 64])
358
+ """
359
+
360
+ def __init__(
361
+ self,
362
+ out_dim,
363
+ in_dim=256, # in_dim of pix_feats
364
+ interpol_size: tuple[int, int] | None = None,
365
+ ):
366
+ """Initialize the MemoryEncoder for encoding pixel features and masks into memory representations.
367
+
368
+ This encoder processes pixel-level features and masks, fusing them to generate encoded memory representations
369
+ suitable for downstream tasks in image segmentation models like SAM (Segment Anything Model).
370
+
371
+ Args:
372
+ out_dim (int): Output dimension of the encoded features.
373
+ in_dim (int): Input dimension of the pixel features.
374
+ interpol_size (tuple[int, int] | None): Size to interpolate masks to. If None, uses the size of pixel
375
+ features.
376
+ """
377
+ super().__init__()
378
+
379
+ self.mask_downsampler = MaskDownSampler(kernel_size=3, stride=2, padding=1, interpol_size=interpol_size)
380
+
381
+ self.pix_feat_proj = nn.Conv2d(in_dim, in_dim, kernel_size=1)
382
+ self.fuser = Fuser(CXBlock(dim=256), num_layers=2)
383
+ self.position_encoding = PositionEmbeddingSine(num_pos_feats=64)
384
+ self.out_proj = nn.Identity()
385
+ if out_dim != in_dim:
386
+ self.out_proj = nn.Conv2d(in_dim, out_dim, kernel_size=1)
387
+
388
+ def forward(
389
+ self,
390
+ pix_feat: torch.Tensor,
391
+ masks: torch.Tensor,
392
+ skip_mask_sigmoid: bool = False,
393
+ ) -> dict:
394
+ """Process pixel features and masks to generate encoded memory representations for segmentation."""
395
+ if not skip_mask_sigmoid:
396
+ masks = F.sigmoid(masks)
397
+ masks = self.mask_downsampler(masks)
398
+
399
+ # Fuse pix_feats and downsampled masks, in case the visual features are on CPU, cast them to CUDA
400
+ pix_feat = pix_feat.to(masks.device)
401
+
402
+ x = self.pix_feat_proj(pix_feat)
403
+ x = x + masks
404
+ x = self.fuser(x)
405
+ x = self.out_proj(x)
406
+
407
+ pos = self.position_encoding(x).to(x.dtype)
408
+
409
+ return {"vision_features": x, "vision_pos_enc": [pos]}
410
+
411
+
412
+ class ImageEncoder(nn.Module):
413
+ """Encode images using a trunk-neck architecture, producing multiscale features and positional encodings.
414
+
415
+ This class combines a trunk network for feature extraction with a neck network for feature refinement and positional
416
+ encoding generation. It can optionally discard the lowest resolution features.
417
+
418
+ Attributes:
419
+ trunk (nn.Module): The trunk network for initial feature extraction.
420
+ neck (nn.Module): The neck network for feature refinement and positional encoding generation.
421
+ scalp (int): Number of lowest resolution feature levels to discard.
422
+
423
+ Methods:
424
+ forward: Process the input image through the trunk and neck networks.
425
+
426
+ Examples:
427
+ >>> trunk = SomeTrunkNetwork()
428
+ >>> neck = SomeNeckNetwork()
429
+ >>> encoder = ImageEncoder(trunk, neck, scalp=1)
430
+ >>> image = torch.randn(1, 3, 224, 224)
431
+ >>> output = encoder(image)
432
+ >>> print(output.keys())
433
+ dict_keys(['vision_features', 'vision_pos_enc', 'backbone_fpn'])
434
+ """
435
+
436
+ def __init__(
437
+ self,
438
+ trunk: nn.Module,
439
+ neck: nn.Module,
440
+ scalp: int = 0,
441
+ ):
442
+ """Initialize the ImageEncoder with trunk and neck networks for feature extraction and refinement.
443
+
444
+ This encoder combines a trunk network for feature extraction with a neck network for feature refinement and
445
+ positional encoding generation. It can optionally discard the lowest resolution features.
446
+
447
+ Args:
448
+ trunk (nn.Module): The trunk network for initial feature extraction.
449
+ neck (nn.Module): The neck network for feature refinement and positional encoding generation.
450
+ scalp (int): Number of lowest resolution feature levels to discard.
451
+ """
452
+ super().__init__()
453
+ self.trunk = trunk
454
+ self.neck = neck
455
+ self.scalp = scalp
456
+ assert self.trunk.channel_list == self.neck.backbone_channel_list, (
457
+ f"Channel dims of trunk {self.trunk.channel_list} and neck {self.neck.backbone_channel_list} do not match."
458
+ )
459
+
460
+ def forward(self, sample: torch.Tensor):
461
+ """Encode input through trunk and neck networks, returning multiscale features and positional encodings."""
462
+ features, pos = self.neck(self.trunk(sample))
463
+ if self.scalp > 0:
464
+ # Discard the lowest resolution features
465
+ features, pos = features[: -self.scalp], pos[: -self.scalp]
466
+
467
+ src = features[-1]
468
+ return {
469
+ "vision_features": src,
470
+ "vision_pos_enc": pos,
471
+ "backbone_fpn": features,
472
+ }
473
+
474
+
475
+ class FpnNeck(nn.Module):
476
+ """A Feature Pyramid Network (FPN) neck variant for multiscale feature fusion in object detection models.
477
+
478
+ This FPN variant removes the output convolution and uses bicubic interpolation for feature resizing, similar to ViT
479
+ positional embedding interpolation.
480
+
481
+ Attributes:
482
+ position_encoding (PositionEmbeddingSine): Sinusoidal positional encoding module.
483
+ convs (nn.ModuleList): List of convolutional layers for each backbone level.
484
+ backbone_channel_list (list[int]): List of channel dimensions from the backbone.
485
+ fpn_interp_model (str): Interpolation mode for FPN feature resizing.
486
+ fuse_type (str): Type of feature fusion, either 'sum' or 'avg'.
487
+ fpn_top_down_levels (list[int]): Levels to have top-down features in outputs.
488
+
489
+ Methods:
490
+ forward: Perform forward pass through the FPN neck.
491
+
492
+ Examples:
493
+ >>> backbone_channels = [64, 128, 256, 512]
494
+ >>> fpn_neck = FpnNeck(256, backbone_channels)
495
+ >>> inputs = [torch.rand(1, c, 32, 32) for c in backbone_channels]
496
+ >>> outputs, positions = fpn_neck(inputs)
497
+ >>> print(len(outputs), len(positions))
498
+ 4 4
499
+ """
500
+
501
+ def __init__(
502
+ self,
503
+ d_model: int,
504
+ backbone_channel_list: list[int],
505
+ kernel_size: int = 1,
506
+ stride: int = 1,
507
+ padding: int = 0,
508
+ fpn_interp_model: str = "bilinear",
509
+ fuse_type: str = "sum",
510
+ fpn_top_down_levels: list[int] | None = None,
511
+ ):
512
+ """Initialize a modified Feature Pyramid Network (FPN) neck.
513
+
514
+ This FPN variant removes the output convolution and uses bicubic interpolation for feature resizing, similar to
515
+ ViT positional embedding interpolation.
516
+
517
+ Args:
518
+ d_model (int): Dimension of the model.
519
+ backbone_channel_list (list[int]): List of channel dimensions from the backbone.
520
+ kernel_size (int): Kernel size for the convolutional layers.
521
+ stride (int): Stride for the convolutional layers.
522
+ padding (int): Padding for the convolutional layers.
523
+ fpn_interp_model (str): Interpolation mode for FPN feature resizing.
524
+ fuse_type (str): Type of feature fusion, either 'sum' or 'avg'.
525
+ fpn_top_down_levels (Optional[list[int]]): Levels to have top-down features in outputs.
526
+ """
527
+ super().__init__()
528
+ self.position_encoding = PositionEmbeddingSine(num_pos_feats=256)
529
+ self.convs = nn.ModuleList()
530
+ self.backbone_channel_list = backbone_channel_list
531
+ for dim in backbone_channel_list:
532
+ current = nn.Sequential()
533
+ current.add_module(
534
+ "conv",
535
+ nn.Conv2d(
536
+ in_channels=dim,
537
+ out_channels=d_model,
538
+ kernel_size=kernel_size,
539
+ stride=stride,
540
+ padding=padding,
541
+ ),
542
+ )
543
+
544
+ self.convs.append(current)
545
+ self.fpn_interp_model = fpn_interp_model
546
+ assert fuse_type in {"sum", "avg"}
547
+ self.fuse_type = fuse_type
548
+
549
+ # Levels to have top-down features in its outputs
550
+ # e.g. if fpn_top_down_levels is [2, 3], then only outputs of level 2 and 3
551
+ # have top-down propagation, while outputs of level 0 and level 1 have only
552
+ # lateral features from the same backbone level
553
+ if fpn_top_down_levels is None:
554
+ # Default is to have top-down features on all levels
555
+ fpn_top_down_levels = range(len(self.convs))
556
+ self.fpn_top_down_levels = list(fpn_top_down_levels)
557
+
558
+ def forward(self, xs: list[torch.Tensor]):
559
+ """Perform forward pass through the Feature Pyramid Network (FPN) neck.
560
+
561
+ This method processes a list of input tensors from the backbone through the FPN, applying lateral connections
562
+ and top-down feature fusion. It generates output feature maps and corresponding positional encodings.
563
+
564
+ Args:
565
+ xs (list[torch.Tensor]): List of input tensors from the backbone, each with shape (B, C, H, W).
566
+
567
+ Returns:
568
+ out (list[torch.Tensor]): List of output feature maps after FPN processing, each with shape (B, d_model, H,
569
+ W).
570
+ pos (list[torch.Tensor]): List of positional encodings corresponding to each output feature map.
571
+
572
+ Examples:
573
+ >>> fpn_neck = FpnNeck(d_model=256, backbone_channel_list=[64, 128, 256, 512])
574
+ >>> inputs = [torch.rand(1, c, 32, 32) for c in [64, 128, 256, 512]]
575
+ >>> outputs, positions = fpn_neck(inputs)
576
+ >>> print(len(outputs), len(positions))
577
+ 4 4
578
+ """
579
+ out = [None] * len(self.convs)
580
+ pos = [None] * len(self.convs)
581
+ assert len(xs) == len(self.convs)
582
+ # FPN forward pass
583
+ # see https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/fpn.py
584
+ prev_features = None
585
+ # Forward in top-down order (from low to high resolution)
586
+ n = len(self.convs) - 1
587
+ for i in range(n, -1, -1):
588
+ x = xs[i]
589
+ lateral_features = self.convs[n - i](x)
590
+ if i in self.fpn_top_down_levels and prev_features is not None:
591
+ top_down_features = F.interpolate(
592
+ prev_features.to(dtype=x.dtype),
593
+ scale_factor=2.0,
594
+ mode=self.fpn_interp_model,
595
+ align_corners=(None if self.fpn_interp_model == "nearest" else False),
596
+ antialias=False,
597
+ )
598
+ prev_features = lateral_features + top_down_features
599
+ if self.fuse_type == "avg":
600
+ prev_features /= 2
601
+ else:
602
+ prev_features = lateral_features
603
+ x_out = prev_features
604
+ out[i] = x_out
605
+ pos[i] = self.position_encoding(x_out).to(x_out.dtype)
606
+
607
+ return out, pos
608
+
609
+
610
+ class Hiera(nn.Module):
611
+ """Hierarchical vision transformer for efficient multiscale feature extraction in image processing tasks.
612
+
613
+ This class implements a Hiera model, which is a hierarchical vision transformer architecture designed for efficient
614
+ multiscale feature extraction. It uses a series of transformer blocks organized into stages, with optional pooling
615
+ and global attention mechanisms.
616
+
617
+ Attributes:
618
+ window_spec (tuple[int, ...]): Window sizes for each stage.
619
+ q_stride (tuple[int, int]): Downsampling stride between stages.
620
+ stage_ends (list[int]): Indices of the last block in each stage.
621
+ q_pool_blocks (list[int]): Indices of blocks where pooling is applied.
622
+ return_interm_layers (bool): Whether to return intermediate layer outputs.
623
+ patch_embed (PatchEmbed): Module for patch embedding.
624
+ global_att_blocks (tuple[int, ...]): Indices of blocks with global attention.
625
+ window_pos_embed_bkg_spatial_size (tuple[int, int]): Spatial size for window positional embedding background.
626
+ pos_embed (nn.Parameter): Positional embedding for the background.
627
+ pos_embed_window (nn.Parameter): Positional embedding for the window.
628
+ blocks (nn.ModuleList): List of MultiScaleBlock modules.
629
+ channel_list (list[int]): List of output channel dimensions for each stage.
630
+
631
+ Methods:
632
+ _get_pos_embed: Generate positional embeddings by interpolating and combining window and background embeddings.
633
+ forward: Perform the forward pass through the Hiera model.
634
+
635
+ Examples:
636
+ >>> model = Hiera(embed_dim=96, num_heads=1, stages=(2, 3, 16, 3))
637
+ >>> input_tensor = torch.randn(1, 3, 224, 224)
638
+ >>> output_features = model(input_tensor)
639
+ >>> for feat in output_features:
640
+ ... print(feat.shape)
641
+ """
642
+
643
+ def __init__(
644
+ self,
645
+ embed_dim: int = 96, # initial embed dim
646
+ num_heads: int = 1, # initial number of heads
647
+ drop_path_rate: float = 0.0, # stochastic depth
648
+ q_pool: int = 3, # number of q_pool stages
649
+ q_stride: tuple[int, int] = (2, 2), # downsample stride bet. stages
650
+ stages: tuple[int, ...] = (2, 3, 16, 3), # blocks per stage
651
+ dim_mul: float = 2.0, # dim_mul factor at stage shift
652
+ head_mul: float = 2.0, # head_mul factor at stage shift
653
+ window_pos_embed_bkg_spatial_size: tuple[int, int] = (14, 14),
654
+ # window size per stage, when not using global att.
655
+ window_spec: tuple[int, ...] = (
656
+ 8,
657
+ 4,
658
+ 14,
659
+ 7,
660
+ ),
661
+ # global attn in these blocks
662
+ global_att_blocks: tuple[int, ...] = (
663
+ 12,
664
+ 16,
665
+ 20,
666
+ ),
667
+ return_interm_layers=True, # return feats from every stage
668
+ ):
669
+ """Initialize a Hiera model, a hierarchical vision transformer for efficient multiscale feature extraction.
670
+
671
+ Hiera is a hierarchical vision transformer architecture designed for efficient multiscale feature extraction in
672
+ image processing tasks. It uses a series of transformer blocks organized into stages, with optional pooling and
673
+ global attention mechanisms.
674
+
675
+ Args:
676
+ embed_dim (int): Initial embedding dimension for the model.
677
+ num_heads (int): Initial number of attention heads.
678
+ drop_path_rate (float): Stochastic depth rate.
679
+ q_pool (int): Number of query pooling stages.
680
+ q_stride (tuple[int, int]): Downsampling stride between stages.
681
+ stages (tuple[int, ...]): Number of blocks per stage.
682
+ dim_mul (float): Dimension multiplier factor at stage transitions.
683
+ head_mul (float): Head multiplier factor at stage transitions.
684
+ window_pos_embed_bkg_spatial_size (tuple[int, int]): Spatial size for window positional embedding
685
+ background.
686
+ window_spec (tuple[int, ...]): Window sizes for each stage when not using global attention.
687
+ global_att_blocks (tuple[int, ...]): Indices of blocks that use global attention.
688
+ return_interm_layers (bool): Whether to return intermediate layer outputs.
689
+ """
690
+ super().__init__()
691
+
692
+ assert len(stages) == len(window_spec)
693
+ self.window_spec = window_spec
694
+
695
+ depth = sum(stages)
696
+ self.q_stride = q_stride
697
+ self.stage_ends = [sum(stages[:i]) - 1 for i in range(1, len(stages) + 1)]
698
+ assert 0 <= q_pool <= len(self.stage_ends[:-1])
699
+ self.q_pool_blocks = [x + 1 for x in self.stage_ends[:-1]][:q_pool]
700
+ self.return_interm_layers = return_interm_layers
701
+
702
+ self.patch_embed = PatchEmbed(
703
+ embed_dim=embed_dim,
704
+ kernel_size=(7, 7),
705
+ stride=(4, 4),
706
+ padding=(3, 3),
707
+ )
708
+ # Which blocks have global attention?
709
+ self.global_att_blocks = global_att_blocks
710
+
711
+ # Windowed positional embedding (https://arxiv.org/abs/2311.05613)
712
+ self.window_pos_embed_bkg_spatial_size = window_pos_embed_bkg_spatial_size
713
+ self.pos_embed = nn.Parameter(torch.zeros(1, embed_dim, *self.window_pos_embed_bkg_spatial_size))
714
+ self.pos_embed_window = nn.Parameter(torch.zeros(1, embed_dim, self.window_spec[0], self.window_spec[0]))
715
+
716
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
717
+
718
+ cur_stage = 1
719
+ self.blocks = nn.ModuleList()
720
+
721
+ for i in range(depth):
722
+ dim_out = embed_dim
723
+ # Lags by a block, so first block of next stage uses an initial window size
724
+ # of previous stage and final window size of current stage
725
+ window_size = self.window_spec[cur_stage - 1]
726
+
727
+ if self.global_att_blocks is not None:
728
+ window_size = 0 if i in self.global_att_blocks else window_size
729
+
730
+ if i - 1 in self.stage_ends:
731
+ dim_out = int(embed_dim * dim_mul)
732
+ num_heads = int(num_heads * head_mul)
733
+ cur_stage += 1
734
+
735
+ block = MultiScaleBlock(
736
+ dim=embed_dim,
737
+ dim_out=dim_out,
738
+ num_heads=num_heads,
739
+ drop_path=dpr[i],
740
+ q_stride=self.q_stride if i in self.q_pool_blocks else None,
741
+ window_size=window_size,
742
+ )
743
+
744
+ embed_dim = dim_out
745
+ self.blocks.append(block)
746
+
747
+ self.channel_list = (
748
+ [self.blocks[i].dim_out for i in self.stage_ends[::-1]]
749
+ if return_interm_layers
750
+ else [self.blocks[-1].dim_out]
751
+ )
752
+
753
+ def _get_pos_embed(self, hw: tuple[int, int]) -> torch.Tensor:
754
+ """Generate positional embeddings by interpolating and combining window and background embeddings."""
755
+ h, w = hw
756
+ window_embed = self.pos_embed_window
757
+ pos_embed = F.interpolate(self.pos_embed, size=(h, w), mode="bicubic")
758
+ pos_embed = pos_embed + window_embed.tile([x // y for x, y in zip(pos_embed.shape, window_embed.shape)])
759
+ pos_embed = pos_embed.permute(0, 2, 3, 1)
760
+ return pos_embed
761
+
762
+ def forward(self, x: torch.Tensor) -> list[torch.Tensor]:
763
+ """Perform forward pass through Hiera model, extracting multiscale features from input images.
764
+
765
+ Args:
766
+ x (torch.Tensor): Input tensor with shape (B, C, H, W) representing a batch of images.
767
+
768
+ Returns:
769
+ (list[torch.Tensor]): List of feature maps at different scales, each with shape (B, C_i, H_i, W_i), where
770
+ C_i is the channel dimension and H_i, W_i are the spatial dimensions at scale i. The list is ordered
771
+ from highest resolution (fine features) to lowest resolution (coarse features) if return_interm_layers
772
+ is True, otherwise contains only the final output.
773
+
774
+ Examples:
775
+ >>> model = Hiera(embed_dim=96, num_heads=1, stages=(2, 3, 16, 3))
776
+ >>> input_tensor = torch.randn(1, 3, 224, 224)
777
+ >>> output_features = model(input_tensor)
778
+ >>> for feat in output_features:
779
+ ... print(feat.shape)
780
+ """
781
+ x = self.patch_embed(x)
782
+ # x: (B, H, W, C)
783
+
784
+ # Add positional embedding
785
+ x = x + self._get_pos_embed(x.shape[1:3])
786
+
787
+ outputs = []
788
+ for i, blk in enumerate(self.blocks):
789
+ x = blk(x)
790
+ if (i == self.stage_ends[-1]) or (i in self.stage_ends and self.return_interm_layers):
791
+ feats = x.permute(0, 3, 1, 2)
792
+ outputs.append(feats)
793
+
794
+ return outputs