ultralytics 8.2.71__py3-none-any.whl → 8.2.73__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.

Potentially problematic release.


This version of ultralytics might be problematic. Click here for more details.

Files changed (35) hide show
  1. tests/test_cli.py +3 -0
  2. ultralytics/__init__.py +2 -3
  3. ultralytics/models/__init__.py +1 -2
  4. ultralytics/models/sam/__init__.py +2 -2
  5. ultralytics/models/sam/amg.py +27 -21
  6. ultralytics/models/sam/build.py +200 -9
  7. ultralytics/models/sam/model.py +86 -34
  8. ultralytics/models/sam/modules/blocks.py +1131 -0
  9. ultralytics/models/sam/modules/decoders.py +390 -23
  10. ultralytics/models/sam/modules/encoders.py +508 -323
  11. ultralytics/models/{sam2 → sam}/modules/memory_attention.py +73 -6
  12. ultralytics/models/sam/modules/sam.py +887 -16
  13. ultralytics/models/sam/modules/tiny_encoder.py +376 -126
  14. ultralytics/models/sam/modules/transformer.py +155 -54
  15. ultralytics/models/{sam2 → sam}/modules/utils.py +105 -3
  16. ultralytics/models/sam/predict.py +382 -92
  17. ultralytics/nn/modules/transformer.py +2 -2
  18. ultralytics/utils/downloads.py +2 -2
  19. ultralytics/utils/ops.py +2 -2
  20. ultralytics/utils/plotting.py +3 -3
  21. {ultralytics-8.2.71.dist-info → ultralytics-8.2.73.dist-info}/METADATA +44 -44
  22. {ultralytics-8.2.71.dist-info → ultralytics-8.2.73.dist-info}/RECORD +26 -34
  23. ultralytics/models/sam2/__init__.py +0 -6
  24. ultralytics/models/sam2/build.py +0 -156
  25. ultralytics/models/sam2/model.py +0 -97
  26. ultralytics/models/sam2/modules/__init__.py +0 -1
  27. ultralytics/models/sam2/modules/decoders.py +0 -305
  28. ultralytics/models/sam2/modules/encoders.py +0 -332
  29. ultralytics/models/sam2/modules/sam2.py +0 -804
  30. ultralytics/models/sam2/modules/sam2_blocks.py +0 -715
  31. ultralytics/models/sam2/predict.py +0 -182
  32. {ultralytics-8.2.71.dist-info → ultralytics-8.2.73.dist-info}/LICENSE +0 -0
  33. {ultralytics-8.2.71.dist-info → ultralytics-8.2.73.dist-info}/WHEEL +0 -0
  34. {ultralytics-8.2.71.dist-info → ultralytics-8.2.73.dist-info}/entry_points.txt +0 -0
  35. {ultralytics-8.2.71.dist-info → ultralytics-8.2.73.dist-info}/top_level.txt +0 -0
@@ -1,305 +0,0 @@
1
- # Ultralytics YOLO 🚀, AGPL-3.0 license
2
-
3
- from typing import List, Optional, Tuple, Type
4
-
5
- import torch
6
- from torch import nn
7
-
8
- from ultralytics.nn.modules import MLP, LayerNorm2d
9
-
10
-
11
- class MaskDecoder(nn.Module):
12
- """Transformer-based decoder predicting instance segmentation masks from image and prompt embeddings."""
13
-
14
- def __init__(
15
- self,
16
- transformer_dim: int,
17
- transformer: nn.Module,
18
- num_multimask_outputs: int = 3,
19
- activation: Type[nn.Module] = nn.GELU,
20
- iou_head_depth: int = 3,
21
- iou_head_hidden_dim: int = 256,
22
- use_high_res_features: bool = False,
23
- iou_prediction_use_sigmoid=False,
24
- dynamic_multimask_via_stability=False,
25
- dynamic_multimask_stability_delta=0.05,
26
- dynamic_multimask_stability_thresh=0.98,
27
- pred_obj_scores: bool = False,
28
- pred_obj_scores_mlp: bool = False,
29
- use_multimask_token_for_obj_ptr: bool = False,
30
- ) -> None:
31
- """
32
- Initializes the MaskDecoder module for predicting instance segmentation masks.
33
-
34
- Args:
35
- transformer_dim (int): Channel dimension of the transformer.
36
- transformer (nn.Module): Transformer used to predict masks.
37
- num_multimask_outputs (int): Number of masks to predict when disambiguating masks.
38
- activation (Type[nn.Module]): Type of activation to use when upscaling masks.
39
- iou_head_depth (int): Depth of the MLP used to predict mask quality.
40
- iou_head_hidden_dim (int): Hidden dimension of the MLP used to predict mask quality.
41
- use_high_res_features (bool): Whether to use high-resolution features.
42
- iou_prediction_use_sigmoid (bool): Whether to use sigmoid for IOU prediction.
43
- dynamic_multimask_via_stability (bool): Whether to use dynamic multimask via stability.
44
- dynamic_multimask_stability_delta (float): Delta value for dynamic multimask stability.
45
- dynamic_multimask_stability_thresh (float): Threshold for dynamic multimask stability.
46
- pred_obj_scores (bool): Whether to predict object scores.
47
- pred_obj_scores_mlp (bool): Whether to use MLP for object score prediction.
48
- use_multimask_token_for_obj_ptr (bool): Whether to use multimask token for object pointer.
49
-
50
- Attributes:
51
- transformer_dim (int): Channel dimension of the transformer.
52
- transformer (nn.Module): Transformer used to predict masks.
53
- num_multimask_outputs (int): Number of masks to predict when disambiguating masks.
54
- iou_token (nn.Embedding): Embedding for IOU token.
55
- num_mask_tokens (int): Total number of mask tokens.
56
- mask_tokens (nn.Embedding): Embedding for mask tokens.
57
- pred_obj_scores (bool): Whether to predict object scores.
58
- obj_score_token (nn.Embedding): Embedding for object score token.
59
- use_multimask_token_for_obj_ptr (bool): Whether to use multimask token for object pointer.
60
- output_upscaling (nn.Sequential): Upscaling layers for output.
61
- use_high_res_features (bool): Whether to use high-resolution features.
62
- conv_s0 (nn.Conv2d): Convolutional layer for high-resolution features (s0).
63
- conv_s1 (nn.Conv2d): Convolutional layer for high-resolution features (s1).
64
- output_hypernetworks_mlps (nn.ModuleList): List of MLPs for output hypernetworks.
65
- iou_prediction_head (MLP): MLP for IOU prediction.
66
- pred_obj_score_head (nn.Linear | MLP): Linear layer or MLP for object score prediction.
67
- dynamic_multimask_via_stability (bool): Whether to use dynamic multimask via stability.
68
- dynamic_multimask_stability_delta (float): Delta value for dynamic multimask stability.
69
- """
70
- super().__init__()
71
- self.transformer_dim = transformer_dim
72
- self.transformer = transformer
73
-
74
- self.num_multimask_outputs = num_multimask_outputs
75
-
76
- self.iou_token = nn.Embedding(1, transformer_dim)
77
- self.num_mask_tokens = num_multimask_outputs + 1
78
- self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim)
79
-
80
- self.pred_obj_scores = pred_obj_scores
81
- if self.pred_obj_scores:
82
- self.obj_score_token = nn.Embedding(1, transformer_dim)
83
- self.use_multimask_token_for_obj_ptr = use_multimask_token_for_obj_ptr
84
-
85
- self.output_upscaling = nn.Sequential(
86
- nn.ConvTranspose2d(transformer_dim, transformer_dim // 4, kernel_size=2, stride=2),
87
- LayerNorm2d(transformer_dim // 4),
88
- activation(),
89
- nn.ConvTranspose2d(transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2),
90
- activation(),
91
- )
92
- self.use_high_res_features = use_high_res_features
93
- if use_high_res_features:
94
- self.conv_s0 = nn.Conv2d(transformer_dim, transformer_dim // 8, kernel_size=1, stride=1)
95
- self.conv_s1 = nn.Conv2d(transformer_dim, transformer_dim // 4, kernel_size=1, stride=1)
96
-
97
- self.output_hypernetworks_mlps = nn.ModuleList(
98
- [MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3) for _ in range(self.num_mask_tokens)]
99
- )
100
-
101
- self.iou_prediction_head = MLP(
102
- transformer_dim,
103
- iou_head_hidden_dim,
104
- self.num_mask_tokens,
105
- iou_head_depth,
106
- sigmoid=iou_prediction_use_sigmoid,
107
- )
108
- if self.pred_obj_scores:
109
- self.pred_obj_score_head = nn.Linear(transformer_dim, 1)
110
- if pred_obj_scores_mlp:
111
- self.pred_obj_score_head = MLP(transformer_dim, transformer_dim, 1, 3)
112
-
113
- # When outputting a single mask, optionally we can dynamically fall back to the best
114
- # multimask output token if the single mask output token gives low stability scores.
115
- self.dynamic_multimask_via_stability = dynamic_multimask_via_stability
116
- self.dynamic_multimask_stability_delta = dynamic_multimask_stability_delta
117
- self.dynamic_multimask_stability_thresh = dynamic_multimask_stability_thresh
118
-
119
- def forward(
120
- self,
121
- image_embeddings: torch.Tensor,
122
- image_pe: torch.Tensor,
123
- sparse_prompt_embeddings: torch.Tensor,
124
- dense_prompt_embeddings: torch.Tensor,
125
- multimask_output: bool,
126
- repeat_image: bool,
127
- high_res_features: Optional[List[torch.Tensor]] = None,
128
- ) -> Tuple[torch.Tensor, torch.Tensor]:
129
- """
130
- Predicts masks given image and prompt embeddings.
131
-
132
- Args:
133
- image_embeddings (torch.Tensor): Embeddings from the image encoder.
134
- image_pe (torch.Tensor): Positional encoding with the shape of image_embeddings.
135
- sparse_prompt_embeddings (torch.Tensor): Embeddings of the points and boxes.
136
- dense_prompt_embeddings (torch.Tensor): Embeddings of the mask inputs.
137
- multimask_output (bool): Whether to return multiple masks or a single mask.
138
- repeat_image (bool): Flag to repeat the image embeddings.
139
- high_res_features (List[torch.Tensor] | None): Optional high-resolution features.
140
-
141
- Returns:
142
- (Tuple[torch.Tensor, torch.Tensor, torch.Tensor]): A tuple containing:
143
- - masks (torch.Tensor): Batched predicted masks.
144
- - iou_pred (torch.Tensor): Batched predictions of mask quality.
145
- - sam_tokens_out (torch.Tensor): Batched SAM token for mask output.
146
-
147
- Examples:
148
- >>> image_embeddings = torch.rand(1, 256, 64, 64)
149
- >>> image_pe = torch.rand(1, 256, 64, 64)
150
- >>> sparse_prompt_embeddings = torch.rand(1, 2, 256)
151
- >>> dense_prompt_embeddings = torch.rand(1, 256, 64, 64)
152
- >>> decoder = MaskDecoder(256, transformer)
153
- >>> masks, iou_pred, sam_tokens_out = decoder.forward(image_embeddings, image_pe,
154
- ... sparse_prompt_embeddings, dense_prompt_embeddings, True, False)
155
- """
156
- masks, iou_pred, mask_tokens_out, object_score_logits = self.predict_masks(
157
- image_embeddings=image_embeddings,
158
- image_pe=image_pe,
159
- sparse_prompt_embeddings=sparse_prompt_embeddings,
160
- dense_prompt_embeddings=dense_prompt_embeddings,
161
- repeat_image=repeat_image,
162
- high_res_features=high_res_features,
163
- )
164
-
165
- # Select the correct mask or masks for output
166
- if multimask_output:
167
- masks = masks[:, 1:, :, :]
168
- iou_pred = iou_pred[:, 1:]
169
- elif self.dynamic_multimask_via_stability and not self.training:
170
- masks, iou_pred = self._dynamic_multimask_via_stability(masks, iou_pred)
171
- else:
172
- masks = masks[:, 0:1, :, :]
173
- iou_pred = iou_pred[:, 0:1]
174
-
175
- if multimask_output and self.use_multimask_token_for_obj_ptr:
176
- sam_tokens_out = mask_tokens_out[:, 1:] # [b, 3, c] shape
177
- else:
178
- # Take the mask output token. Here we *always* use the token for single mask output.
179
- # At test time, even if we track after 1-click (and using multimask_output=True),
180
- # we still take the single mask token here. The rationale is that we always track
181
- # after multiple clicks during training, so the past tokens seen during training
182
- # are always the single mask token (and we'll let it be the object-memory token).
183
- sam_tokens_out = mask_tokens_out[:, 0:1] # [b, 1, c] shape
184
-
185
- # Prepare output
186
- return masks, iou_pred, sam_tokens_out, object_score_logits
187
-
188
- def predict_masks(
189
- self,
190
- image_embeddings: torch.Tensor,
191
- image_pe: torch.Tensor,
192
- sparse_prompt_embeddings: torch.Tensor,
193
- dense_prompt_embeddings: torch.Tensor,
194
- repeat_image: bool,
195
- high_res_features: Optional[List[torch.Tensor]] = None,
196
- ) -> Tuple[torch.Tensor, torch.Tensor]:
197
- """Predicts instance segmentation masks from image and prompt embeddings using a transformer architecture."""
198
- # Concatenate output tokens
199
- s = 0
200
- if self.pred_obj_scores:
201
- output_tokens = torch.cat(
202
- [
203
- self.obj_score_token.weight,
204
- self.iou_token.weight,
205
- self.mask_tokens.weight,
206
- ],
207
- dim=0,
208
- )
209
- s = 1
210
- else:
211
- output_tokens = torch.cat([self.iou_token.weight, self.mask_tokens.weight], dim=0)
212
- output_tokens = output_tokens.unsqueeze(0).expand(sparse_prompt_embeddings.size(0), -1, -1)
213
- tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1)
214
-
215
- # Expand per-image data in batch direction to be per-mask
216
- if repeat_image:
217
- src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0)
218
- else:
219
- assert image_embeddings.shape[0] == tokens.shape[0]
220
- src = image_embeddings
221
- src = src + dense_prompt_embeddings
222
- assert image_pe.size(0) == 1, "image_pe should have size 1 in batch dim (from `get_dense_pe()`)"
223
- pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0)
224
- b, c, h, w = src.shape
225
-
226
- # Run the transformer
227
- hs, src = self.transformer(src, pos_src, tokens)
228
- iou_token_out = hs[:, s, :]
229
- mask_tokens_out = hs[:, s + 1 : (s + 1 + self.num_mask_tokens), :]
230
-
231
- # Upscale mask embeddings and predict masks using the mask tokens
232
- src = src.transpose(1, 2).view(b, c, h, w)
233
- if not self.use_high_res_features:
234
- upscaled_embedding = self.output_upscaling(src)
235
- else:
236
- dc1, ln1, act1, dc2, act2 = self.output_upscaling
237
- feat_s0, feat_s1 = high_res_features
238
- upscaled_embedding = act1(ln1(dc1(src) + feat_s1))
239
- upscaled_embedding = act2(dc2(upscaled_embedding) + feat_s0)
240
-
241
- hyper_in_list: List[torch.Tensor] = []
242
- for i in range(self.num_mask_tokens):
243
- hyper_in_list.append(self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :]))
244
- hyper_in = torch.stack(hyper_in_list, dim=1)
245
- b, c, h, w = upscaled_embedding.shape
246
- masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w)
247
-
248
- # Generate mask quality predictions
249
- iou_pred = self.iou_prediction_head(iou_token_out)
250
- if self.pred_obj_scores:
251
- assert s == 1
252
- object_score_logits = self.pred_obj_score_head(hs[:, 0, :])
253
- else:
254
- # Obj scores logits - default to 10.0, i.e. assuming the object is present, sigmoid(10)=1
255
- object_score_logits = 10.0 * iou_pred.new_ones(iou_pred.shape[0], 1)
256
-
257
- return masks, iou_pred, mask_tokens_out, object_score_logits
258
-
259
- def _get_stability_scores(self, mask_logits):
260
- """Computes mask stability scores based on IoU between upper and lower thresholds."""
261
- mask_logits = mask_logits.flatten(-2)
262
- stability_delta = self.dynamic_multimask_stability_delta
263
- area_i = torch.sum(mask_logits > stability_delta, dim=-1).float()
264
- area_u = torch.sum(mask_logits > -stability_delta, dim=-1).float()
265
- stability_scores = torch.where(area_u > 0, area_i / area_u, 1.0)
266
- return stability_scores
267
-
268
- def _dynamic_multimask_via_stability(self, all_mask_logits, all_iou_scores):
269
- """
270
- Dynamically selects the most stable mask output based on stability scores and IoU predictions.
271
-
272
- When outputting a single mask, if the stability score from the current single-mask output (based on output token
273
- 0) falls below a threshold, we instead select from multi-mask outputs (based on output token 1~3) the mask with
274
- the highest predicted IoU score.
275
-
276
- This is intended to ensure a valid mask for both clicking and tracking.
277
- """
278
- # The best mask from multimask output tokens (1~3)
279
- multimask_logits = all_mask_logits[:, 1:, :, :]
280
- multimask_iou_scores = all_iou_scores[:, 1:]
281
- best_scores_inds = torch.argmax(multimask_iou_scores, dim=-1)
282
- batch_inds = torch.arange(multimask_iou_scores.size(0), device=all_iou_scores.device)
283
- best_multimask_logits = multimask_logits[batch_inds, best_scores_inds]
284
- best_multimask_logits = best_multimask_logits.unsqueeze(1)
285
- best_multimask_iou_scores = multimask_iou_scores[batch_inds, best_scores_inds]
286
- best_multimask_iou_scores = best_multimask_iou_scores.unsqueeze(1)
287
-
288
- # The mask from singlemask output token 0 and its stability score
289
- singlemask_logits = all_mask_logits[:, 0:1, :, :]
290
- singlemask_iou_scores = all_iou_scores[:, 0:1]
291
- stability_scores = self._get_stability_scores(singlemask_logits)
292
- is_stable = stability_scores >= self.dynamic_multimask_stability_thresh
293
-
294
- # Dynamically fall back to best multimask output upon low stability scores.
295
- mask_logits_out = torch.where(
296
- is_stable[..., None, None].expand_as(singlemask_logits),
297
- singlemask_logits,
298
- best_multimask_logits,
299
- )
300
- iou_scores_out = torch.where(
301
- is_stable.expand_as(singlemask_iou_scores),
302
- singlemask_iou_scores,
303
- best_multimask_iou_scores,
304
- )
305
- return mask_logits_out, iou_scores_out
@@ -1,332 +0,0 @@
1
- # Ultralytics YOLO 🚀, AGPL-3.0 license
2
-
3
- from typing import List, Optional, Tuple
4
-
5
- import torch
6
- import torch.nn as nn
7
- import torch.nn.functional as F
8
-
9
- from ultralytics.models.sam.modules.encoders import PatchEmbed
10
-
11
- from .sam2_blocks import CXBlock, Fuser, MaskDownSampler, MultiScaleBlock, PositionEmbeddingSine
12
-
13
-
14
- class MemoryEncoder(nn.Module):
15
- """Encodes pixel features and masks into a memory representation for efficient image segmentation."""
16
-
17
- def __init__(
18
- self,
19
- out_dim,
20
- in_dim=256, # in_dim of pix_feats
21
- ):
22
- """Initializes the MemoryEncoder module for encoding pixel features and masks in SAM-like models."""
23
- super().__init__()
24
-
25
- self.mask_downsampler = MaskDownSampler(kernel_size=3, stride=2, padding=1)
26
-
27
- self.pix_feat_proj = nn.Conv2d(in_dim, in_dim, kernel_size=1)
28
- self.fuser = Fuser(CXBlock(dim=256), num_layers=2)
29
- self.position_encoding = PositionEmbeddingSine(num_pos_feats=64)
30
- self.out_proj = nn.Identity()
31
- if out_dim != in_dim:
32
- self.out_proj = nn.Conv2d(in_dim, out_dim, kernel_size=1)
33
-
34
- def forward(
35
- self,
36
- pix_feat: torch.Tensor,
37
- masks: torch.Tensor,
38
- skip_mask_sigmoid: bool = False,
39
- ) -> Tuple[torch.Tensor, torch.Tensor]:
40
- """Processes pixel features and masks, fusing them to generate encoded memory representations."""
41
- if not skip_mask_sigmoid:
42
- masks = F.sigmoid(masks)
43
- masks = self.mask_downsampler(masks)
44
-
45
- # Fuse pix_feats and downsampled masks, in case the visual features are on CPU, cast them to CUDA
46
- pix_feat = pix_feat.to(masks.device)
47
-
48
- x = self.pix_feat_proj(pix_feat)
49
- x = x + masks
50
- x = self.fuser(x)
51
- x = self.out_proj(x)
52
-
53
- pos = self.position_encoding(x).to(x.dtype)
54
-
55
- return {"vision_features": x, "vision_pos_enc": [pos]}
56
-
57
-
58
- class ImageEncoder(nn.Module):
59
- """Encodes images using a trunk-neck architecture, producing multiscale features and positional encodings."""
60
-
61
- def __init__(
62
- self,
63
- trunk: nn.Module,
64
- neck: nn.Module,
65
- scalp: int = 0,
66
- ):
67
- """Initializes an image encoder with a trunk, neck, and optional scalp for feature extraction."""
68
- super().__init__()
69
- self.trunk = trunk
70
- self.neck = neck
71
- self.scalp = scalp
72
- assert (
73
- self.trunk.channel_list == self.neck.backbone_channel_list
74
- ), f"Channel dims of trunk {self.trunk.channel_list} and neck {self.neck.backbone_channel_list} do not match."
75
-
76
- def forward(self, sample: torch.Tensor):
77
- """Processes image input through trunk and neck, returning features, positional encodings, and FPN outputs."""
78
- features, pos = self.neck(self.trunk(sample))
79
- if self.scalp > 0:
80
- # Discard the lowest resolution features
81
- features, pos = features[: -self.scalp], pos[: -self.scalp]
82
-
83
- src = features[-1]
84
- output = {
85
- "vision_features": src,
86
- "vision_pos_enc": pos,
87
- "backbone_fpn": features,
88
- }
89
- return output
90
-
91
-
92
- class FpnNeck(nn.Module):
93
- """Feature Pyramid Network (FPN) neck variant for multiscale feature fusion in object detection models."""
94
-
95
- def __init__(
96
- self,
97
- d_model: int,
98
- backbone_channel_list: List[int],
99
- kernel_size: int = 1,
100
- stride: int = 1,
101
- padding: int = 0,
102
- fpn_interp_model: str = "bilinear",
103
- fuse_type: str = "sum",
104
- fpn_top_down_levels: Optional[List[int]] = None,
105
- ):
106
- """
107
- Initializes a modified Feature Pyramid Network (FPN) neck.
108
-
109
- This FPN variant removes the output convolution and uses bicubic interpolation for feature resizing,
110
- similar to ViT positional embedding interpolation.
111
-
112
- Args:
113
- d_model (int): Dimension of the model.
114
- backbone_channel_list (List[int]): List of channel dimensions from the backbone.
115
- kernel_size (int): Kernel size for the convolutional layers.
116
- stride (int): Stride for the convolutional layers.
117
- padding (int): Padding for the convolutional layers.
118
- fpn_interp_model (str): Interpolation mode for FPN feature resizing.
119
- fuse_type (str): Type of feature fusion, either 'sum' or 'avg'.
120
- fpn_top_down_levels (Optional[List[int]]): Levels to have top-down features in outputs.
121
-
122
- Attributes:
123
- position_encoding (PositionEmbeddingSine): Sinusoidal positional encoding.
124
- convs (nn.ModuleList): List of convolutional layers for each backbone level.
125
- backbone_channel_list (List[int]): List of channel dimensions from the backbone.
126
- fpn_interp_model (str): Interpolation mode for FPN feature resizing.
127
- fuse_type (str): Type of feature fusion.
128
- fpn_top_down_levels (List[int]): Levels with top-down feature propagation.
129
-
130
- Examples:
131
- >>> backbone_channels = [64, 128, 256, 512]
132
- >>> fpn_neck = FpnNeck(256, backbone_channels)
133
- >>> print(fpn_neck)
134
- """
135
- super().__init__()
136
- self.position_encoding = PositionEmbeddingSine(num_pos_feats=256)
137
- self.convs = nn.ModuleList()
138
- self.backbone_channel_list = backbone_channel_list
139
- for dim in backbone_channel_list:
140
- current = nn.Sequential()
141
- current.add_module(
142
- "conv",
143
- nn.Conv2d(
144
- in_channels=dim,
145
- out_channels=d_model,
146
- kernel_size=kernel_size,
147
- stride=stride,
148
- padding=padding,
149
- ),
150
- )
151
-
152
- self.convs.append(current)
153
- self.fpn_interp_model = fpn_interp_model
154
- assert fuse_type in ["sum", "avg"]
155
- self.fuse_type = fuse_type
156
-
157
- # levels to have top-down features in its outputs
158
- # e.g. if fpn_top_down_levels is [2, 3], then only outputs of level 2 and 3
159
- # have top-down propagation, while outputs of level 0 and level 1 have only
160
- # lateral features from the same backbone level.
161
- if fpn_top_down_levels is None:
162
- # default is to have top-down features on all levels
163
- fpn_top_down_levels = range(len(self.convs))
164
- self.fpn_top_down_levels = list(fpn_top_down_levels)
165
-
166
- def forward(self, xs: List[torch.Tensor]):
167
- """
168
- Performs forward pass through the Feature Pyramid Network (FPN) neck.
169
-
170
- Args:
171
- xs (List[torch.Tensor]): List of input tensors from the backbone, with shape (B, C, H, W) for each tensor.
172
-
173
- Returns:
174
- (Tuple[List[torch.Tensor], List[torch.Tensor]]): A tuple containing two lists:
175
- - out: List of output feature maps after FPN processing, with shape (B, d_model, H, W) for each tensor.
176
- - pos: List of positional encodings corresponding to each output feature map.
177
-
178
- Examples:
179
- >>> fpn_neck = FpnNeck(d_model=256, backbone_channel_list=[64, 128, 256, 512])
180
- >>> inputs = [torch.rand(1, c, 32, 32) for c in [64, 128, 256, 512]]
181
- >>> outputs, positions = fpn_neck(inputs)
182
- """
183
- out = [None] * len(self.convs)
184
- pos = [None] * len(self.convs)
185
- assert len(xs) == len(self.convs)
186
- # fpn forward pass
187
- # see https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/fpn.py
188
- prev_features = None
189
- # forward in top-down order (from low to high resolution)
190
- n = len(self.convs) - 1
191
- for i in range(n, -1, -1):
192
- x = xs[i]
193
- lateral_features = self.convs[n - i](x)
194
- if i in self.fpn_top_down_levels and prev_features is not None:
195
- top_down_features = F.interpolate(
196
- prev_features.to(dtype=torch.float32),
197
- scale_factor=2.0,
198
- mode=self.fpn_interp_model,
199
- align_corners=(None if self.fpn_interp_model == "nearest" else False),
200
- antialias=False,
201
- )
202
- prev_features = lateral_features + top_down_features
203
- if self.fuse_type == "avg":
204
- prev_features /= 2
205
- else:
206
- prev_features = lateral_features
207
- x_out = prev_features
208
- out[i] = x_out
209
- pos[i] = self.position_encoding(x_out).to(x_out.dtype)
210
-
211
- return out, pos
212
-
213
-
214
- class Hiera(nn.Module):
215
- """Hierarchical vision transformer for efficient multiscale feature extraction in image processing tasks."""
216
-
217
- def __init__(
218
- self,
219
- embed_dim: int = 96, # initial embed dim
220
- num_heads: int = 1, # initial number of heads
221
- drop_path_rate: float = 0.0, # stochastic depth
222
- q_pool: int = 3, # number of q_pool stages
223
- q_stride: Tuple[int, int] = (2, 2), # downsample stride bet. stages
224
- stages: Tuple[int, ...] = (2, 3, 16, 3), # blocks per stage
225
- dim_mul: float = 2.0, # dim_mul factor at stage shift
226
- head_mul: float = 2.0, # head_mul factor at stage shift
227
- window_pos_embed_bkg_spatial_size: Tuple[int, int] = (14, 14),
228
- # window size per stage, when not using global att.
229
- window_spec: Tuple[int, ...] = (
230
- 8,
231
- 4,
232
- 14,
233
- 7,
234
- ),
235
- # global attn in these blocks
236
- global_att_blocks: Tuple[int, ...] = (
237
- 12,
238
- 16,
239
- 20,
240
- ),
241
- return_interm_layers=True, # return feats from every stage
242
- ):
243
- """Initializes a Hiera model with configurable architecture for hierarchical vision transformers."""
244
- super().__init__()
245
-
246
- assert len(stages) == len(window_spec)
247
- self.window_spec = window_spec
248
-
249
- depth = sum(stages)
250
- self.q_stride = q_stride
251
- self.stage_ends = [sum(stages[:i]) - 1 for i in range(1, len(stages) + 1)]
252
- assert 0 <= q_pool <= len(self.stage_ends[:-1])
253
- self.q_pool_blocks = [x + 1 for x in self.stage_ends[:-1]][:q_pool]
254
- self.return_interm_layers = return_interm_layers
255
-
256
- self.patch_embed = PatchEmbed(
257
- embed_dim=embed_dim,
258
- kernel_size=(7, 7),
259
- stride=(4, 4),
260
- padding=(3, 3),
261
- )
262
- # Which blocks have global att?
263
- self.global_att_blocks = global_att_blocks
264
-
265
- # Windowed positional embedding (https://arxiv.org/abs/2311.05613)
266
- self.window_pos_embed_bkg_spatial_size = window_pos_embed_bkg_spatial_size
267
- self.pos_embed = nn.Parameter(torch.zeros(1, embed_dim, *self.window_pos_embed_bkg_spatial_size))
268
- self.pos_embed_window = nn.Parameter(torch.zeros(1, embed_dim, self.window_spec[0], self.window_spec[0]))
269
-
270
- dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
271
-
272
- cur_stage = 1
273
- self.blocks = nn.ModuleList()
274
-
275
- for i in range(depth):
276
- dim_out = embed_dim
277
- # lags by a block, so first block of
278
- # next stage uses an initial window size
279
- # of previous stage and final window size of current stage
280
- window_size = self.window_spec[cur_stage - 1]
281
-
282
- if self.global_att_blocks is not None:
283
- window_size = 0 if i in self.global_att_blocks else window_size
284
-
285
- if i - 1 in self.stage_ends:
286
- dim_out = int(embed_dim * dim_mul)
287
- num_heads = int(num_heads * head_mul)
288
- cur_stage += 1
289
-
290
- block = MultiScaleBlock(
291
- dim=embed_dim,
292
- dim_out=dim_out,
293
- num_heads=num_heads,
294
- drop_path=dpr[i],
295
- q_stride=self.q_stride if i in self.q_pool_blocks else None,
296
- window_size=window_size,
297
- )
298
-
299
- embed_dim = dim_out
300
- self.blocks.append(block)
301
-
302
- self.channel_list = (
303
- [self.blocks[i].dim_out for i in self.stage_ends[::-1]]
304
- if return_interm_layers
305
- else [self.blocks[-1].dim_out]
306
- )
307
-
308
- def _get_pos_embed(self, hw: Tuple[int, int]) -> torch.Tensor:
309
- """Generate positional embeddings by interpolating and combining window and background embeddings."""
310
- h, w = hw
311
- window_embed = self.pos_embed_window
312
- pos_embed = F.interpolate(self.pos_embed, size=(h, w), mode="bicubic")
313
- pos_embed = pos_embed + window_embed.tile([x // y for x, y in zip(pos_embed.shape, window_embed.shape)])
314
- pos_embed = pos_embed.permute(0, 2, 3, 1)
315
- return pos_embed
316
-
317
- def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
318
- """Performs hierarchical vision transformer forward pass, returning multiscale feature maps."""
319
- x = self.patch_embed(x)
320
- # x: (B, H, W, C)
321
-
322
- # Add pos embed
323
- x = x + self._get_pos_embed(x.shape[1:3])
324
-
325
- outputs = []
326
- for i, blk in enumerate(self.blocks):
327
- x = blk(x)
328
- if (i == self.stage_ends[-1]) or (i in self.stage_ends and self.return_interm_layers):
329
- feats = x.permute(0, 3, 1, 2)
330
- outputs.append(feats)
331
-
332
- return outputs