sam2_base.py 43 KB

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