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,6 +1,6 @@
1
1
  # Ultralytics YOLO 🚀, AGPL-3.0 license
2
2
 
3
- from typing import List, Tuple, Type
3
+ from typing import List, Optional, Tuple, Type
4
4
 
5
5
  import torch
6
6
  from torch import nn
@@ -10,12 +10,14 @@ from ultralytics.nn.modules import MLP, LayerNorm2d
10
10
 
11
11
  class MaskDecoder(nn.Module):
12
12
  """
13
- Decoder module for generating masks and their associated quality scores, using a transformer architecture to predict
14
- masks given image and prompt embeddings.
13
+ Decoder module for generating masks and their associated quality scores using a transformer architecture.
14
+
15
+ This class predicts masks given image and prompt embeddings, utilizing a transformer to process the inputs and
16
+ generate mask predictions along with their quality scores.
15
17
 
16
18
  Attributes:
17
19
  transformer_dim (int): Channel dimension for the transformer module.
18
- transformer (nn.Module): The transformer module used for mask prediction.
20
+ transformer (nn.Module): Transformer module used for mask prediction.
19
21
  num_multimask_outputs (int): Number of masks to predict for disambiguating masks.
20
22
  iou_token (nn.Embedding): Embedding for the IoU token.
21
23
  num_mask_tokens (int): Number of mask tokens.
@@ -23,6 +25,16 @@ class MaskDecoder(nn.Module):
23
25
  output_upscaling (nn.Sequential): Neural network sequence for upscaling the output.
24
26
  output_hypernetworks_mlps (nn.ModuleList): Hypernetwork MLPs for generating masks.
25
27
  iou_prediction_head (nn.Module): MLP for predicting mask quality.
28
+
29
+ Methods:
30
+ forward: Predicts masks given image and prompt embeddings.
31
+ predict_masks: Internal method for mask prediction.
32
+
33
+ Examples:
34
+ >>> decoder = MaskDecoder(transformer_dim=256, transformer=transformer_module)
35
+ >>> masks, iou_pred = decoder(image_embeddings, image_pe, sparse_prompt_embeddings,
36
+ ... dense_prompt_embeddings, multimask_output=True)
37
+ >>> print(f"Predicted masks shape: {masks.shape}, IoU predictions shape: {iou_pred.shape}")
26
38
  """
27
39
 
28
40
  def __init__(
@@ -35,15 +47,20 @@ class MaskDecoder(nn.Module):
35
47
  iou_head_hidden_dim: int = 256,
36
48
  ) -> None:
37
49
  """
38
- Predicts masks given an image and prompt embeddings, using a transformer architecture.
50
+ Initializes the MaskDecoder module for generating masks and their quality scores.
39
51
 
40
52
  Args:
41
- transformer_dim (int): the channel dimension of the transformer module
42
- transformer (nn.Module): the transformer used to predict masks
43
- num_multimask_outputs (int): the number of masks to predict when disambiguating masks
44
- activation (nn.Module): the type of activation to use when upscaling masks
45
- iou_head_depth (int): the depth of the MLP used to predict mask quality
46
- iou_head_hidden_dim (int): the hidden dimension of the MLP used to predict mask quality
53
+ transformer_dim (int): Channel dimension for the transformer module.
54
+ transformer (nn.Module): Transformer module used for mask prediction.
55
+ num_multimask_outputs (int): Number of masks to predict for disambiguating masks.
56
+ activation (Type[nn.Module]): Type of activation to use when upscaling masks.
57
+ iou_head_depth (int): Depth of the MLP used to predict mask quality.
58
+ iou_head_hidden_dim (int): Hidden dimension of the MLP used to predict mask quality.
59
+
60
+ Examples:
61
+ >>> transformer = nn.TransformerEncoder(nn.TransformerEncoderLayer(d_model=256, nhead=8), num_layers=6)
62
+ >>> decoder = MaskDecoder(transformer_dim=256, transformer=transformer)
63
+ >>> print(decoder)
47
64
  """
48
65
  super().__init__()
49
66
  self.transformer_dim = transformer_dim
@@ -77,18 +94,28 @@ class MaskDecoder(nn.Module):
77
94
  multimask_output: bool,
78
95
  ) -> Tuple[torch.Tensor, torch.Tensor]:
79
96
  """
80
- Predict masks given image and prompt embeddings.
97
+ Predicts masks given image and prompt embeddings.
81
98
 
82
99
  Args:
83
- image_embeddings (torch.Tensor): the embeddings from the image encoder
84
- image_pe (torch.Tensor): positional encoding with the shape of image_embeddings
85
- sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes
86
- dense_prompt_embeddings (torch.Tensor): the embeddings of the mask inputs
100
+ image_embeddings (torch.Tensor): Embeddings from the image encoder.
101
+ image_pe (torch.Tensor): Positional encoding with the shape of image_embeddings.
102
+ sparse_prompt_embeddings (torch.Tensor): Embeddings of the points and boxes.
103
+ dense_prompt_embeddings (torch.Tensor): Embeddings of the mask inputs.
87
104
  multimask_output (bool): Whether to return multiple masks or a single mask.
88
105
 
89
106
  Returns:
90
- torch.Tensor: batched predicted masks
91
- torch.Tensor: batched predictions of mask quality
107
+ (Tuple[torch.Tensor, torch.Tensor]): A tuple containing:
108
+ - masks (torch.Tensor): Batched predicted masks.
109
+ - iou_pred (torch.Tensor): Batched predictions of mask quality.
110
+
111
+ Examples:
112
+ >>> decoder = MaskDecoder(transformer_dim=256, transformer=transformer_module)
113
+ >>> image_emb = torch.rand(1, 256, 64, 64)
114
+ >>> image_pe = torch.rand(1, 256, 64, 64)
115
+ >>> sparse_emb = torch.rand(1, 2, 256)
116
+ >>> dense_emb = torch.rand(1, 256, 64, 64)
117
+ >>> masks, iou_pred = decoder(image_emb, image_pe, sparse_emb, dense_emb, multimask_output=True)
118
+ >>> print(f"Masks shape: {masks.shape}, IoU predictions shape: {iou_pred.shape}")
92
119
  """
93
120
  masks, iou_pred = self.predict_masks(
94
121
  image_embeddings=image_embeddings,
@@ -112,11 +139,7 @@ class MaskDecoder(nn.Module):
112
139
  sparse_prompt_embeddings: torch.Tensor,
113
140
  dense_prompt_embeddings: torch.Tensor,
114
141
  ) -> Tuple[torch.Tensor, torch.Tensor]:
115
- """
116
- Predicts masks.
117
-
118
- See 'forward' for more details.
119
- """
142
+ """Predicts masks and quality scores using image and prompt embeddings via transformer architecture."""
120
143
  # Concatenate output tokens
121
144
  output_tokens = torch.cat([self.iou_token.weight, self.mask_tokens.weight], dim=0)
122
145
  output_tokens = output_tokens.unsqueeze(0).expand(sparse_prompt_embeddings.shape[0], -1, -1)
@@ -147,3 +170,347 @@ class MaskDecoder(nn.Module):
147
170
  iou_pred = self.iou_prediction_head(iou_token_out)
148
171
 
149
172
  return masks, iou_pred
173
+
174
+
175
+ class SAM2MaskDecoder(nn.Module):
176
+ """
177
+ Transformer-based decoder for predicting instance segmentation masks from image and prompt embeddings.
178
+
179
+ This class extends the functionality of the MaskDecoder, incorporating additional features such as
180
+ high-resolution feature processing, dynamic multimask output, and object score prediction.
181
+
182
+ Attributes:
183
+ transformer_dim (int): Channel dimension of the transformer.
184
+ transformer (nn.Module): Transformer used to predict masks.
185
+ num_multimask_outputs (int): Number of masks to predict when disambiguating masks.
186
+ iou_token (nn.Embedding): Embedding for IOU token.
187
+ num_mask_tokens (int): Total number of mask tokens.
188
+ mask_tokens (nn.Embedding): Embedding for mask tokens.
189
+ pred_obj_scores (bool): Whether to predict object scores.
190
+ obj_score_token (nn.Embedding): Embedding for object score token.
191
+ use_multimask_token_for_obj_ptr (bool): Whether to use multimask token for object pointer.
192
+ output_upscaling (nn.Sequential): Upscaling layers for output.
193
+ use_high_res_features (bool): Whether to use high-resolution features.
194
+ conv_s0 (nn.Conv2d): Convolutional layer for high-resolution features (s0).
195
+ conv_s1 (nn.Conv2d): Convolutional layer for high-resolution features (s1).
196
+ output_hypernetworks_mlps (nn.ModuleList): List of MLPs for output hypernetworks.
197
+ iou_prediction_head (MLP): MLP for IOU prediction.
198
+ pred_obj_score_head (nn.Linear | MLP): Linear layer or MLP for object score prediction.
199
+ dynamic_multimask_via_stability (bool): Whether to use dynamic multimask via stability.
200
+ dynamic_multimask_stability_delta (float): Delta value for dynamic multimask stability.
201
+ dynamic_multimask_stability_thresh (float): Threshold for dynamic multimask stability.
202
+
203
+ Methods:
204
+ forward: Predicts masks given image and prompt embeddings.
205
+ predict_masks: Predicts instance segmentation masks from image and prompt embeddings.
206
+ _get_stability_scores: Computes mask stability scores based on IoU between thresholds.
207
+ _dynamic_multimask_via_stability: Dynamically selects the most stable mask output.
208
+
209
+ Examples:
210
+ >>> image_embeddings = torch.rand(1, 256, 64, 64)
211
+ >>> image_pe = torch.rand(1, 256, 64, 64)
212
+ >>> sparse_prompt_embeddings = torch.rand(1, 2, 256)
213
+ >>> dense_prompt_embeddings = torch.rand(1, 256, 64, 64)
214
+ >>> decoder = SAM2MaskDecoder(256, transformer)
215
+ >>> masks, iou_pred, sam_tokens_out, obj_score_logits = decoder.forward(
216
+ ... image_embeddings, image_pe, sparse_prompt_embeddings, dense_prompt_embeddings, True, False)
217
+ """
218
+
219
+ def __init__(
220
+ self,
221
+ transformer_dim: int,
222
+ transformer: nn.Module,
223
+ num_multimask_outputs: int = 3,
224
+ activation: Type[nn.Module] = nn.GELU,
225
+ iou_head_depth: int = 3,
226
+ iou_head_hidden_dim: int = 256,
227
+ use_high_res_features: bool = False,
228
+ iou_prediction_use_sigmoid=False,
229
+ dynamic_multimask_via_stability=False,
230
+ dynamic_multimask_stability_delta=0.05,
231
+ dynamic_multimask_stability_thresh=0.98,
232
+ pred_obj_scores: bool = False,
233
+ pred_obj_scores_mlp: bool = False,
234
+ use_multimask_token_for_obj_ptr: bool = False,
235
+ ) -> None:
236
+ """
237
+ Initializes the SAM2MaskDecoder module for predicting instance segmentation masks.
238
+
239
+ This decoder extends the functionality of MaskDecoder, incorporating additional features such as
240
+ high-resolution feature processing, dynamic multimask output, and object score prediction.
241
+
242
+ Args:
243
+ transformer_dim (int): Channel dimension of the transformer.
244
+ transformer (nn.Module): Transformer used to predict masks.
245
+ num_multimask_outputs (int): Number of masks to predict when disambiguating masks.
246
+ activation (Type[nn.Module]): Type of activation to use when upscaling masks.
247
+ iou_head_depth (int): Depth of the MLP used to predict mask quality.
248
+ iou_head_hidden_dim (int): Hidden dimension of the MLP used to predict mask quality.
249
+ use_high_res_features (bool): Whether to use high-resolution features.
250
+ iou_prediction_use_sigmoid (bool): Whether to use sigmoid for IOU prediction.
251
+ dynamic_multimask_via_stability (bool): Whether to use dynamic multimask via stability.
252
+ dynamic_multimask_stability_delta (float): Delta value for dynamic multimask stability.
253
+ dynamic_multimask_stability_thresh (float): Threshold for dynamic multimask stability.
254
+ pred_obj_scores (bool): Whether to predict object scores.
255
+ pred_obj_scores_mlp (bool): Whether to use MLP for object score prediction.
256
+ use_multimask_token_for_obj_ptr (bool): Whether to use multimask token for object pointer.
257
+
258
+ Examples:
259
+ >>> transformer = nn.TransformerEncoder(nn.TransformerEncoderLayer(d_model=256, nhead=8), num_layers=6)
260
+ >>> decoder = SAM2MaskDecoder(transformer_dim=256, transformer=transformer)
261
+ >>> print(decoder)
262
+ """
263
+ super().__init__()
264
+ self.transformer_dim = transformer_dim
265
+ self.transformer = transformer
266
+
267
+ self.num_multimask_outputs = num_multimask_outputs
268
+
269
+ self.iou_token = nn.Embedding(1, transformer_dim)
270
+ self.num_mask_tokens = num_multimask_outputs + 1
271
+ self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim)
272
+
273
+ self.pred_obj_scores = pred_obj_scores
274
+ if self.pred_obj_scores:
275
+ self.obj_score_token = nn.Embedding(1, transformer_dim)
276
+ self.use_multimask_token_for_obj_ptr = use_multimask_token_for_obj_ptr
277
+
278
+ self.output_upscaling = nn.Sequential(
279
+ nn.ConvTranspose2d(transformer_dim, transformer_dim // 4, kernel_size=2, stride=2),
280
+ LayerNorm2d(transformer_dim // 4),
281
+ activation(),
282
+ nn.ConvTranspose2d(transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2),
283
+ activation(),
284
+ )
285
+ self.use_high_res_features = use_high_res_features
286
+ if use_high_res_features:
287
+ self.conv_s0 = nn.Conv2d(transformer_dim, transformer_dim // 8, kernel_size=1, stride=1)
288
+ self.conv_s1 = nn.Conv2d(transformer_dim, transformer_dim // 4, kernel_size=1, stride=1)
289
+
290
+ self.output_hypernetworks_mlps = nn.ModuleList(
291
+ [MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3) for _ in range(self.num_mask_tokens)]
292
+ )
293
+
294
+ self.iou_prediction_head = MLP(
295
+ transformer_dim,
296
+ iou_head_hidden_dim,
297
+ self.num_mask_tokens,
298
+ iou_head_depth,
299
+ sigmoid=iou_prediction_use_sigmoid,
300
+ )
301
+ if self.pred_obj_scores:
302
+ self.pred_obj_score_head = nn.Linear(transformer_dim, 1)
303
+ if pred_obj_scores_mlp:
304
+ self.pred_obj_score_head = MLP(transformer_dim, transformer_dim, 1, 3)
305
+
306
+ # When outputting a single mask, optionally we can dynamically fall back to the best
307
+ # multimask output token if the single mask output token gives low stability scores.
308
+ self.dynamic_multimask_via_stability = dynamic_multimask_via_stability
309
+ self.dynamic_multimask_stability_delta = dynamic_multimask_stability_delta
310
+ self.dynamic_multimask_stability_thresh = dynamic_multimask_stability_thresh
311
+
312
+ def forward(
313
+ self,
314
+ image_embeddings: torch.Tensor,
315
+ image_pe: torch.Tensor,
316
+ sparse_prompt_embeddings: torch.Tensor,
317
+ dense_prompt_embeddings: torch.Tensor,
318
+ multimask_output: bool,
319
+ repeat_image: bool,
320
+ high_res_features: Optional[List[torch.Tensor]] = None,
321
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
322
+ """
323
+ Predicts masks given image and prompt embeddings.
324
+
325
+ Args:
326
+ image_embeddings (torch.Tensor): Embeddings from the image encoder with shape (B, C, H, W).
327
+ image_pe (torch.Tensor): Positional encoding with the shape of image_embeddings (B, C, H, W).
328
+ sparse_prompt_embeddings (torch.Tensor): Embeddings of the points and boxes with shape (B, N, C).
329
+ dense_prompt_embeddings (torch.Tensor): Embeddings of the mask inputs with shape (B, C, H, W).
330
+ multimask_output (bool): Whether to return multiple masks or a single mask.
331
+ repeat_image (bool): Flag to repeat the image embeddings.
332
+ high_res_features (List[torch.Tensor] | None): Optional high-resolution features.
333
+
334
+ Returns:
335
+ (Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]): A tuple containing:
336
+ - masks (torch.Tensor): Batched predicted masks with shape (B, N, H, W).
337
+ - iou_pred (torch.Tensor): Batched predictions of mask quality with shape (B, N).
338
+ - sam_tokens_out (torch.Tensor): Batched SAM token for mask output with shape (B, N, C).
339
+ - object_score_logits (torch.Tensor): Batched object score logits with shape (B, 1).
340
+
341
+ Examples:
342
+ >>> image_embeddings = torch.rand(1, 256, 64, 64)
343
+ >>> image_pe = torch.rand(1, 256, 64, 64)
344
+ >>> sparse_prompt_embeddings = torch.rand(1, 2, 256)
345
+ >>> dense_prompt_embeddings = torch.rand(1, 256, 64, 64)
346
+ >>> decoder = SAM2MaskDecoder(256, transformer)
347
+ >>> masks, iou_pred, sam_tokens_out, obj_score_logits = decoder.forward(
348
+ ... image_embeddings, image_pe, sparse_prompt_embeddings, dense_prompt_embeddings, True, False)
349
+ """
350
+ masks, iou_pred, mask_tokens_out, object_score_logits = self.predict_masks(
351
+ image_embeddings=image_embeddings,
352
+ image_pe=image_pe,
353
+ sparse_prompt_embeddings=sparse_prompt_embeddings,
354
+ dense_prompt_embeddings=dense_prompt_embeddings,
355
+ repeat_image=repeat_image,
356
+ high_res_features=high_res_features,
357
+ )
358
+
359
+ # Select the correct mask or masks for output
360
+ if multimask_output:
361
+ masks = masks[:, 1:, :, :]
362
+ iou_pred = iou_pred[:, 1:]
363
+ elif self.dynamic_multimask_via_stability and not self.training:
364
+ masks, iou_pred = self._dynamic_multimask_via_stability(masks, iou_pred)
365
+ else:
366
+ masks = masks[:, 0:1, :, :]
367
+ iou_pred = iou_pred[:, 0:1]
368
+
369
+ if multimask_output and self.use_multimask_token_for_obj_ptr:
370
+ sam_tokens_out = mask_tokens_out[:, 1:] # [b, 3, c] shape
371
+ else:
372
+ # Take the mask output token. Here we *always* use the token for single mask output.
373
+ # At test time, even if we track after 1-click (and using multimask_output=True),
374
+ # we still take the single mask token here. The rationale is that we always track
375
+ # after multiple clicks during training, so the past tokens seen during training
376
+ # are always the single mask token (and we'll let it be the object-memory token).
377
+ sam_tokens_out = mask_tokens_out[:, 0:1] # [b, 1, c] shape
378
+
379
+ # Prepare output
380
+ return masks, iou_pred, sam_tokens_out, object_score_logits
381
+
382
+ def predict_masks(
383
+ self,
384
+ image_embeddings: torch.Tensor,
385
+ image_pe: torch.Tensor,
386
+ sparse_prompt_embeddings: torch.Tensor,
387
+ dense_prompt_embeddings: torch.Tensor,
388
+ repeat_image: bool,
389
+ high_res_features: Optional[List[torch.Tensor]] = None,
390
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
391
+ """Predicts instance segmentation masks from image and prompt embeddings using a transformer."""
392
+ # Concatenate output tokens
393
+ s = 0
394
+ if self.pred_obj_scores:
395
+ output_tokens = torch.cat(
396
+ [
397
+ self.obj_score_token.weight,
398
+ self.iou_token.weight,
399
+ self.mask_tokens.weight,
400
+ ],
401
+ dim=0,
402
+ )
403
+ s = 1
404
+ else:
405
+ output_tokens = torch.cat([self.iou_token.weight, self.mask_tokens.weight], dim=0)
406
+ output_tokens = output_tokens.unsqueeze(0).expand(sparse_prompt_embeddings.size(0), -1, -1)
407
+ tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1)
408
+
409
+ # Expand per-image data in batch direction to be per-mask
410
+ if repeat_image:
411
+ src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0)
412
+ else:
413
+ assert image_embeddings.shape[0] == tokens.shape[0]
414
+ src = image_embeddings
415
+ src = src + dense_prompt_embeddings
416
+ assert image_pe.size(0) == 1, "image_pe should have size 1 in batch dim (from `get_dense_pe()`)"
417
+ pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0)
418
+ b, c, h, w = src.shape
419
+
420
+ # Run the transformer
421
+ hs, src = self.transformer(src, pos_src, tokens)
422
+ iou_token_out = hs[:, s, :]
423
+ mask_tokens_out = hs[:, s + 1 : (s + 1 + self.num_mask_tokens), :]
424
+
425
+ # Upscale mask embeddings and predict masks using the mask tokens
426
+ src = src.transpose(1, 2).view(b, c, h, w)
427
+ if not self.use_high_res_features:
428
+ upscaled_embedding = self.output_upscaling(src)
429
+ else:
430
+ dc1, ln1, act1, dc2, act2 = self.output_upscaling
431
+ feat_s0, feat_s1 = high_res_features
432
+ upscaled_embedding = act1(ln1(dc1(src) + feat_s1))
433
+ upscaled_embedding = act2(dc2(upscaled_embedding) + feat_s0)
434
+
435
+ hyper_in_list: List[torch.Tensor] = []
436
+ for i in range(self.num_mask_tokens):
437
+ hyper_in_list.append(self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :]))
438
+ hyper_in = torch.stack(hyper_in_list, dim=1)
439
+ b, c, h, w = upscaled_embedding.shape
440
+ masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w)
441
+
442
+ # Generate mask quality predictions
443
+ iou_pred = self.iou_prediction_head(iou_token_out)
444
+ if self.pred_obj_scores:
445
+ assert s == 1
446
+ object_score_logits = self.pred_obj_score_head(hs[:, 0, :])
447
+ else:
448
+ # Obj scores logits - default to 10.0, i.e. assuming the object is present, sigmoid(10)=1
449
+ object_score_logits = 10.0 * iou_pred.new_ones(iou_pred.shape[0], 1)
450
+
451
+ return masks, iou_pred, mask_tokens_out, object_score_logits
452
+
453
+ def _get_stability_scores(self, mask_logits):
454
+ """Computes mask stability scores based on IoU between upper and lower thresholds."""
455
+ mask_logits = mask_logits.flatten(-2)
456
+ stability_delta = self.dynamic_multimask_stability_delta
457
+ area_i = torch.sum(mask_logits > stability_delta, dim=-1).float()
458
+ area_u = torch.sum(mask_logits > -stability_delta, dim=-1).float()
459
+ stability_scores = torch.where(area_u > 0, area_i / area_u, 1.0)
460
+ return stability_scores
461
+
462
+ def _dynamic_multimask_via_stability(self, all_mask_logits, all_iou_scores):
463
+ """
464
+ Dynamically selects the most stable mask output based on stability scores and IoU predictions.
465
+
466
+ This method is used when outputting a single mask. If the stability score from the current single-mask
467
+ output (based on output token 0) falls below a threshold, it instead selects from multi-mask outputs
468
+ (based on output tokens 1-3) the mask with the highest predicted IoU score. This ensures a valid mask
469
+ for both clicking and tracking scenarios.
470
+
471
+ Args:
472
+ all_mask_logits (torch.Tensor): Logits for all predicted masks, shape (B, N, H, W) where B is
473
+ batch size, N is number of masks (typically 4), and H, W are mask dimensions.
474
+ all_iou_scores (torch.Tensor): Predicted IoU scores for all masks, shape (B, N).
475
+
476
+ Returns:
477
+ (Tuple[torch.Tensor, torch.Tensor]):
478
+ - mask_logits_out (torch.Tensor): Selected mask logits, shape (B, 1, H, W).
479
+ - iou_scores_out (torch.Tensor): Selected IoU scores, shape (B, 1).
480
+
481
+ Examples:
482
+ >>> decoder = SAM2MaskDecoder(...)
483
+ >>> all_mask_logits = torch.rand(2, 4, 256, 256) # 2 images, 4 masks each
484
+ >>> all_iou_scores = torch.rand(2, 4)
485
+ >>> mask_logits, iou_scores = decoder._dynamic_multimask_via_stability(all_mask_logits, all_iou_scores)
486
+ >>> print(mask_logits.shape, iou_scores.shape)
487
+ torch.Size([2, 1, 256, 256]) torch.Size([2, 1])
488
+ """
489
+ # The best mask from multimask output tokens (1~3)
490
+ multimask_logits = all_mask_logits[:, 1:, :, :]
491
+ multimask_iou_scores = all_iou_scores[:, 1:]
492
+ best_scores_inds = torch.argmax(multimask_iou_scores, dim=-1)
493
+ batch_inds = torch.arange(multimask_iou_scores.size(0), device=all_iou_scores.device)
494
+ best_multimask_logits = multimask_logits[batch_inds, best_scores_inds]
495
+ best_multimask_logits = best_multimask_logits.unsqueeze(1)
496
+ best_multimask_iou_scores = multimask_iou_scores[batch_inds, best_scores_inds]
497
+ best_multimask_iou_scores = best_multimask_iou_scores.unsqueeze(1)
498
+
499
+ # The mask from singlemask output token 0 and its stability score
500
+ singlemask_logits = all_mask_logits[:, 0:1, :, :]
501
+ singlemask_iou_scores = all_iou_scores[:, 0:1]
502
+ stability_scores = self._get_stability_scores(singlemask_logits)
503
+ is_stable = stability_scores >= self.dynamic_multimask_stability_thresh
504
+
505
+ # Dynamically fall back to best multimask output upon low stability scores.
506
+ mask_logits_out = torch.where(
507
+ is_stable[..., None, None].expand_as(singlemask_logits),
508
+ singlemask_logits,
509
+ best_multimask_logits,
510
+ )
511
+ iou_scores_out = torch.where(
512
+ is_stable.expand_as(singlemask_iou_scores),
513
+ singlemask_iou_scores,
514
+ best_multimask_iou_scores,
515
+ )
516
+ return mask_logits_out, iou_scores_out