nnInteractive 2.0.0__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 (76) hide show
  1. nnInteractive/__init__.py +3 -0
  2. nnInteractive/inference/__init__.py +0 -0
  3. nnInteractive/inference/cvpr2025_challenge_baseline/__init__.py +0 -0
  4. nnInteractive/inference/cvpr2025_challenge_baseline/predict.py +173 -0
  5. nnInteractive/inference/inference_session.py +1400 -0
  6. nnInteractive/interaction/__init__.py +0 -0
  7. nnInteractive/interaction/point.py +166 -0
  8. nnInteractive/supervoxel/setup.py +4 -0
  9. nnInteractive/supervoxel/src/metadata.py +118 -0
  10. nnInteractive/supervoxel/src/reader.py +175 -0
  11. nnInteractive/supervoxel/src/run.py +136 -0
  12. nnInteractive/supervoxel/src/sam2/__init__.py +2 -0
  13. nnInteractive/supervoxel/src/sam2/sam2/__init__.py +11 -0
  14. nnInteractive/supervoxel/src/sam2/sam2/automatic_mask_generator.py +434 -0
  15. nnInteractive/supervoxel/src/sam2/sam2/benchmark.py +86 -0
  16. nnInteractive/supervoxel/src/sam2/sam2/build_sam.py +172 -0
  17. nnInteractive/supervoxel/src/sam2/sam2/modeling/__init__.py +5 -0
  18. nnInteractive/supervoxel/src/sam2/sam2/modeling/backbones/__init__.py +5 -0
  19. nnInteractive/supervoxel/src/sam2/sam2/modeling/backbones/hieradet.py +305 -0
  20. nnInteractive/supervoxel/src/sam2/sam2/modeling/backbones/image_encoder.py +132 -0
  21. nnInteractive/supervoxel/src/sam2/sam2/modeling/backbones/utils.py +89 -0
  22. nnInteractive/supervoxel/src/sam2/sam2/modeling/memory_attention.py +167 -0
  23. nnInteractive/supervoxel/src/sam2/sam2/modeling/memory_encoder.py +179 -0
  24. nnInteractive/supervoxel/src/sam2/sam2/modeling/position_encoding.py +217 -0
  25. nnInteractive/supervoxel/src/sam2/sam2/modeling/sam/__init__.py +5 -0
  26. nnInteractive/supervoxel/src/sam2/sam2/modeling/sam/mask_decoder.py +274 -0
  27. nnInteractive/supervoxel/src/sam2/sam2/modeling/sam/prompt_encoder.py +194 -0
  28. nnInteractive/supervoxel/src/sam2/sam2/modeling/sam/transformer.py +293 -0
  29. nnInteractive/supervoxel/src/sam2/sam2/modeling/sam2_base.py +879 -0
  30. nnInteractive/supervoxel/src/sam2/sam2/modeling/sam2_utils.py +315 -0
  31. nnInteractive/supervoxel/src/sam2/sam2/sam2_image_predictor.py +433 -0
  32. nnInteractive/supervoxel/src/sam2/sam2/sam2_video_predictor.py +1171 -0
  33. nnInteractive/supervoxel/src/sam2/sam2/sam2_video_predictor_legacy.py +1125 -0
  34. nnInteractive/supervoxel/src/sam2/sam2/utils/__init__.py +5 -0
  35. nnInteractive/supervoxel/src/sam2/sam2/utils/amg.py +332 -0
  36. nnInteractive/supervoxel/src/sam2/sam2/utils/misc.py +488 -0
  37. nnInteractive/supervoxel/src/sam2/sam2/utils/transforms.py +108 -0
  38. nnInteractive/supervoxel/src/sam2/setup.py +174 -0
  39. nnInteractive/supervoxel/src/sam2/training/__init__.py +5 -0
  40. nnInteractive/supervoxel/src/sam2/training/dataset/__init__.py +5 -0
  41. nnInteractive/supervoxel/src/sam2/training/dataset/sam2_datasets.py +176 -0
  42. nnInteractive/supervoxel/src/sam2/training/dataset/transforms.py +481 -0
  43. nnInteractive/supervoxel/src/sam2/training/dataset/utils.py +102 -0
  44. nnInteractive/supervoxel/src/sam2/training/dataset/vos_dataset.py +154 -0
  45. nnInteractive/supervoxel/src/sam2/training/dataset/vos_raw_dataset.py +290 -0
  46. nnInteractive/supervoxel/src/sam2/training/dataset/vos_sampler.py +103 -0
  47. nnInteractive/supervoxel/src/sam2/training/dataset/vos_segment_loader.py +289 -0
  48. nnInteractive/supervoxel/src/sam2/training/loss_fns.py +290 -0
  49. nnInteractive/supervoxel/src/sam2/training/model/__init__.py +5 -0
  50. nnInteractive/supervoxel/src/sam2/training/model/sam2.py +515 -0
  51. nnInteractive/supervoxel/src/sam2/training/optimizer.py +462 -0
  52. nnInteractive/supervoxel/src/sam2/training/scripts/sav_frame_extraction_submitit.py +157 -0
  53. nnInteractive/supervoxel/src/sam2/training/train.py +232 -0
  54. nnInteractive/supervoxel/src/sam2/training/trainer.py +1051 -0
  55. nnInteractive/supervoxel/src/sam2/training/utils/__init__.py +5 -0
  56. nnInteractive/supervoxel/src/sam2/training/utils/checkpoint_utils.py +328 -0
  57. nnInteractive/supervoxel/src/sam2/training/utils/data_utils.py +166 -0
  58. nnInteractive/supervoxel/src/sam2/training/utils/distributed.py +560 -0
  59. nnInteractive/supervoxel/src/sam2/training/utils/logger.py +236 -0
  60. nnInteractive/supervoxel/src/sam2/training/utils/train_utils.py +275 -0
  61. nnInteractive/supervoxel/src/supervoxel.py +198 -0
  62. nnInteractive/trainer/__init__.py +0 -0
  63. nnInteractive/trainer/nnInteractiveTrainer.py +24 -0
  64. nnInteractive/utils/__init__.py +0 -0
  65. nnInteractive/utils/bboxes.py +217 -0
  66. nnInteractive/utils/checkpoint_cleansing.py +9 -0
  67. nnInteractive/utils/crop.py +268 -0
  68. nnInteractive/utils/erosion_dilation.py +48 -0
  69. nnInteractive/utils/inference_helpers.py +45 -0
  70. nnInteractive/utils/os_shennanigans.py +16 -0
  71. nnInteractive/utils/rounding.py +13 -0
  72. nninteractive-2.0.0.dist-info/METADATA +511 -0
  73. nninteractive-2.0.0.dist-info/RECORD +76 -0
  74. nninteractive-2.0.0.dist-info/WHEEL +5 -0
  75. nninteractive-2.0.0.dist-info/licenses/LICENSE +201 -0
  76. nninteractive-2.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,879 @@
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import torch
8
+ import torch.distributed
9
+ import torch.nn.functional as F
10
+
11
+ from torch.nn.init import trunc_normal_
12
+
13
+ from sam2.modeling.sam.mask_decoder import MaskDecoder
14
+ from sam2.modeling.sam.prompt_encoder import PromptEncoder
15
+ from sam2.modeling.sam.transformer import TwoWayTransformer
16
+ from sam2.modeling.sam2_utils import get_1d_sine_pe, MLP, select_closest_cond_frames
17
+
18
+ # a large negative value as a placeholder score for missing objects
19
+ NO_OBJ_SCORE = -1024.0
20
+
21
+
22
+ class SAM2Base(torch.nn.Module):
23
+ def __init__(
24
+ self,
25
+ image_encoder,
26
+ memory_attention,
27
+ memory_encoder,
28
+ num_maskmem=7, # default 1 input frame + 6 previous frames
29
+ image_size=512,
30
+ backbone_stride=16, # stride of the image backbone output
31
+ sigmoid_scale_for_mem_enc=1.0, # scale factor for mask sigmoid prob
32
+ sigmoid_bias_for_mem_enc=0.0, # bias factor for mask sigmoid prob
33
+ # During evaluation, whether to binarize the sigmoid mask logits on interacted frames with clicks
34
+ binarize_mask_from_pts_for_mem_enc=False,
35
+ use_mask_input_as_output_without_sam=False, # on frames with mask input, whether to directly output the input mask without using a SAM prompt encoder + mask decoder
36
+ # The maximum number of conditioning frames to participate in the memory attention (-1 means no limit; if there are more conditioning frames than this limit,
37
+ # we only cross-attend to the temporally closest `max_cond_frames_in_attn` conditioning frames in the encoder when tracking each frame). This gives the model
38
+ # a temporal locality when handling a large number of annotated frames (since closer frames should be more important) and also avoids GPU OOM.
39
+ max_cond_frames_in_attn=-1,
40
+ # on the first frame, whether to directly add the no-memory embedding to the image feature
41
+ # (instead of using the transformer encoder)
42
+ directly_add_no_mem_embed=False,
43
+ # whether to use high-resolution feature maps in the SAM mask decoder
44
+ use_high_res_features_in_sam=False,
45
+ # whether to output multiple (3) masks for the first click on initial conditioning frames
46
+ multimask_output_in_sam=False,
47
+ # the minimum and maximum number of clicks to use multimask_output_in_sam (only relevant when `multimask_output_in_sam=True`;
48
+ # default is 1 for both, meaning that only the first click gives multimask output; also note that a box counts as two points)
49
+ multimask_min_pt_num=1,
50
+ multimask_max_pt_num=1,
51
+ # whether to also use multimask output for tracking (not just for the first click on initial conditioning frames; only relevant when `multimask_output_in_sam=True`)
52
+ multimask_output_for_tracking=False,
53
+ # Whether to use multimask tokens for obj ptr; Only relevant when both
54
+ # use_obj_ptrs_in_encoder=True and multimask_output_for_tracking=True
55
+ use_multimask_token_for_obj_ptr: bool = False,
56
+ # whether to use sigmoid to restrict ious prediction to [0-1]
57
+ iou_prediction_use_sigmoid=False,
58
+ # The memory bank's temporal stride during evaluation (i.e. the `r` parameter in XMem and Cutie; XMem and Cutie use r=5).
59
+ # For r>1, the (self.num_maskmem - 1) non-conditioning memory frames consist of
60
+ # (self.num_maskmem - 2) nearest frames from every r-th frames, plus the last frame.
61
+ memory_temporal_stride_for_eval=1,
62
+ # whether to apply non-overlapping constraints on the object masks in the memory encoder during evaluation (to avoid/alleviate superposing masks)
63
+ non_overlap_masks_for_mem_enc=False,
64
+ # whether to cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder
65
+ use_obj_ptrs_in_encoder=False,
66
+ # the maximum number of object pointers from other frames in encoder cross attention (only relevant when `use_obj_ptrs_in_encoder=True`)
67
+ max_obj_ptrs_in_encoder=16,
68
+ # whether to add temporal positional encoding to the object pointers in the encoder (only relevant when `use_obj_ptrs_in_encoder=True`)
69
+ add_tpos_enc_to_obj_ptrs=True,
70
+ # whether to add an extra linear projection layer for the temporal positional encoding in the object pointers to avoid potential interference
71
+ # with spatial positional encoding (only relevant when both `use_obj_ptrs_in_encoder=True` and `add_tpos_enc_to_obj_ptrs=True`)
72
+ proj_tpos_enc_in_obj_ptrs=False,
73
+ # whether to use signed distance (instead of unsigned absolute distance) in the temporal positional encoding in the object pointers
74
+ # (only relevant when both `use_obj_ptrs_in_encoder=True` and `add_tpos_enc_to_obj_ptrs=True`)
75
+ use_signed_tpos_enc_to_obj_ptrs=False,
76
+ # whether to only attend to object pointers in the past (before the current frame) in the encoder during evaluation
77
+ # (only relevant when `use_obj_ptrs_in_encoder=True`; this might avoid pointer information too far in the future to distract the initial tracking)
78
+ only_obj_ptrs_in_the_past_for_eval=False,
79
+ # Whether to predict if there is an object in the frame
80
+ pred_obj_scores: bool = False,
81
+ # Whether to use an MLP to predict object scores
82
+ pred_obj_scores_mlp: bool = False,
83
+ # Only relevant if pred_obj_scores=True and use_obj_ptrs_in_encoder=True;
84
+ # Whether to have a fixed no obj pointer when there is no object present
85
+ # or to use it as an additive embedding with obj_ptr produced by decoder
86
+ fixed_no_obj_ptr: bool = False,
87
+ # Soft no object, i.e. mix in no_obj_ptr softly,
88
+ # hope to make recovery easier if there is a mistake and mitigate accumulation of errors
89
+ soft_no_obj_ptr: bool = False,
90
+ use_mlp_for_obj_ptr_proj: bool = False,
91
+ # add no obj embedding to spatial frames
92
+ no_obj_embed_spatial: bool = False,
93
+ # extra arguments used to construct the SAM mask decoder; if not None, it should be a dict of kwargs to be passed into `MaskDecoder` class.
94
+ sam_mask_decoder_extra_args=None,
95
+ compile_image_encoder: bool = False,
96
+ ):
97
+ super().__init__()
98
+
99
+ # Part 1: the image backbone
100
+ self.image_encoder = image_encoder
101
+ # Use level 0, 1, 2 for high-res setting, or just level 2 for the default setting
102
+ self.use_high_res_features_in_sam = use_high_res_features_in_sam
103
+ self.num_feature_levels = 3 if use_high_res_features_in_sam else 1
104
+ self.use_obj_ptrs_in_encoder = use_obj_ptrs_in_encoder
105
+ self.max_obj_ptrs_in_encoder = max_obj_ptrs_in_encoder
106
+ if use_obj_ptrs_in_encoder:
107
+ # A conv layer to downsample the mask prompt to stride 4 (the same stride as
108
+ # low-res SAM mask logits) and to change its scales from 0~1 to SAM logit scale,
109
+ # so that it can be fed into the SAM mask decoder to generate a pointer.
110
+ self.mask_downsample = torch.nn.Conv2d(1, 1, kernel_size=4, stride=4)
111
+ self.add_tpos_enc_to_obj_ptrs = add_tpos_enc_to_obj_ptrs
112
+ if proj_tpos_enc_in_obj_ptrs:
113
+ assert add_tpos_enc_to_obj_ptrs # these options need to be used together
114
+ self.proj_tpos_enc_in_obj_ptrs = proj_tpos_enc_in_obj_ptrs
115
+ self.use_signed_tpos_enc_to_obj_ptrs = use_signed_tpos_enc_to_obj_ptrs
116
+ self.only_obj_ptrs_in_the_past_for_eval = only_obj_ptrs_in_the_past_for_eval
117
+
118
+ # Part 2: memory attention to condition current frame's visual features
119
+ # with memories (and obj ptrs) from past frames
120
+ self.memory_attention = memory_attention
121
+ self.hidden_dim = image_encoder.neck.d_model
122
+
123
+ # Part 3: memory encoder for the previous frame's outputs
124
+ self.memory_encoder = memory_encoder
125
+ self.mem_dim = self.hidden_dim
126
+ if hasattr(self.memory_encoder, "out_proj") and hasattr(self.memory_encoder.out_proj, "weight"):
127
+ # if there is compression of memories along channel dim
128
+ self.mem_dim = self.memory_encoder.out_proj.weight.shape[0]
129
+ self.num_maskmem = num_maskmem # Number of memories accessible
130
+ # Temporal encoding of the memories
131
+ self.maskmem_tpos_enc = torch.nn.Parameter(torch.zeros(num_maskmem, 1, 1, self.mem_dim))
132
+ trunc_normal_(self.maskmem_tpos_enc, std=0.02)
133
+ # a single token to indicate no memory embedding from previous frames
134
+ self.no_mem_embed = torch.nn.Parameter(torch.zeros(1, 1, self.hidden_dim))
135
+ self.no_mem_pos_enc = torch.nn.Parameter(torch.zeros(1, 1, self.hidden_dim))
136
+ trunc_normal_(self.no_mem_embed, std=0.02)
137
+ trunc_normal_(self.no_mem_pos_enc, std=0.02)
138
+ self.directly_add_no_mem_embed = directly_add_no_mem_embed
139
+ # Apply sigmoid to the output raw mask logits (to turn them from
140
+ # range (-inf, +inf) to range (0, 1)) before feeding them into the memory encoder
141
+ self.sigmoid_scale_for_mem_enc = sigmoid_scale_for_mem_enc
142
+ self.sigmoid_bias_for_mem_enc = sigmoid_bias_for_mem_enc
143
+ self.binarize_mask_from_pts_for_mem_enc = binarize_mask_from_pts_for_mem_enc
144
+ self.non_overlap_masks_for_mem_enc = non_overlap_masks_for_mem_enc
145
+ self.memory_temporal_stride_for_eval = memory_temporal_stride_for_eval
146
+ # On frames with mask input, whether to directly output the input mask without
147
+ # using a SAM prompt encoder + mask decoder
148
+ self.use_mask_input_as_output_without_sam = use_mask_input_as_output_without_sam
149
+ self.multimask_output_in_sam = multimask_output_in_sam
150
+ self.multimask_min_pt_num = multimask_min_pt_num
151
+ self.multimask_max_pt_num = multimask_max_pt_num
152
+ self.multimask_output_for_tracking = multimask_output_for_tracking
153
+ self.use_multimask_token_for_obj_ptr = use_multimask_token_for_obj_ptr
154
+ self.iou_prediction_use_sigmoid = iou_prediction_use_sigmoid
155
+
156
+ # Part 4: SAM-style prompt encoder (for both mask and point inputs)
157
+ # and SAM-style mask decoder for the final mask output
158
+ self.image_size = image_size
159
+ self.backbone_stride = backbone_stride
160
+ self.sam_mask_decoder_extra_args = sam_mask_decoder_extra_args
161
+ self.pred_obj_scores = pred_obj_scores
162
+ self.pred_obj_scores_mlp = pred_obj_scores_mlp
163
+ self.fixed_no_obj_ptr = fixed_no_obj_ptr
164
+ self.soft_no_obj_ptr = soft_no_obj_ptr
165
+ if self.fixed_no_obj_ptr:
166
+ assert self.pred_obj_scores
167
+ assert self.use_obj_ptrs_in_encoder
168
+ if self.pred_obj_scores and self.use_obj_ptrs_in_encoder:
169
+ self.no_obj_ptr = torch.nn.Parameter(torch.zeros(1, self.hidden_dim))
170
+ trunc_normal_(self.no_obj_ptr, std=0.02)
171
+ self.use_mlp_for_obj_ptr_proj = use_mlp_for_obj_ptr_proj
172
+ self.no_obj_embed_spatial = None
173
+ if no_obj_embed_spatial:
174
+ self.no_obj_embed_spatial = torch.nn.Parameter(torch.zeros(1, self.mem_dim))
175
+ trunc_normal_(self.no_obj_embed_spatial, std=0.02)
176
+
177
+ self._build_sam_heads()
178
+ self.max_cond_frames_in_attn = max_cond_frames_in_attn
179
+
180
+ # Model compilation
181
+ if compile_image_encoder:
182
+ # Compile the forward function (not the full module) to allow loading checkpoints.
183
+ print("Image encoder compilation is enabled. First forward pass will be slow.")
184
+ self.image_encoder.forward = torch.compile(
185
+ self.image_encoder.forward,
186
+ mode="max-autotune",
187
+ fullgraph=True,
188
+ dynamic=False,
189
+ )
190
+
191
+ @property
192
+ def device(self):
193
+ return next(self.parameters()).device
194
+
195
+ def forward(self, *args, **kwargs):
196
+ raise NotImplementedError(
197
+ "Please use the corresponding methods in SAM2VideoPredictor for inference or SAM2Train for training/fine-tuning"
198
+ "See notebooks/video_predictor_example.ipynb for an inference example."
199
+ )
200
+
201
+ def _build_sam_heads(self):
202
+ """Build SAM-style prompt encoder and mask decoder."""
203
+ self.sam_prompt_embed_dim = self.hidden_dim
204
+ self.sam_image_embedding_size = self.image_size // self.backbone_stride
205
+
206
+ # build PromptEncoder and MaskDecoder from SAM
207
+ # (their hyperparameters like `mask_in_chans=16` are from SAM code)
208
+ self.sam_prompt_encoder = PromptEncoder(
209
+ embed_dim=self.sam_prompt_embed_dim,
210
+ image_embedding_size=(
211
+ self.sam_image_embedding_size,
212
+ self.sam_image_embedding_size,
213
+ ),
214
+ input_image_size=(self.image_size, self.image_size),
215
+ mask_in_chans=16,
216
+ )
217
+ self.sam_mask_decoder = MaskDecoder(
218
+ num_multimask_outputs=3,
219
+ transformer=TwoWayTransformer(
220
+ depth=2,
221
+ embedding_dim=self.sam_prompt_embed_dim,
222
+ mlp_dim=2048,
223
+ num_heads=8,
224
+ ),
225
+ transformer_dim=self.sam_prompt_embed_dim,
226
+ iou_head_depth=3,
227
+ iou_head_hidden_dim=256,
228
+ use_high_res_features=self.use_high_res_features_in_sam,
229
+ iou_prediction_use_sigmoid=self.iou_prediction_use_sigmoid,
230
+ pred_obj_scores=self.pred_obj_scores,
231
+ pred_obj_scores_mlp=self.pred_obj_scores_mlp,
232
+ use_multimask_token_for_obj_ptr=self.use_multimask_token_for_obj_ptr,
233
+ **(self.sam_mask_decoder_extra_args or {}),
234
+ )
235
+ if self.use_obj_ptrs_in_encoder:
236
+ # a linear projection on SAM output tokens to turn them into object pointers
237
+ self.obj_ptr_proj = torch.nn.Linear(self.hidden_dim, self.hidden_dim)
238
+ if self.use_mlp_for_obj_ptr_proj:
239
+ self.obj_ptr_proj = MLP(self.hidden_dim, self.hidden_dim, self.hidden_dim, 3)
240
+ else:
241
+ self.obj_ptr_proj = torch.nn.Identity()
242
+ if self.proj_tpos_enc_in_obj_ptrs:
243
+ # a linear projection on temporal positional encoding in object pointers to
244
+ # avoid potential interference with spatial positional encoding
245
+ self.obj_ptr_tpos_proj = torch.nn.Linear(self.hidden_dim, self.mem_dim)
246
+ else:
247
+ self.obj_ptr_tpos_proj = torch.nn.Identity()
248
+
249
+ def _forward_sam_heads(
250
+ self,
251
+ backbone_features,
252
+ point_inputs=None,
253
+ mask_inputs=None,
254
+ high_res_features=None,
255
+ multimask_output=False,
256
+ ):
257
+ """
258
+ Forward SAM prompt encoders and mask heads.
259
+
260
+ Inputs:
261
+ - backbone_features: image features of [B, C, H, W] shape
262
+ - point_inputs: a dictionary with "point_coords" and "point_labels", where
263
+ 1) "point_coords" has [B, P, 2] shape and float32 dtype and contains the
264
+ absolute pixel-unit coordinate in (x, y) format of the P input points
265
+ 2) "point_labels" has shape [B, P] and int32 dtype, where 1 means
266
+ positive clicks, 0 means negative clicks, and -1 means padding
267
+ - mask_inputs: a mask of [B, 1, H*16, W*16] shape, float or bool, with the
268
+ same spatial size as the image.
269
+ - high_res_features: either 1) None or 2) or a list of length 2 containing
270
+ two feature maps of [B, C, 4*H, 4*W] and [B, C, 2*H, 2*W] shapes respectively,
271
+ which will be used as high-resolution feature maps for SAM decoder.
272
+ - multimask_output: if it's True, we output 3 candidate masks and their 3
273
+ corresponding IoU estimates, and if it's False, we output only 1 mask and
274
+ its corresponding IoU estimate.
275
+
276
+ Outputs:
277
+ - low_res_multimasks: [B, M, H*4, W*4] shape (where M = 3 if
278
+ `multimask_output=True` and M = 1 if `multimask_output=False`), the SAM
279
+ output mask logits (before sigmoid) for the low-resolution masks, with 4x
280
+ the resolution (1/4 stride) of the input backbone_features.
281
+ - high_res_multimasks: [B, M, H*16, W*16] shape (where M = 3
282
+ if `multimask_output=True` and M = 1 if `multimask_output=False`),
283
+ upsampled from the low-resolution masks, with shape size as the image
284
+ (stride is 1 pixel).
285
+ - ious, [B, M] shape, where (where M = 3 if `multimask_output=True` and M = 1
286
+ if `multimask_output=False`), the estimated IoU of each output mask.
287
+ - low_res_masks: [B, 1, H*4, W*4] shape, the best mask in `low_res_multimasks`.
288
+ If `multimask_output=True`, it's the mask with the highest IoU estimate.
289
+ If `multimask_output=False`, it's the same as `low_res_multimasks`.
290
+ - high_res_masks: [B, 1, H*16, W*16] shape, the best mask in `high_res_multimasks`.
291
+ If `multimask_output=True`, it's the mask with the highest IoU estimate.
292
+ If `multimask_output=False`, it's the same as `high_res_multimasks`.
293
+ - obj_ptr: [B, C] shape, the object pointer vector for the output mask, extracted
294
+ based on the output token from the SAM mask decoder.
295
+ """
296
+ B = backbone_features.size(0)
297
+ device = backbone_features.device
298
+ assert backbone_features.size(1) == self.sam_prompt_embed_dim
299
+ assert backbone_features.size(2) == self.sam_image_embedding_size
300
+ assert backbone_features.size(3) == self.sam_image_embedding_size
301
+
302
+ # a) Handle point prompts
303
+ if point_inputs is not None:
304
+ sam_point_coords = point_inputs["point_coords"]
305
+ sam_point_labels = point_inputs["point_labels"]
306
+ assert sam_point_coords.size(0) == B and sam_point_labels.size(0) == B
307
+ else:
308
+ # If no points are provide, pad with an empty point (with label -1)
309
+ sam_point_coords = torch.zeros(B, 1, 2, device=device)
310
+ sam_point_labels = -torch.ones(B, 1, dtype=torch.int32, device=device)
311
+
312
+ # b) Handle mask prompts
313
+ if mask_inputs is not None:
314
+ # If mask_inputs is provided, downsize it into low-res mask input if needed
315
+ # and feed it as a dense mask prompt into the SAM mask encoder
316
+ assert len(mask_inputs.shape) == 4 and mask_inputs.shape[:2] == (B, 1)
317
+ if mask_inputs.shape[-2:] != self.sam_prompt_encoder.mask_input_size:
318
+ sam_mask_prompt = F.interpolate(
319
+ mask_inputs.float(),
320
+ size=self.sam_prompt_encoder.mask_input_size,
321
+ align_corners=False,
322
+ mode="bilinear",
323
+ antialias=True, # use antialias for downsampling
324
+ )
325
+ else:
326
+ sam_mask_prompt = mask_inputs
327
+ else:
328
+ # Otherwise, simply feed None (and SAM's prompt encoder will add
329
+ # a learned `no_mask_embed` to indicate no mask input in this case).
330
+ sam_mask_prompt = None
331
+
332
+ sparse_embeddings, dense_embeddings = self.sam_prompt_encoder(
333
+ points=(sam_point_coords, sam_point_labels),
334
+ boxes=None,
335
+ masks=sam_mask_prompt,
336
+ )
337
+ (
338
+ low_res_multimasks,
339
+ ious,
340
+ sam_output_tokens,
341
+ object_score_logits,
342
+ ) = self.sam_mask_decoder(
343
+ image_embeddings=backbone_features,
344
+ image_pe=self.sam_prompt_encoder.get_dense_pe(),
345
+ sparse_prompt_embeddings=sparse_embeddings,
346
+ dense_prompt_embeddings=dense_embeddings,
347
+ multimask_output=multimask_output,
348
+ repeat_image=False, # the image is already batched
349
+ high_res_features=high_res_features,
350
+ )
351
+ if self.pred_obj_scores:
352
+ is_obj_appearing = object_score_logits > 0
353
+
354
+ # Mask used for spatial memories is always a *hard* choice between obj and no obj,
355
+ # consistent with the actual mask prediction
356
+ low_res_multimasks = torch.where(
357
+ is_obj_appearing[:, None, None],
358
+ low_res_multimasks,
359
+ NO_OBJ_SCORE,
360
+ )
361
+
362
+ # convert masks from possibly bfloat16 (or float16) to float32
363
+ # (older PyTorch versions before 2.1 don't support `interpolate` on bf16)
364
+ low_res_multimasks = low_res_multimasks.float()
365
+ high_res_multimasks = F.interpolate(
366
+ low_res_multimasks,
367
+ size=(self.image_size, self.image_size),
368
+ mode="bilinear",
369
+ align_corners=False,
370
+ )
371
+
372
+ sam_output_token = sam_output_tokens[:, 0]
373
+ if multimask_output:
374
+ # take the best mask prediction (with the highest IoU estimation)
375
+ best_iou_inds = torch.argmax(ious, dim=-1)
376
+ batch_inds = torch.arange(B, device=device)
377
+ low_res_masks = low_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1)
378
+ high_res_masks = high_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1)
379
+ if sam_output_tokens.size(1) > 1:
380
+ sam_output_token = sam_output_tokens[batch_inds, best_iou_inds]
381
+ else:
382
+ low_res_masks, high_res_masks = low_res_multimasks, high_res_multimasks
383
+
384
+ # Extract object pointer from the SAM output token (with occlusion handling)
385
+ obj_ptr = self.obj_ptr_proj(sam_output_token)
386
+ if self.pred_obj_scores:
387
+ # Allow *soft* no obj ptr, unlike for masks
388
+ if self.soft_no_obj_ptr:
389
+ lambda_is_obj_appearing = object_score_logits.sigmoid()
390
+ else:
391
+ lambda_is_obj_appearing = is_obj_appearing.float()
392
+
393
+ if self.fixed_no_obj_ptr:
394
+ obj_ptr = lambda_is_obj_appearing * obj_ptr
395
+ obj_ptr = obj_ptr + (1 - lambda_is_obj_appearing) * self.no_obj_ptr
396
+
397
+ return (
398
+ low_res_multimasks,
399
+ high_res_multimasks,
400
+ ious,
401
+ low_res_masks,
402
+ high_res_masks,
403
+ obj_ptr,
404
+ object_score_logits,
405
+ )
406
+
407
+ def _use_mask_as_output(self, backbone_features, high_res_features, mask_inputs):
408
+ """
409
+ Directly turn binary `mask_inputs` into a output mask logits without using SAM.
410
+ (same input and output shapes as in _forward_sam_heads above).
411
+ """
412
+ # Use -10/+10 as logits for neg/pos pixels (very close to 0/1 in prob after sigmoid).
413
+ out_scale, out_bias = 20.0, -10.0 # sigmoid(-10.0)=4.5398e-05
414
+ mask_inputs_float = mask_inputs.float()
415
+ high_res_masks = mask_inputs_float * out_scale + out_bias
416
+ low_res_masks = F.interpolate(
417
+ high_res_masks,
418
+ size=(high_res_masks.size(-2) // 4, high_res_masks.size(-1) // 4),
419
+ align_corners=False,
420
+ mode="bilinear",
421
+ antialias=True, # use antialias for downsampling
422
+ )
423
+ # a dummy IoU prediction of all 1's under mask input
424
+ ious = mask_inputs.new_ones(mask_inputs.size(0), 1).float()
425
+ if not self.use_obj_ptrs_in_encoder:
426
+ # all zeros as a dummy object pointer (of shape [B, C])
427
+ obj_ptr = torch.zeros(mask_inputs.size(0), self.hidden_dim, device=mask_inputs.device)
428
+ else:
429
+ # produce an object pointer using the SAM decoder from the mask input
430
+ _, _, _, _, _, obj_ptr, _ = self._forward_sam_heads(
431
+ backbone_features=backbone_features,
432
+ mask_inputs=self.mask_downsample(mask_inputs_float),
433
+ high_res_features=high_res_features,
434
+ )
435
+ # In this method, we are treating mask_input as output, e.g. using it directly to create spatial mem;
436
+ # Below, we follow the same design axiom to use mask_input to decide if obj appears or not instead of relying
437
+ # on the object_scores from the SAM decoder.
438
+ is_obj_appearing = torch.any(mask_inputs.flatten(1).float() > 0.0, dim=1)
439
+ is_obj_appearing = is_obj_appearing[..., None]
440
+ lambda_is_obj_appearing = is_obj_appearing.float()
441
+ object_score_logits = out_scale * lambda_is_obj_appearing + out_bias
442
+ if self.pred_obj_scores:
443
+ if self.fixed_no_obj_ptr:
444
+ obj_ptr = lambda_is_obj_appearing * obj_ptr
445
+ obj_ptr = obj_ptr + (1 - lambda_is_obj_appearing) * self.no_obj_ptr
446
+
447
+ return (
448
+ low_res_masks,
449
+ high_res_masks,
450
+ ious,
451
+ low_res_masks,
452
+ high_res_masks,
453
+ obj_ptr,
454
+ object_score_logits,
455
+ )
456
+
457
+ def forward_image(self, img_batch: torch.Tensor):
458
+ """Get the image feature on the input batch."""
459
+ backbone_out = self.image_encoder(img_batch)
460
+ if self.use_high_res_features_in_sam:
461
+ # precompute projected level 0 and level 1 features in SAM decoder
462
+ # to avoid running it again on every SAM click
463
+ backbone_out["backbone_fpn"][0] = self.sam_mask_decoder.conv_s0(backbone_out["backbone_fpn"][0])
464
+ backbone_out["backbone_fpn"][1] = self.sam_mask_decoder.conv_s1(backbone_out["backbone_fpn"][1])
465
+ return backbone_out
466
+
467
+ def _prepare_backbone_features(self, backbone_out):
468
+ """Prepare and flatten visual features."""
469
+ backbone_out = backbone_out.copy()
470
+ assert len(backbone_out["backbone_fpn"]) == len(backbone_out["vision_pos_enc"])
471
+ assert len(backbone_out["backbone_fpn"]) >= self.num_feature_levels
472
+
473
+ feature_maps = backbone_out["backbone_fpn"][-self.num_feature_levels :]
474
+ vision_pos_embeds = backbone_out["vision_pos_enc"][-self.num_feature_levels :]
475
+
476
+ feat_sizes = [(x.shape[-2], x.shape[-1]) for x in vision_pos_embeds]
477
+ # flatten NxCxHxW to HWxNxC
478
+ vision_feats = [x.flatten(2).permute(2, 0, 1) for x in feature_maps]
479
+ vision_pos_embeds = [x.flatten(2).permute(2, 0, 1) for x in vision_pos_embeds]
480
+
481
+ return backbone_out, vision_feats, vision_pos_embeds, feat_sizes
482
+
483
+ def _prepare_memory_conditioned_features(
484
+ self,
485
+ frame_idx,
486
+ is_init_cond_frame,
487
+ current_vision_feats,
488
+ current_vision_pos_embeds,
489
+ feat_sizes,
490
+ output_dict,
491
+ num_frames,
492
+ track_in_reverse=False, # tracking in reverse time order (for demo usage)
493
+ ):
494
+ """Fuse the current frame's visual feature map with previous memory."""
495
+ B = current_vision_feats[-1].size(1) # batch size on this frame
496
+ C = self.hidden_dim
497
+ H, W = feat_sizes[-1] # top-level (lowest-resolution) feature size
498
+ device = current_vision_feats[-1].device
499
+ # The case of `self.num_maskmem == 0` below is primarily used for reproducing SAM on images.
500
+ # In this case, we skip the fusion with any memory.
501
+ if self.num_maskmem == 0: # Disable memory and skip fusion
502
+ pix_feat = current_vision_feats[-1].permute(1, 2, 0).view(B, C, H, W)
503
+ return pix_feat
504
+
505
+ num_obj_ptr_tokens = 0
506
+ tpos_sign_mul = -1 if track_in_reverse else 1
507
+ # Step 1: condition the visual features of the current frame on previous memories
508
+ if not is_init_cond_frame:
509
+ # Retrieve the memories encoded with the maskmem backbone
510
+ to_cat_memory, to_cat_memory_pos_embed = [], []
511
+ # Add conditioning frames's output first (all cond frames have t_pos=0 for
512
+ # when getting temporal positional embedding below)
513
+ assert len(output_dict["cond_frame_outputs"]) > 0
514
+ # Select a maximum number of temporally closest cond frames for cross attention
515
+ cond_outputs = output_dict["cond_frame_outputs"]
516
+ selected_cond_outputs, unselected_cond_outputs = select_closest_cond_frames(
517
+ frame_idx, cond_outputs, self.max_cond_frames_in_attn
518
+ )
519
+ t_pos_and_prevs = [(0, out) for out in selected_cond_outputs.values()]
520
+ # Add last (self.num_maskmem - 1) frames before current frame for non-conditioning memory
521
+ # the earliest one has t_pos=1 and the latest one has t_pos=self.num_maskmem-1
522
+ # We also allow taking the memory frame non-consecutively (with stride>1), in which case
523
+ # we take (self.num_maskmem - 2) frames among every stride-th frames plus the last frame.
524
+ stride = 1 if self.training else self.memory_temporal_stride_for_eval
525
+ for t_pos in range(1, self.num_maskmem):
526
+ t_rel = self.num_maskmem - t_pos # how many frames before current frame
527
+ if t_rel == 1:
528
+ # for t_rel == 1, we take the last frame (regardless of r)
529
+ if not track_in_reverse:
530
+ # the frame immediately before this frame (i.e. frame_idx - 1)
531
+ prev_frame_idx = frame_idx - t_rel
532
+ else:
533
+ # the frame immediately after this frame (i.e. frame_idx + 1)
534
+ prev_frame_idx = frame_idx + t_rel
535
+ else:
536
+ # for t_rel >= 2, we take the memory frame from every r-th frames
537
+ if not track_in_reverse:
538
+ # first find the nearest frame among every r-th frames before this frame
539
+ # for r=1, this would be (frame_idx - 2)
540
+ prev_frame_idx = ((frame_idx - 2) // stride) * stride
541
+ # then seek further among every r-th frames
542
+ prev_frame_idx = prev_frame_idx - (t_rel - 2) * stride
543
+ else:
544
+ # first find the nearest frame among every r-th frames after this frame
545
+ # for r=1, this would be (frame_idx + 2)
546
+ prev_frame_idx = -(-(frame_idx + 2) // stride) * stride
547
+ # then seek further among every r-th frames
548
+ prev_frame_idx = prev_frame_idx + (t_rel - 2) * stride
549
+ out = output_dict["non_cond_frame_outputs"].get(prev_frame_idx, None)
550
+ if out is None:
551
+ # If an unselected conditioning frame is among the last (self.num_maskmem - 1)
552
+ # frames, we still attend to it as if it's a non-conditioning frame.
553
+ out = unselected_cond_outputs.get(prev_frame_idx, None)
554
+ t_pos_and_prevs.append((t_pos, out))
555
+
556
+ for t_pos, prev in t_pos_and_prevs:
557
+ if prev is None:
558
+ continue # skip padding frames
559
+ # "maskmem_features" might have been offloaded to CPU in demo use cases,
560
+ # so we load it back to GPU (it's a no-op if it's already on GPU).
561
+ feats = prev["maskmem_features"].to(device, non_blocking=True)
562
+ to_cat_memory.append(feats.flatten(2).permute(2, 0, 1))
563
+ # Spatial positional encoding (it might have been offloaded to CPU in eval)
564
+ maskmem_enc = prev["maskmem_pos_enc"][-1].to(device)
565
+ maskmem_enc = maskmem_enc.flatten(2).permute(2, 0, 1)
566
+ # Temporal positional encoding
567
+ maskmem_enc = maskmem_enc + self.maskmem_tpos_enc[self.num_maskmem - t_pos - 1]
568
+ to_cat_memory_pos_embed.append(maskmem_enc)
569
+
570
+ # Construct the list of past object pointers
571
+ if self.use_obj_ptrs_in_encoder:
572
+ max_obj_ptrs_in_encoder = min(num_frames, self.max_obj_ptrs_in_encoder)
573
+ # First add those object pointers from selected conditioning frames
574
+ # (optionally, only include object pointers in the past during evaluation)
575
+ if not self.training and self.only_obj_ptrs_in_the_past_for_eval:
576
+ ptr_cond_outputs = {
577
+ t: out
578
+ for t, out in selected_cond_outputs.items()
579
+ if (t >= frame_idx if track_in_reverse else t <= frame_idx)
580
+ }
581
+ else:
582
+ ptr_cond_outputs = selected_cond_outputs
583
+ pos_and_ptrs = [
584
+ # Temporal pos encoding contains how far away each pointer is from current frame
585
+ (
586
+ (
587
+ (frame_idx - t) * tpos_sign_mul
588
+ if self.use_signed_tpos_enc_to_obj_ptrs
589
+ else abs(frame_idx - t)
590
+ ),
591
+ out["obj_ptr"],
592
+ )
593
+ for t, out in ptr_cond_outputs.items()
594
+ ]
595
+ # Add up to (max_obj_ptrs_in_encoder - 1) non-conditioning frames before current frame
596
+ for t_diff in range(1, max_obj_ptrs_in_encoder):
597
+ t = frame_idx + t_diff if track_in_reverse else frame_idx - t_diff
598
+ if t < 0 or (num_frames is not None and t >= num_frames):
599
+ break
600
+ out = output_dict["non_cond_frame_outputs"].get(t, unselected_cond_outputs.get(t, None))
601
+ if out is not None:
602
+ pos_and_ptrs.append((t_diff, out["obj_ptr"]))
603
+ # If we have at least one object pointer, add them to the across attention
604
+ if len(pos_and_ptrs) > 0:
605
+ pos_list, ptrs_list = zip(*pos_and_ptrs)
606
+ # stack object pointers along dim=0 into [ptr_seq_len, B, C] shape
607
+ obj_ptrs = torch.stack(ptrs_list, dim=0)
608
+ # a temporal positional embedding based on how far each object pointer is from
609
+ # the current frame (sine embedding normalized by the max pointer num).
610
+ if self.add_tpos_enc_to_obj_ptrs:
611
+ t_diff_max = max_obj_ptrs_in_encoder - 1
612
+ tpos_dim = C if self.proj_tpos_enc_in_obj_ptrs else self.mem_dim
613
+ obj_pos = torch.tensor(pos_list).pin_memory().to(device=device, non_blocking=True)
614
+ obj_pos = get_1d_sine_pe(obj_pos / t_diff_max, dim=tpos_dim)
615
+ obj_pos = self.obj_ptr_tpos_proj(obj_pos)
616
+ obj_pos = obj_pos.unsqueeze(1).expand(-1, B, self.mem_dim)
617
+ else:
618
+ obj_pos = obj_ptrs.new_zeros(len(pos_list), B, self.mem_dim)
619
+ if self.mem_dim < C:
620
+ # split a pointer into (C // self.mem_dim) tokens for self.mem_dim < C
621
+ obj_ptrs = obj_ptrs.reshape(-1, B, C // self.mem_dim, self.mem_dim)
622
+ obj_ptrs = obj_ptrs.permute(0, 2, 1, 3).flatten(0, 1)
623
+ obj_pos = obj_pos.repeat_interleave(C // self.mem_dim, dim=0)
624
+ to_cat_memory.append(obj_ptrs)
625
+ to_cat_memory_pos_embed.append(obj_pos)
626
+ num_obj_ptr_tokens = obj_ptrs.shape[0]
627
+ else:
628
+ num_obj_ptr_tokens = 0
629
+ else:
630
+ # for initial conditioning frames, encode them without using any previous memory
631
+ if self.directly_add_no_mem_embed:
632
+ # directly add no-mem embedding (instead of using the transformer encoder)
633
+ pix_feat_with_mem = current_vision_feats[-1] + self.no_mem_embed
634
+ pix_feat_with_mem = pix_feat_with_mem.permute(1, 2, 0).view(B, C, H, W)
635
+ return pix_feat_with_mem
636
+
637
+ # Use a dummy token on the first frame (to avoid empty memory input to tranformer encoder)
638
+ to_cat_memory = [self.no_mem_embed.expand(1, B, self.mem_dim)]
639
+ to_cat_memory_pos_embed = [self.no_mem_pos_enc.expand(1, B, self.mem_dim)]
640
+
641
+ # Step 2: Concatenate the memories and forward through the transformer encoder
642
+ memory = torch.cat(to_cat_memory, dim=0)
643
+ memory_pos_embed = torch.cat(to_cat_memory_pos_embed, dim=0)
644
+
645
+ pix_feat_with_mem = self.memory_attention(
646
+ curr=current_vision_feats,
647
+ curr_pos=current_vision_pos_embeds,
648
+ memory=memory,
649
+ memory_pos=memory_pos_embed,
650
+ num_obj_ptr_tokens=num_obj_ptr_tokens,
651
+ )
652
+ # reshape the output (HW)BC => BCHW
653
+ pix_feat_with_mem = pix_feat_with_mem.permute(1, 2, 0).view(B, C, H, W)
654
+ return pix_feat_with_mem
655
+
656
+ def _encode_new_memory(
657
+ self,
658
+ current_vision_feats,
659
+ feat_sizes,
660
+ pred_masks_high_res,
661
+ object_score_logits,
662
+ is_mask_from_pts,
663
+ ):
664
+ """Encode the current image and its prediction into a memory feature."""
665
+ B = current_vision_feats[-1].size(1) # batch size on this frame
666
+ C = self.hidden_dim
667
+ H, W = feat_sizes[-1] # top-level (lowest-resolution) feature size
668
+ # top-level feature, (HW)BC => BCHW
669
+ pix_feat = current_vision_feats[-1].permute(1, 2, 0).view(B, C, H, W)
670
+ if self.non_overlap_masks_for_mem_enc and not self.training:
671
+ # optionally, apply non-overlapping constraints to the masks (it's applied
672
+ # in the batch dimension and should only be used during eval, where all
673
+ # the objects come from the same video under batch size 1).
674
+ pred_masks_high_res = self._apply_non_overlapping_constraints(pred_masks_high_res)
675
+ # scale the raw mask logits with a temperature before applying sigmoid
676
+ binarize = self.binarize_mask_from_pts_for_mem_enc and is_mask_from_pts
677
+ if binarize and not self.training:
678
+ mask_for_mem = (pred_masks_high_res > 0).float()
679
+ else:
680
+ # apply sigmoid on the raw mask logits to turn them into range (0, 1)
681
+ mask_for_mem = torch.sigmoid(pred_masks_high_res)
682
+ # apply scale and bias terms to the sigmoid probabilities
683
+ if self.sigmoid_scale_for_mem_enc != 1.0:
684
+ mask_for_mem = mask_for_mem * self.sigmoid_scale_for_mem_enc
685
+ if self.sigmoid_bias_for_mem_enc != 0.0:
686
+ mask_for_mem = mask_for_mem + self.sigmoid_bias_for_mem_enc
687
+ maskmem_out = self.memory_encoder(pix_feat, mask_for_mem, skip_mask_sigmoid=True) # sigmoid already applied
688
+ maskmem_features = maskmem_out["vision_features"]
689
+ maskmem_pos_enc = maskmem_out["vision_pos_enc"]
690
+ # add a no-object embedding to the spatial memory to indicate that the frame
691
+ # is predicted to be occluded (i.e. no object is appearing in the frame)
692
+ if self.no_obj_embed_spatial is not None:
693
+ is_obj_appearing = (object_score_logits > 0).float()
694
+ maskmem_features += (1 - is_obj_appearing[..., None, None]) * self.no_obj_embed_spatial[
695
+ ..., None, None
696
+ ].expand(*maskmem_features.shape)
697
+
698
+ return maskmem_features, maskmem_pos_enc
699
+
700
+ def _track_step(
701
+ self,
702
+ frame_idx,
703
+ is_init_cond_frame,
704
+ current_vision_feats,
705
+ current_vision_pos_embeds,
706
+ feat_sizes,
707
+ point_inputs,
708
+ mask_inputs,
709
+ output_dict,
710
+ num_frames,
711
+ track_in_reverse,
712
+ prev_sam_mask_logits,
713
+ ):
714
+ current_out = {"point_inputs": point_inputs, "mask_inputs": mask_inputs}
715
+ # High-resolution feature maps for the SAM head, reshape (HW)BC => BCHW
716
+ if len(current_vision_feats) > 1:
717
+ high_res_features = [
718
+ x.permute(1, 2, 0).view(x.size(1), x.size(2), *s)
719
+ for x, s in zip(current_vision_feats[:-1], feat_sizes[:-1])
720
+ ]
721
+ else:
722
+ high_res_features = None
723
+ if mask_inputs is not None and self.use_mask_input_as_output_without_sam:
724
+ # When use_mask_input_as_output_without_sam=True, we directly output the mask input
725
+ # (see it as a GT mask) without using a SAM prompt encoder + mask decoder.
726
+ pix_feat = current_vision_feats[-1].permute(1, 2, 0)
727
+ pix_feat = pix_feat.view(-1, self.hidden_dim, *feat_sizes[-1])
728
+ sam_outputs = self._use_mask_as_output(pix_feat, high_res_features, mask_inputs)
729
+ else:
730
+ # fused the visual feature with previous memory features in the memory bank
731
+ pix_feat = self._prepare_memory_conditioned_features(
732
+ frame_idx=frame_idx,
733
+ is_init_cond_frame=is_init_cond_frame,
734
+ current_vision_feats=current_vision_feats[-1:],
735
+ current_vision_pos_embeds=current_vision_pos_embeds[-1:],
736
+ feat_sizes=feat_sizes[-1:],
737
+ output_dict=output_dict,
738
+ num_frames=num_frames,
739
+ track_in_reverse=track_in_reverse,
740
+ )
741
+ # apply SAM-style segmentation head
742
+ # here we might feed previously predicted low-res SAM mask logits into the SAM mask decoder,
743
+ # e.g. in demo where such logits come from earlier interaction instead of correction sampling
744
+ # (in this case, any `mask_inputs` shouldn't reach here as they are sent to _use_mask_as_output instead)
745
+ if prev_sam_mask_logits is not None:
746
+ assert point_inputs is not None and mask_inputs is None
747
+ mask_inputs = prev_sam_mask_logits
748
+ multimask_output = self._use_multimask(is_init_cond_frame, point_inputs)
749
+ sam_outputs = self._forward_sam_heads(
750
+ backbone_features=pix_feat,
751
+ point_inputs=point_inputs,
752
+ mask_inputs=mask_inputs,
753
+ high_res_features=high_res_features,
754
+ multimask_output=multimask_output,
755
+ )
756
+
757
+ return current_out, sam_outputs, high_res_features, pix_feat
758
+
759
+ def _encode_memory_in_output(
760
+ self,
761
+ current_vision_feats,
762
+ feat_sizes,
763
+ point_inputs,
764
+ run_mem_encoder,
765
+ high_res_masks,
766
+ object_score_logits,
767
+ current_out,
768
+ ):
769
+ if run_mem_encoder and self.num_maskmem > 0:
770
+ high_res_masks_for_mem_enc = high_res_masks
771
+ maskmem_features, maskmem_pos_enc = self._encode_new_memory(
772
+ current_vision_feats=current_vision_feats,
773
+ feat_sizes=feat_sizes,
774
+ pred_masks_high_res=high_res_masks_for_mem_enc,
775
+ object_score_logits=object_score_logits,
776
+ is_mask_from_pts=(point_inputs is not None),
777
+ )
778
+ current_out["maskmem_features"] = maskmem_features
779
+ current_out["maskmem_pos_enc"] = maskmem_pos_enc
780
+ else:
781
+ current_out["maskmem_features"] = None
782
+ current_out["maskmem_pos_enc"] = None
783
+
784
+ def track_step(
785
+ self,
786
+ frame_idx,
787
+ is_init_cond_frame,
788
+ current_vision_feats,
789
+ current_vision_pos_embeds,
790
+ feat_sizes,
791
+ point_inputs,
792
+ mask_inputs,
793
+ output_dict,
794
+ num_frames,
795
+ track_in_reverse=False, # tracking in reverse time order (for demo usage)
796
+ # Whether to run the memory encoder on the predicted masks. Sometimes we might want
797
+ # to skip the memory encoder with `run_mem_encoder=False`. For example,
798
+ # in demo we might call `track_step` multiple times for each user click,
799
+ # and only encode the memory when the user finalizes their clicks. And in ablation
800
+ # settings like SAM training on static images, we don't need the memory encoder.
801
+ run_mem_encoder=True,
802
+ # The previously predicted SAM mask logits (which can be fed together with new clicks in demo).
803
+ prev_sam_mask_logits=None,
804
+ ):
805
+ current_out, sam_outputs, _, _ = self._track_step(
806
+ frame_idx,
807
+ is_init_cond_frame,
808
+ current_vision_feats,
809
+ current_vision_pos_embeds,
810
+ feat_sizes,
811
+ point_inputs,
812
+ mask_inputs,
813
+ output_dict,
814
+ num_frames,
815
+ track_in_reverse,
816
+ prev_sam_mask_logits,
817
+ )
818
+
819
+ (
820
+ _,
821
+ _,
822
+ _,
823
+ low_res_masks,
824
+ high_res_masks,
825
+ obj_ptr,
826
+ object_score_logits,
827
+ ) = sam_outputs
828
+
829
+ current_out["pred_masks"] = low_res_masks
830
+ current_out["pred_masks_high_res"] = high_res_masks
831
+ current_out["obj_ptr"] = obj_ptr
832
+ if not self.training:
833
+ # Only add this in inference (to avoid unused param in activation checkpointing;
834
+ # it's mainly used in the demo to encode spatial memories w/ consolidated masks)
835
+ current_out["object_score_logits"] = object_score_logits
836
+
837
+ # Finally run the memory encoder on the predicted mask to encode
838
+ # it into a new memory feature (that can be used in future frames)
839
+ self._encode_memory_in_output(
840
+ current_vision_feats,
841
+ feat_sizes,
842
+ point_inputs,
843
+ run_mem_encoder,
844
+ high_res_masks,
845
+ object_score_logits,
846
+ current_out,
847
+ )
848
+
849
+ return current_out
850
+
851
+ def _use_multimask(self, is_init_cond_frame, point_inputs):
852
+ """Whether to use multimask output in the SAM head."""
853
+ num_pts = 0 if point_inputs is None else point_inputs["point_labels"].size(1)
854
+ multimask_output = (
855
+ self.multimask_output_in_sam
856
+ and (is_init_cond_frame or self.multimask_output_for_tracking)
857
+ and (self.multimask_min_pt_num <= num_pts <= self.multimask_max_pt_num)
858
+ )
859
+ return multimask_output
860
+
861
+ def _apply_non_overlapping_constraints(self, pred_masks):
862
+ """
863
+ Apply non-overlapping constraints to the object scores in pred_masks. Here we
864
+ keep only the highest scoring object at each spatial location in pred_masks.
865
+ """
866
+ batch_size = pred_masks.size(0)
867
+ if batch_size == 1:
868
+ return pred_masks
869
+
870
+ device = pred_masks.device
871
+ # "max_obj_inds": object index of the object with the highest score at each location
872
+ max_obj_inds = torch.argmax(pred_masks, dim=0, keepdim=True)
873
+ # "batch_obj_inds": object index of each object slice (along dim 0) in `pred_masks`
874
+ batch_obj_inds = torch.arange(batch_size, device=device)[:, None, None, None]
875
+ keep = max_obj_inds == batch_obj_inds
876
+ # suppress overlapping regions' scores below -10.0 so that the foreground regions
877
+ # don't overlap (here sigmoid(-10.0)=4.5398e-05)
878
+ pred_masks = torch.where(keep, pred_masks, torch.clamp(pred_masks, max=-10.0))
879
+ return pred_masks