sam2_base.py 46 KB

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