dgenerate-ultralytics-headless 8.3.134__py3-none-any.whl

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