sam2_video_predictor.py 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222
  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 warnings
  6. from collections import OrderedDict
  7. import torch
  8. import torch.nn.functional as F
  9. from tqdm import tqdm
  10. from sam2.modeling.sam2_base import NO_OBJ_SCORE, SAM2Base
  11. from sam2.utils.misc import concat_points, fill_holes_in_mask_scores, load_video_frames
  12. class SAM2VideoPredictor(SAM2Base):
  13. """The predictor class to handle user interactions and manage inference states."""
  14. def __init__(
  15. self,
  16. fill_hole_area=0,
  17. # whether to apply non-overlapping constraints on the output object masks
  18. non_overlap_masks=False,
  19. # whether to clear non-conditioning memory of the surrounding frames (which may contain outdated information) after adding correction clicks;
  20. # note that this would only apply to *single-object tracking* unless `clear_non_cond_mem_for_multi_obj` is also set to True)
  21. clear_non_cond_mem_around_input=False,
  22. # 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
  23. # if `add_all_frames_to_correct_as_cond` is False, we conditioning frame list to only use those initial conditioning frames
  24. add_all_frames_to_correct_as_cond=False,
  25. **kwargs,
  26. ):
  27. super().__init__(**kwargs)
  28. self.fill_hole_area = fill_hole_area
  29. self.non_overlap_masks = non_overlap_masks
  30. self.clear_non_cond_mem_around_input = clear_non_cond_mem_around_input
  31. self.add_all_frames_to_correct_as_cond = add_all_frames_to_correct_as_cond
  32. @torch.inference_mode()
  33. def init_state(
  34. self,
  35. video_path,
  36. offload_video_to_cpu=False,
  37. offload_state_to_cpu=False,
  38. async_loading_frames=False,
  39. ):
  40. """Initialize an inference state."""
  41. compute_device = self.device # device of the model
  42. images, video_height, video_width = load_video_frames(
  43. video_path=video_path,
  44. image_size=self.image_size,
  45. offload_video_to_cpu=offload_video_to_cpu,
  46. async_loading_frames=async_loading_frames,
  47. compute_device=compute_device,
  48. )
  49. inference_state = {}
  50. inference_state["images"] = images
  51. inference_state["num_frames"] = len(images)
  52. # whether to offload the video frames to CPU memory
  53. # turning on this option saves the GPU memory with only a very small overhead
  54. inference_state["offload_video_to_cpu"] = offload_video_to_cpu
  55. # whether to offload the inference state to CPU memory
  56. # turning on this option saves the GPU memory at the cost of a lower tracking fps
  57. # (e.g. in a test case of 768x768 model, fps dropped from 27 to 24 when tracking one object
  58. # and from 24 to 21 when tracking two objects)
  59. inference_state["offload_state_to_cpu"] = offload_state_to_cpu
  60. # the original video height and width, used for resizing final output scores
  61. inference_state["video_height"] = video_height
  62. inference_state["video_width"] = video_width
  63. inference_state["device"] = compute_device
  64. if offload_state_to_cpu:
  65. inference_state["storage_device"] = torch.device("cpu")
  66. else:
  67. inference_state["storage_device"] = compute_device
  68. # inputs on each frame
  69. inference_state["point_inputs_per_obj"] = {}
  70. inference_state["mask_inputs_per_obj"] = {}
  71. # visual features on a small number of recently visited frames for quick interactions
  72. inference_state["cached_features"] = {}
  73. # values that don't change across frames (so we only need to hold one copy of them)
  74. inference_state["constants"] = {}
  75. # mapping between client-side object id and model-side object index
  76. inference_state["obj_id_to_idx"] = OrderedDict()
  77. inference_state["obj_idx_to_id"] = OrderedDict()
  78. inference_state["obj_ids"] = []
  79. # Slice (view) of each object tracking results, sharing the same memory with "output_dict"
  80. inference_state["output_dict_per_obj"] = {}
  81. # A temporary storage to hold new outputs when user interact with a frame
  82. # to add clicks or mask (it's merged into "output_dict" before propagation starts)
  83. inference_state["temp_output_dict_per_obj"] = {}
  84. # Frames that already holds consolidated outputs from click or mask inputs
  85. # (we directly use their consolidated outputs during tracking)
  86. # metadata for each tracking frame (e.g. which direction it's tracked)
  87. inference_state["frames_tracked_per_obj"] = {}
  88. # Warm up the visual backbone and cache the image feature on frame 0
  89. self._get_image_feature(inference_state, frame_idx=0, batch_size=1)
  90. return inference_state
  91. @classmethod
  92. def from_pretrained(cls, model_id: str, **kwargs) -> "SAM2VideoPredictor":
  93. """
  94. Load a pretrained model from the Hugging Face hub.
  95. Arguments:
  96. model_id (str): The Hugging Face repository ID.
  97. **kwargs: Additional arguments to pass to the model constructor.
  98. Returns:
  99. (SAM2VideoPredictor): The loaded model.
  100. """
  101. from sam2.build_sam import build_sam2_video_predictor_hf
  102. sam_model = build_sam2_video_predictor_hf(model_id, **kwargs)
  103. return sam_model
  104. def _obj_id_to_idx(self, inference_state, obj_id):
  105. """Map client-side object id to model-side object index."""
  106. obj_idx = inference_state["obj_id_to_idx"].get(obj_id, None)
  107. if obj_idx is not None:
  108. return obj_idx
  109. # We always allow adding new objects (including after tracking starts).
  110. allow_new_object = True
  111. if allow_new_object:
  112. # get the next object slot
  113. obj_idx = len(inference_state["obj_id_to_idx"])
  114. inference_state["obj_id_to_idx"][obj_id] = obj_idx
  115. inference_state["obj_idx_to_id"][obj_idx] = obj_id
  116. inference_state["obj_ids"] = list(inference_state["obj_id_to_idx"])
  117. # set up input and output structures for this object
  118. inference_state["point_inputs_per_obj"][obj_idx] = {}
  119. inference_state["mask_inputs_per_obj"][obj_idx] = {}
  120. inference_state["output_dict_per_obj"][obj_idx] = {
  121. "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
  122. "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
  123. }
  124. inference_state["temp_output_dict_per_obj"][obj_idx] = {
  125. "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
  126. "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
  127. }
  128. inference_state["frames_tracked_per_obj"][obj_idx] = {}
  129. return obj_idx
  130. else:
  131. raise RuntimeError(
  132. f"Cannot add new object id {obj_id} after tracking starts. "
  133. f"All existing object ids: {inference_state['obj_ids']}. "
  134. f"Please call 'reset_state' to restart from scratch."
  135. )
  136. def _obj_idx_to_id(self, inference_state, obj_idx):
  137. """Map model-side object index to client-side object id."""
  138. return inference_state["obj_idx_to_id"][obj_idx]
  139. def _get_obj_num(self, inference_state):
  140. """Get the total number of unique object ids received so far in this session."""
  141. return len(inference_state["obj_idx_to_id"])
  142. @torch.inference_mode()
  143. def add_new_points_or_box(
  144. self,
  145. inference_state,
  146. frame_idx,
  147. obj_id,
  148. points=None,
  149. labels=None,
  150. clear_old_points=True,
  151. normalize_coords=True,
  152. box=None,
  153. ):
  154. """Add new points to a frame."""
  155. obj_idx = self._obj_id_to_idx(inference_state, obj_id)
  156. point_inputs_per_frame = inference_state["point_inputs_per_obj"][obj_idx]
  157. mask_inputs_per_frame = inference_state["mask_inputs_per_obj"][obj_idx]
  158. if (points is not None) != (labels is not None):
  159. raise ValueError("points and labels must be provided together")
  160. if points is None and box is None:
  161. raise ValueError("at least one of points or box must be provided as input")
  162. if points is None:
  163. points = torch.zeros(0, 2, dtype=torch.float32)
  164. elif not isinstance(points, torch.Tensor):
  165. points = torch.tensor(points, dtype=torch.float32)
  166. if labels is None:
  167. labels = torch.zeros(0, dtype=torch.int32)
  168. elif not isinstance(labels, torch.Tensor):
  169. labels = torch.tensor(labels, dtype=torch.int32)
  170. if points.dim() == 2:
  171. points = points.unsqueeze(0) # add batch dimension
  172. if labels.dim() == 1:
  173. labels = labels.unsqueeze(0) # add batch dimension
  174. # If `box` is provided, we add it as the first two points with labels 2 and 3
  175. # along with the user-provided points (consistent with how SAM 2 is trained).
  176. if box is not None:
  177. if not clear_old_points:
  178. raise ValueError(
  179. "cannot add box without clearing old points, since "
  180. "box prompt must be provided before any point prompt "
  181. "(please use clear_old_points=True instead)"
  182. )
  183. if not isinstance(box, torch.Tensor):
  184. box = torch.tensor(box, dtype=torch.float32, device=points.device)
  185. box_coords = box.reshape(1, 2, 2)
  186. box_labels = torch.tensor([2, 3], dtype=torch.int32, device=labels.device)
  187. box_labels = box_labels.reshape(1, 2)
  188. points = torch.cat([box_coords, points], dim=1)
  189. labels = torch.cat([box_labels, labels], dim=1)
  190. if normalize_coords:
  191. video_H = inference_state["video_height"]
  192. video_W = inference_state["video_width"]
  193. points = points / torch.tensor([video_W, video_H]).to(points.device)
  194. # scale the (normalized) coordinates by the model's internal image size
  195. points = points * self.image_size
  196. points = points.to(inference_state["device"])
  197. labels = labels.to(inference_state["device"])
  198. if not clear_old_points:
  199. point_inputs = point_inputs_per_frame.get(frame_idx, None)
  200. else:
  201. point_inputs = None
  202. point_inputs = concat_points(point_inputs, points, labels)
  203. point_inputs_per_frame[frame_idx] = point_inputs
  204. mask_inputs_per_frame.pop(frame_idx, None)
  205. # If this frame hasn't been tracked before, we treat it as an initial conditioning
  206. # frame, meaning that the inputs points are to generate segments on this frame without
  207. # using any memory from other frames, like in SAM. Otherwise (if it has been tracked),
  208. # the input points will be used to correct the already tracked masks.
  209. obj_frames_tracked = inference_state["frames_tracked_per_obj"][obj_idx]
  210. is_init_cond_frame = frame_idx not in obj_frames_tracked
  211. # whether to track in reverse time order
  212. if is_init_cond_frame:
  213. reverse = False
  214. else:
  215. reverse = obj_frames_tracked[frame_idx]["reverse"]
  216. obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
  217. obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
  218. # Add a frame to conditioning output if it's an initial conditioning frame or
  219. # if the model sees all frames receiving clicks/mask as conditioning frames.
  220. is_cond = is_init_cond_frame or self.add_all_frames_to_correct_as_cond
  221. storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
  222. # Get any previously predicted mask logits on this object and feed it along with
  223. # the new clicks into the SAM mask decoder.
  224. prev_sam_mask_logits = None
  225. # lookup temporary output dict first, which contains the most recent output
  226. # (if not found, then lookup conditioning and non-conditioning frame output)
  227. prev_out = obj_temp_output_dict[storage_key].get(frame_idx)
  228. if prev_out is None:
  229. prev_out = obj_output_dict["cond_frame_outputs"].get(frame_idx)
  230. if prev_out is None:
  231. prev_out = obj_output_dict["non_cond_frame_outputs"].get(frame_idx)
  232. if prev_out is not None and prev_out["pred_masks"] is not None:
  233. device = inference_state["device"]
  234. prev_sam_mask_logits = prev_out["pred_masks"].to(device, non_blocking=True)
  235. # Clamp the scale of prev_sam_mask_logits to avoid rare numerical issues.
  236. prev_sam_mask_logits = torch.clamp(prev_sam_mask_logits, -32.0, 32.0)
  237. current_out, _ = self._run_single_frame_inference(
  238. inference_state=inference_state,
  239. output_dict=obj_output_dict, # run on the slice of a single object
  240. frame_idx=frame_idx,
  241. batch_size=1, # run on the slice of a single object
  242. is_init_cond_frame=is_init_cond_frame,
  243. point_inputs=point_inputs,
  244. mask_inputs=None,
  245. reverse=reverse,
  246. # Skip the memory encoder when adding clicks or mask. We execute the memory encoder
  247. # at the beginning of `propagate_in_video` (after user finalize their clicks). This
  248. # allows us to enforce non-overlapping constraints on all objects before encoding
  249. # them into memory.
  250. run_mem_encoder=False,
  251. prev_sam_mask_logits=prev_sam_mask_logits,
  252. )
  253. # Add the output to the output dict (to be used as future memory)
  254. obj_temp_output_dict[storage_key][frame_idx] = current_out
  255. # Resize the output mask to the original video resolution
  256. obj_ids = inference_state["obj_ids"]
  257. consolidated_out = self._consolidate_temp_output_across_obj(
  258. inference_state,
  259. frame_idx,
  260. is_cond=is_cond,
  261. consolidate_at_video_res=True,
  262. )
  263. _, video_res_masks = self._get_orig_video_res_output(
  264. inference_state, consolidated_out["pred_masks_video_res"]
  265. )
  266. return frame_idx, obj_ids, video_res_masks
  267. def add_new_points(self, *args, **kwargs):
  268. """Deprecated method. Please use `add_new_points_or_box` instead."""
  269. return self.add_new_points_or_box(*args, **kwargs)
  270. @torch.inference_mode()
  271. def add_new_mask(
  272. self,
  273. inference_state,
  274. frame_idx,
  275. obj_id,
  276. mask,
  277. ):
  278. """Add new mask to a frame."""
  279. obj_idx = self._obj_id_to_idx(inference_state, obj_id)
  280. point_inputs_per_frame = inference_state["point_inputs_per_obj"][obj_idx]
  281. mask_inputs_per_frame = inference_state["mask_inputs_per_obj"][obj_idx]
  282. if not isinstance(mask, torch.Tensor):
  283. mask = torch.tensor(mask, dtype=torch.bool)
  284. assert mask.dim() == 2
  285. mask_H, mask_W = mask.shape
  286. mask_inputs_orig = mask[None, None] # add batch and channel dimension
  287. mask_inputs_orig = mask_inputs_orig.float().to(inference_state["device"])
  288. # resize the mask if it doesn't match the model's image size
  289. if mask_H != self.image_size or mask_W != self.image_size:
  290. mask_inputs = torch.nn.functional.interpolate(
  291. mask_inputs_orig,
  292. size=(self.image_size, self.image_size),
  293. align_corners=False,
  294. mode="bilinear",
  295. antialias=True, # use antialias for downsampling
  296. )
  297. mask_inputs = (mask_inputs >= 0.5).float()
  298. else:
  299. mask_inputs = mask_inputs_orig
  300. mask_inputs_per_frame[frame_idx] = mask_inputs
  301. point_inputs_per_frame.pop(frame_idx, None)
  302. # If this frame hasn't been tracked before, we treat it as an initial conditioning
  303. # frame, meaning that the inputs points are to generate segments on this frame without
  304. # using any memory from other frames, like in SAM. Otherwise (if it has been tracked),
  305. # the input points will be used to correct the already tracked masks.
  306. obj_frames_tracked = inference_state["frames_tracked_per_obj"][obj_idx]
  307. is_init_cond_frame = frame_idx not in obj_frames_tracked
  308. # whether to track in reverse time order
  309. if is_init_cond_frame:
  310. reverse = False
  311. else:
  312. reverse = obj_frames_tracked[frame_idx]["reverse"]
  313. obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
  314. obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
  315. # Add a frame to conditioning output if it's an initial conditioning frame or
  316. # if the model sees all frames receiving clicks/mask as conditioning frames.
  317. is_cond = is_init_cond_frame or self.add_all_frames_to_correct_as_cond
  318. storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
  319. current_out, _ = self._run_single_frame_inference(
  320. inference_state=inference_state,
  321. output_dict=obj_output_dict, # run on the slice of a single object
  322. frame_idx=frame_idx,
  323. batch_size=1, # run on the slice of a single object
  324. is_init_cond_frame=is_init_cond_frame,
  325. point_inputs=None,
  326. mask_inputs=mask_inputs,
  327. reverse=reverse,
  328. # Skip the memory encoder when adding clicks or mask. We execute the memory encoder
  329. # at the beginning of `propagate_in_video` (after user finalize their clicks). This
  330. # allows us to enforce non-overlapping constraints on all objects before encoding
  331. # them into memory.
  332. run_mem_encoder=False,
  333. )
  334. # Add the output to the output dict (to be used as future memory)
  335. obj_temp_output_dict[storage_key][frame_idx] = current_out
  336. # Resize the output mask to the original video resolution
  337. obj_ids = inference_state["obj_ids"]
  338. consolidated_out = self._consolidate_temp_output_across_obj(
  339. inference_state,
  340. frame_idx,
  341. is_cond=is_cond,
  342. consolidate_at_video_res=True,
  343. )
  344. _, video_res_masks = self._get_orig_video_res_output(
  345. inference_state, consolidated_out["pred_masks_video_res"]
  346. )
  347. return frame_idx, obj_ids, video_res_masks
  348. def _get_orig_video_res_output(self, inference_state, any_res_masks):
  349. """
  350. Resize the object scores to the original video resolution (video_res_masks)
  351. and apply non-overlapping constraints for final output.
  352. """
  353. device = inference_state["device"]
  354. video_H = inference_state["video_height"]
  355. video_W = inference_state["video_width"]
  356. any_res_masks = any_res_masks.to(device, non_blocking=True)
  357. if any_res_masks.shape[-2:] == (video_H, video_W):
  358. video_res_masks = any_res_masks
  359. else:
  360. video_res_masks = torch.nn.functional.interpolate(
  361. any_res_masks,
  362. size=(video_H, video_W),
  363. mode="bilinear",
  364. align_corners=False,
  365. )
  366. if self.non_overlap_masks:
  367. video_res_masks = self._apply_non_overlapping_constraints(video_res_masks)
  368. return any_res_masks, video_res_masks
  369. def _consolidate_temp_output_across_obj(
  370. self,
  371. inference_state,
  372. frame_idx,
  373. is_cond,
  374. consolidate_at_video_res=False,
  375. ):
  376. """
  377. Consolidate the per-object temporary outputs in `temp_output_dict_per_obj` on
  378. a frame into a single output for all objects, including
  379. 1) fill any missing objects either from `output_dict_per_obj` (if they exist in
  380. `output_dict_per_obj` for this frame) or leave them as placeholder values
  381. (if they don't exist in `output_dict_per_obj` for this frame);
  382. 2) if specified, rerun memory encoder after apply non-overlapping constraints
  383. on the object scores.
  384. """
  385. batch_size = self._get_obj_num(inference_state)
  386. storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
  387. # Optionally, we allow consolidating the temporary outputs at the original
  388. # video resolution (to provide a better editing experience for mask prompts).
  389. if consolidate_at_video_res:
  390. consolidated_H = inference_state["video_height"]
  391. consolidated_W = inference_state["video_width"]
  392. consolidated_mask_key = "pred_masks_video_res"
  393. else:
  394. consolidated_H = consolidated_W = self.image_size // 4
  395. consolidated_mask_key = "pred_masks"
  396. # Initialize `consolidated_out`. Its "maskmem_features" and "maskmem_pos_enc"
  397. # will be added when rerunning the memory encoder after applying non-overlapping
  398. # constraints to object scores. Its "pred_masks" are prefilled with a large
  399. # negative value (NO_OBJ_SCORE) to represent missing objects.
  400. consolidated_out = {
  401. consolidated_mask_key: torch.full(
  402. size=(batch_size, 1, consolidated_H, consolidated_W),
  403. fill_value=NO_OBJ_SCORE,
  404. dtype=torch.float32,
  405. device=inference_state["storage_device"],
  406. ),
  407. }
  408. for obj_idx in range(batch_size):
  409. obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
  410. obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
  411. out = obj_temp_output_dict[storage_key].get(frame_idx, None)
  412. # If the object doesn't appear in "temp_output_dict_per_obj" on this frame,
  413. # we fall back and look up its previous output in "output_dict_per_obj".
  414. # We look up both "cond_frame_outputs" and "non_cond_frame_outputs" in
  415. # "output_dict_per_obj" to find a previous output for this object.
  416. if out is None:
  417. out = obj_output_dict["cond_frame_outputs"].get(frame_idx, None)
  418. if out is None:
  419. out = obj_output_dict["non_cond_frame_outputs"].get(frame_idx, None)
  420. # If the object doesn't appear in "output_dict_per_obj" either, we skip it
  421. # and leave its mask scores to the default scores (i.e. the NO_OBJ_SCORE
  422. # placeholder above) and set its object pointer to be a dummy pointer.
  423. if out is None:
  424. continue
  425. # Add the temporary object output mask to consolidated output mask
  426. obj_mask = out["pred_masks"]
  427. consolidated_pred_masks = consolidated_out[consolidated_mask_key]
  428. if obj_mask.shape[-2:] == consolidated_pred_masks.shape[-2:]:
  429. consolidated_pred_masks[obj_idx : obj_idx + 1] = obj_mask
  430. else:
  431. # Resize first if temporary object mask has a different resolution
  432. resized_obj_mask = torch.nn.functional.interpolate(
  433. obj_mask,
  434. size=consolidated_pred_masks.shape[-2:],
  435. mode="bilinear",
  436. align_corners=False,
  437. )
  438. consolidated_pred_masks[obj_idx : obj_idx + 1] = resized_obj_mask
  439. return consolidated_out
  440. @torch.inference_mode()
  441. def propagate_in_video_preflight(self, inference_state):
  442. """Prepare inference_state and consolidate temporary outputs before tracking."""
  443. # Check and make sure that every object has received input points or masks.
  444. batch_size = self._get_obj_num(inference_state)
  445. if batch_size == 0:
  446. raise RuntimeError(
  447. "No input points or masks are provided for any object; please add inputs first."
  448. )
  449. # Consolidate per-object temporary outputs in "temp_output_dict_per_obj" and
  450. # add them into "output_dict".
  451. for obj_idx in range(batch_size):
  452. obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
  453. obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
  454. for is_cond in [False, True]:
  455. # Separately consolidate conditioning and non-conditioning temp outputs
  456. storage_key = (
  457. "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
  458. )
  459. # Find all the frames that contain temporary outputs for any objects
  460. # (these should be the frames that have just received clicks for mask inputs
  461. # via `add_new_points_or_box` or `add_new_mask`)
  462. for frame_idx, out in obj_temp_output_dict[storage_key].items():
  463. # Run memory encoder on the temporary outputs (if the memory feature is missing)
  464. if out["maskmem_features"] is None:
  465. high_res_masks = torch.nn.functional.interpolate(
  466. out["pred_masks"].to(inference_state["device"]),
  467. size=(self.image_size, self.image_size),
  468. mode="bilinear",
  469. align_corners=False,
  470. )
  471. maskmem_features, maskmem_pos_enc = self._run_memory_encoder(
  472. inference_state=inference_state,
  473. frame_idx=frame_idx,
  474. batch_size=1, # run on the slice of a single object
  475. high_res_masks=high_res_masks,
  476. object_score_logits=out["object_score_logits"],
  477. # these frames are what the user interacted with
  478. is_mask_from_pts=True,
  479. )
  480. out["maskmem_features"] = maskmem_features
  481. out["maskmem_pos_enc"] = maskmem_pos_enc
  482. obj_output_dict[storage_key][frame_idx] = out
  483. if self.clear_non_cond_mem_around_input:
  484. # clear non-conditioning memory of the surrounding frames
  485. self._clear_obj_non_cond_mem_around_input(
  486. inference_state, frame_idx, obj_idx
  487. )
  488. # clear temporary outputs in `temp_output_dict_per_obj`
  489. obj_temp_output_dict[storage_key].clear()
  490. # check and make sure that every object has received input points or masks
  491. obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
  492. if len(obj_output_dict["cond_frame_outputs"]) == 0:
  493. obj_id = self._obj_idx_to_id(inference_state, obj_idx)
  494. raise RuntimeError(
  495. f"No input points or masks are provided for object id {obj_id}; please add inputs first."
  496. )
  497. # edge case: if an output is added to "cond_frame_outputs", we remove any prior
  498. # output on the same frame in "non_cond_frame_outputs"
  499. for frame_idx in obj_output_dict["cond_frame_outputs"]:
  500. obj_output_dict["non_cond_frame_outputs"].pop(frame_idx, None)
  501. @torch.inference_mode()
  502. def propagate_in_video(
  503. self,
  504. inference_state,
  505. start_frame_idx=None,
  506. max_frame_num_to_track=None,
  507. reverse=False,
  508. ):
  509. """Propagate the input points across frames to track in the entire video."""
  510. self.propagate_in_video_preflight(inference_state)
  511. obj_ids = inference_state["obj_ids"]
  512. num_frames = inference_state["num_frames"]
  513. batch_size = self._get_obj_num(inference_state)
  514. # set start index, end index, and processing order
  515. if start_frame_idx is None:
  516. # default: start from the earliest frame with input points
  517. start_frame_idx = min(
  518. t
  519. for obj_output_dict in inference_state["output_dict_per_obj"].values()
  520. for t in obj_output_dict["cond_frame_outputs"]
  521. )
  522. if max_frame_num_to_track is None:
  523. # default: track all the frames in the video
  524. max_frame_num_to_track = num_frames
  525. if reverse:
  526. end_frame_idx = max(start_frame_idx - max_frame_num_to_track, 0)
  527. if start_frame_idx > 0:
  528. processing_order = range(start_frame_idx, end_frame_idx - 1, -1)
  529. else:
  530. processing_order = [] # skip reverse tracking if starting from frame 0
  531. else:
  532. end_frame_idx = min(
  533. start_frame_idx + max_frame_num_to_track, num_frames - 1
  534. )
  535. processing_order = range(start_frame_idx, end_frame_idx + 1)
  536. for frame_idx in tqdm(processing_order, desc="propagate in video"):
  537. pred_masks_per_obj = [None] * batch_size
  538. for obj_idx in range(batch_size):
  539. obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
  540. # We skip those frames already in consolidated outputs (these are frames
  541. # that received input clicks or mask). Note that we cannot directly run
  542. # batched forward on them via `_run_single_frame_inference` because the
  543. # number of clicks on each object might be different.
  544. if frame_idx in obj_output_dict["cond_frame_outputs"]:
  545. storage_key = "cond_frame_outputs"
  546. current_out = obj_output_dict[storage_key][frame_idx]
  547. pred_masks = current_out["pred_masks"]
  548. if self.clear_non_cond_mem_around_input:
  549. # clear non-conditioning memory of the surrounding frames
  550. self._clear_obj_non_cond_mem_around_input(
  551. inference_state, frame_idx, obj_idx
  552. )
  553. else:
  554. storage_key = "non_cond_frame_outputs"
  555. current_out, pred_masks = self._run_single_frame_inference(
  556. inference_state=inference_state,
  557. output_dict=obj_output_dict,
  558. frame_idx=frame_idx,
  559. batch_size=1, # run on the slice of a single object
  560. is_init_cond_frame=False,
  561. point_inputs=None,
  562. mask_inputs=None,
  563. reverse=reverse,
  564. run_mem_encoder=True,
  565. )
  566. obj_output_dict[storage_key][frame_idx] = current_out
  567. inference_state["frames_tracked_per_obj"][obj_idx][frame_idx] = {
  568. "reverse": reverse
  569. }
  570. pred_masks_per_obj[obj_idx] = pred_masks
  571. # Resize the output mask to the original video resolution (we directly use
  572. # the mask scores on GPU for output to avoid any CPU conversion in between)
  573. if len(pred_masks_per_obj) > 1:
  574. all_pred_masks = torch.cat(pred_masks_per_obj, dim=0)
  575. else:
  576. all_pred_masks = pred_masks_per_obj[0]
  577. _, video_res_masks = self._get_orig_video_res_output(
  578. inference_state, all_pred_masks
  579. )
  580. yield frame_idx, obj_ids, video_res_masks
  581. @torch.inference_mode()
  582. def clear_all_prompts_in_frame(
  583. self, inference_state, frame_idx, obj_id, need_output=True
  584. ):
  585. """Remove all input points or mask in a specific frame for a given object."""
  586. obj_idx = self._obj_id_to_idx(inference_state, obj_id)
  587. # Clear the conditioning information on the given frame
  588. inference_state["point_inputs_per_obj"][obj_idx].pop(frame_idx, None)
  589. inference_state["mask_inputs_per_obj"][obj_idx].pop(frame_idx, None)
  590. temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"]
  591. temp_output_dict_per_obj[obj_idx]["cond_frame_outputs"].pop(frame_idx, None)
  592. temp_output_dict_per_obj[obj_idx]["non_cond_frame_outputs"].pop(frame_idx, None)
  593. # Remove the frame's conditioning output (possibly downgrading it to non-conditioning)
  594. obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
  595. out = obj_output_dict["cond_frame_outputs"].pop(frame_idx, None)
  596. if out is not None:
  597. # The frame is not a conditioning frame anymore since it's not receiving inputs,
  598. # so we "downgrade" its output (if exists) to a non-conditioning frame output.
  599. obj_output_dict["non_cond_frame_outputs"][frame_idx] = out
  600. inference_state["frames_tracked_per_obj"][obj_idx].pop(frame_idx, None)
  601. if not need_output:
  602. return
  603. # Finally, output updated masks per object (after removing the inputs above)
  604. obj_ids = inference_state["obj_ids"]
  605. is_cond = any(
  606. frame_idx in obj_temp_output_dict["cond_frame_outputs"]
  607. for obj_temp_output_dict in temp_output_dict_per_obj.values()
  608. )
  609. consolidated_out = self._consolidate_temp_output_across_obj(
  610. inference_state,
  611. frame_idx,
  612. is_cond=is_cond,
  613. consolidate_at_video_res=True,
  614. )
  615. _, video_res_masks = self._get_orig_video_res_output(
  616. inference_state, consolidated_out["pred_masks_video_res"]
  617. )
  618. return frame_idx, obj_ids, video_res_masks
  619. @torch.inference_mode()
  620. def reset_state(self, inference_state):
  621. """Remove all input points or mask in all frames throughout the video."""
  622. self._reset_tracking_results(inference_state)
  623. # Remove all object ids
  624. inference_state["obj_id_to_idx"].clear()
  625. inference_state["obj_idx_to_id"].clear()
  626. inference_state["obj_ids"].clear()
  627. inference_state["point_inputs_per_obj"].clear()
  628. inference_state["mask_inputs_per_obj"].clear()
  629. inference_state["output_dict_per_obj"].clear()
  630. inference_state["temp_output_dict_per_obj"].clear()
  631. inference_state["frames_tracked_per_obj"].clear()
  632. def _reset_tracking_results(self, inference_state):
  633. """Reset all tracking inputs and results across the videos."""
  634. for v in inference_state["point_inputs_per_obj"].values():
  635. v.clear()
  636. for v in inference_state["mask_inputs_per_obj"].values():
  637. v.clear()
  638. for v in inference_state["output_dict_per_obj"].values():
  639. v["cond_frame_outputs"].clear()
  640. v["non_cond_frame_outputs"].clear()
  641. for v in inference_state["temp_output_dict_per_obj"].values():
  642. v["cond_frame_outputs"].clear()
  643. v["non_cond_frame_outputs"].clear()
  644. for v in inference_state["frames_tracked_per_obj"].values():
  645. v.clear()
  646. def _get_image_feature(self, inference_state, frame_idx, batch_size):
  647. """Compute the image features on a given frame."""
  648. # Look up in the cache first
  649. image, backbone_out = inference_state["cached_features"].get(
  650. frame_idx, (None, None)
  651. )
  652. if backbone_out is None:
  653. # Cache miss -- we will run inference on a single image
  654. device = inference_state["device"]
  655. image = inference_state["images"][frame_idx].to(device).float().unsqueeze(0)
  656. backbone_out = self.forward_image(image)
  657. # Cache the most recent frame's feature (for repeated interactions with
  658. # a frame; we can use an LRU cache for more frames in the future).
  659. inference_state["cached_features"] = {frame_idx: (image, backbone_out)}
  660. # expand the features to have the same dimension as the number of objects
  661. expanded_image = image.expand(batch_size, -1, -1, -1)
  662. expanded_backbone_out = {
  663. "backbone_fpn": backbone_out["backbone_fpn"].copy(),
  664. "vision_pos_enc": backbone_out["vision_pos_enc"].copy(),
  665. }
  666. for i, feat in enumerate(expanded_backbone_out["backbone_fpn"]):
  667. expanded_backbone_out["backbone_fpn"][i] = feat.expand(
  668. batch_size, -1, -1, -1
  669. )
  670. for i, pos in enumerate(expanded_backbone_out["vision_pos_enc"]):
  671. pos = pos.expand(batch_size, -1, -1, -1)
  672. expanded_backbone_out["vision_pos_enc"][i] = pos
  673. features = self._prepare_backbone_features(expanded_backbone_out)
  674. features = (expanded_image,) + features
  675. return features
  676. def _run_single_frame_inference(
  677. self,
  678. inference_state,
  679. output_dict,
  680. frame_idx,
  681. batch_size,
  682. is_init_cond_frame,
  683. point_inputs,
  684. mask_inputs,
  685. reverse,
  686. run_mem_encoder,
  687. prev_sam_mask_logits=None,
  688. ):
  689. """Run tracking on a single frame based on current inputs and previous memory."""
  690. # Retrieve correct image features
  691. (
  692. _,
  693. _,
  694. current_vision_feats,
  695. current_vision_pos_embeds,
  696. feat_sizes,
  697. ) = self._get_image_feature(inference_state, frame_idx, batch_size)
  698. # point and mask should not appear as input simultaneously on the same frame
  699. assert point_inputs is None or mask_inputs is None
  700. current_out = self.track_step(
  701. frame_idx=frame_idx,
  702. is_init_cond_frame=is_init_cond_frame,
  703. current_vision_feats=current_vision_feats,
  704. current_vision_pos_embeds=current_vision_pos_embeds,
  705. feat_sizes=feat_sizes,
  706. point_inputs=point_inputs,
  707. mask_inputs=mask_inputs,
  708. output_dict=output_dict,
  709. num_frames=inference_state["num_frames"],
  710. track_in_reverse=reverse,
  711. run_mem_encoder=run_mem_encoder,
  712. prev_sam_mask_logits=prev_sam_mask_logits,
  713. )
  714. # optionally offload the output to CPU memory to save GPU space
  715. storage_device = inference_state["storage_device"]
  716. maskmem_features = current_out["maskmem_features"]
  717. if maskmem_features is not None:
  718. maskmem_features = maskmem_features.to(torch.bfloat16)
  719. maskmem_features = maskmem_features.to(storage_device, non_blocking=True)
  720. pred_masks_gpu = current_out["pred_masks"]
  721. # potentially fill holes in the predicted masks
  722. if self.fill_hole_area > 0:
  723. pred_masks_gpu = fill_holes_in_mask_scores(
  724. pred_masks_gpu, self.fill_hole_area
  725. )
  726. pred_masks = pred_masks_gpu.to(storage_device, non_blocking=True)
  727. # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
  728. maskmem_pos_enc = self._get_maskmem_pos_enc(inference_state, current_out)
  729. # object pointer is a small tensor, so we always keep it on GPU memory for fast access
  730. obj_ptr = current_out["obj_ptr"]
  731. object_score_logits = current_out["object_score_logits"]
  732. # make a compact version of this frame's output to reduce the state size
  733. compact_current_out = {
  734. "maskmem_features": maskmem_features,
  735. "maskmem_pos_enc": maskmem_pos_enc,
  736. "pred_masks": pred_masks,
  737. "obj_ptr": obj_ptr,
  738. "object_score_logits": object_score_logits,
  739. }
  740. return compact_current_out, pred_masks_gpu
  741. def _run_memory_encoder(
  742. self,
  743. inference_state,
  744. frame_idx,
  745. batch_size,
  746. high_res_masks,
  747. object_score_logits,
  748. is_mask_from_pts,
  749. ):
  750. """
  751. Run the memory encoder on `high_res_masks`. This is usually after applying
  752. non-overlapping constraints to object scores. Since their scores changed, their
  753. memory also need to be computed again with the memory encoder.
  754. """
  755. # Retrieve correct image features
  756. _, _, current_vision_feats, _, feat_sizes = self._get_image_feature(
  757. inference_state, frame_idx, batch_size
  758. )
  759. maskmem_features, maskmem_pos_enc = self._encode_new_memory(
  760. current_vision_feats=current_vision_feats,
  761. feat_sizes=feat_sizes,
  762. pred_masks_high_res=high_res_masks,
  763. object_score_logits=object_score_logits,
  764. is_mask_from_pts=is_mask_from_pts,
  765. )
  766. # optionally offload the output to CPU memory to save GPU space
  767. storage_device = inference_state["storage_device"]
  768. maskmem_features = maskmem_features.to(torch.bfloat16)
  769. maskmem_features = maskmem_features.to(storage_device, non_blocking=True)
  770. # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
  771. maskmem_pos_enc = self._get_maskmem_pos_enc(
  772. inference_state, {"maskmem_pos_enc": maskmem_pos_enc}
  773. )
  774. return maskmem_features, maskmem_pos_enc
  775. def _get_maskmem_pos_enc(self, inference_state, current_out):
  776. """
  777. `maskmem_pos_enc` is the same across frames and objects, so we cache it as
  778. a constant in the inference session to reduce session storage size.
  779. """
  780. model_constants = inference_state["constants"]
  781. # "out_maskmem_pos_enc" should be either a list of tensors or None
  782. out_maskmem_pos_enc = current_out["maskmem_pos_enc"]
  783. if out_maskmem_pos_enc is not None:
  784. if "maskmem_pos_enc" not in model_constants:
  785. assert isinstance(out_maskmem_pos_enc, list)
  786. # only take the slice for one object, since it's same across objects
  787. maskmem_pos_enc = [x[0:1].clone() for x in out_maskmem_pos_enc]
  788. model_constants["maskmem_pos_enc"] = maskmem_pos_enc
  789. else:
  790. maskmem_pos_enc = model_constants["maskmem_pos_enc"]
  791. # expand the cached maskmem_pos_enc to the actual batch size
  792. batch_size = out_maskmem_pos_enc[0].size(0)
  793. expanded_maskmem_pos_enc = [
  794. x.expand(batch_size, -1, -1, -1) for x in maskmem_pos_enc
  795. ]
  796. else:
  797. expanded_maskmem_pos_enc = None
  798. return expanded_maskmem_pos_enc
  799. @torch.inference_mode()
  800. def remove_object(self, inference_state, obj_id, strict=False, need_output=True):
  801. """
  802. Remove an object id from the tracking state. If strict is True, we check whether
  803. the object id actually exists and raise an error if it doesn't exist.
  804. """
  805. old_obj_idx_to_rm = inference_state["obj_id_to_idx"].get(obj_id, None)
  806. updated_frames = []
  807. # Check whether this object_id to remove actually exists and possibly raise an error.
  808. if old_obj_idx_to_rm is None:
  809. if not strict:
  810. return inference_state["obj_ids"], updated_frames
  811. raise RuntimeError(
  812. f"Cannot remove object id {obj_id} as it doesn't exist. "
  813. f"All existing object ids: {inference_state['obj_ids']}."
  814. )
  815. # If this is the only remaining object id, we simply reset the state.
  816. if len(inference_state["obj_id_to_idx"]) == 1:
  817. self.reset_state(inference_state)
  818. return inference_state["obj_ids"], updated_frames
  819. # There are still remaining objects after removing this object id. In this case,
  820. # we need to delete the object storage from inference state tensors.
  821. # Step 0: clear the input on those frames where this object id has point or mask input
  822. # (note that this step is required as it might downgrade conditioning frames to
  823. # non-conditioning ones)
  824. obj_input_frames_inds = set()
  825. obj_input_frames_inds.update(
  826. inference_state["point_inputs_per_obj"][old_obj_idx_to_rm]
  827. )
  828. obj_input_frames_inds.update(
  829. inference_state["mask_inputs_per_obj"][old_obj_idx_to_rm]
  830. )
  831. for frame_idx in obj_input_frames_inds:
  832. self.clear_all_prompts_in_frame(
  833. inference_state, frame_idx, obj_id, need_output=False
  834. )
  835. # Step 1: Update the object id mapping (note that it must be done after Step 0,
  836. # since Step 0 still requires the old object id mappings in inference_state)
  837. old_obj_ids = inference_state["obj_ids"]
  838. old_obj_inds = list(range(len(old_obj_ids)))
  839. remain_old_obj_inds = old_obj_inds.copy()
  840. remain_old_obj_inds.remove(old_obj_idx_to_rm)
  841. new_obj_ids = [old_obj_ids[old_idx] for old_idx in remain_old_obj_inds]
  842. new_obj_inds = list(range(len(new_obj_ids)))
  843. # build new mappings
  844. old_idx_to_new_idx = dict(zip(remain_old_obj_inds, new_obj_inds))
  845. inference_state["obj_id_to_idx"] = dict(zip(new_obj_ids, new_obj_inds))
  846. inference_state["obj_idx_to_id"] = dict(zip(new_obj_inds, new_obj_ids))
  847. inference_state["obj_ids"] = new_obj_ids
  848. # Step 2: For per-object tensor storage, we shift their obj_idx in the dict keys.
  849. def _map_keys(container):
  850. new_kvs = []
  851. for k in old_obj_inds:
  852. v = container.pop(k)
  853. if k in old_idx_to_new_idx:
  854. new_kvs.append((old_idx_to_new_idx[k], v))
  855. container.update(new_kvs)
  856. _map_keys(inference_state["point_inputs_per_obj"])
  857. _map_keys(inference_state["mask_inputs_per_obj"])
  858. _map_keys(inference_state["output_dict_per_obj"])
  859. _map_keys(inference_state["temp_output_dict_per_obj"])
  860. _map_keys(inference_state["frames_tracked_per_obj"])
  861. # Step 3: Further collect the outputs on those frames in `obj_input_frames_inds`, which
  862. # could show an updated mask for objects previously occluded by the object being removed
  863. if need_output:
  864. temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"]
  865. for frame_idx in obj_input_frames_inds:
  866. is_cond = any(
  867. frame_idx in obj_temp_output_dict["cond_frame_outputs"]
  868. for obj_temp_output_dict in temp_output_dict_per_obj.values()
  869. )
  870. consolidated_out = self._consolidate_temp_output_across_obj(
  871. inference_state,
  872. frame_idx,
  873. is_cond=is_cond,
  874. consolidate_at_video_res=True,
  875. )
  876. _, video_res_masks = self._get_orig_video_res_output(
  877. inference_state, consolidated_out["pred_masks_video_res"]
  878. )
  879. updated_frames.append((frame_idx, video_res_masks))
  880. return inference_state["obj_ids"], updated_frames
  881. def _clear_non_cond_mem_around_input(self, inference_state, frame_idx):
  882. """
  883. Remove the non-conditioning memory around the input frame. When users provide
  884. correction clicks, the surrounding frames' non-conditioning memories can still
  885. contain outdated object appearance information and could confuse the model.
  886. This method clears those non-conditioning memories surrounding the interacted
  887. frame to avoid giving the model both old and new information about the object.
  888. """
  889. r = self.memory_temporal_stride_for_eval
  890. frame_idx_begin = frame_idx - r * self.num_maskmem
  891. frame_idx_end = frame_idx + r * self.num_maskmem
  892. batch_size = self._get_obj_num(inference_state)
  893. for obj_idx in range(batch_size):
  894. obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
  895. non_cond_frame_outputs = obj_output_dict["non_cond_frame_outputs"]
  896. for t in range(frame_idx_begin, frame_idx_end + 1):
  897. non_cond_frame_outputs.pop(t, None)
  898. class SAM2VideoPredictorVOS(SAM2VideoPredictor):
  899. """Optimized for the VOS setting"""
  900. def __init__(self, *args, **kwargs):
  901. super().__init__(*args, **kwargs)
  902. self._compile_all_components()
  903. def _compile_all_components(self):
  904. print("Compiling all components for VOS setting. First time may be very slow.")
  905. self.memory_encoder.forward = torch.compile(
  906. self.memory_encoder.forward,
  907. mode="max-autotune",
  908. fullgraph=True,
  909. dynamic=False,
  910. )
  911. self.memory_attention.forward = torch.compile(
  912. self.memory_attention.forward,
  913. mode="max-autotune",
  914. fullgraph=True,
  915. dynamic=True, # Num. of memories varies
  916. )
  917. self.sam_prompt_encoder.forward = torch.compile(
  918. self.sam_prompt_encoder.forward,
  919. mode="max-autotune",
  920. fullgraph=True,
  921. dynamic=False, # Accuracy regression on True
  922. )
  923. self.sam_mask_decoder.forward = torch.compile(
  924. self.sam_mask_decoder.forward,
  925. mode="max-autotune",
  926. fullgraph=True,
  927. dynamic=False, # Accuracy regression on True
  928. )
  929. def forward_image(self, img_batch: torch.Tensor):
  930. """
  931. Identical to the corresponding method in the parent (SAM2VideoPredictor), but
  932. cloning the backbone features and pos encoding to enable compilation.
  933. """
  934. backbone_out = self.image_encoder(img_batch)
  935. if self.use_high_res_features_in_sam:
  936. # precompute projected level 0 and level 1 features in SAM decoder
  937. # to avoid running it again on every SAM click
  938. backbone_out["backbone_fpn"][0] = self.sam_mask_decoder.conv_s0(
  939. backbone_out["backbone_fpn"][0]
  940. )
  941. backbone_out["backbone_fpn"][1] = self.sam_mask_decoder.conv_s1(
  942. backbone_out["backbone_fpn"][1]
  943. )
  944. # Clone to help torch.compile
  945. for i in range(len(backbone_out["backbone_fpn"])):
  946. backbone_out["backbone_fpn"][i] = backbone_out["backbone_fpn"][i].clone()
  947. backbone_out["vision_pos_enc"][i] = backbone_out["vision_pos_enc"][
  948. i
  949. ].clone()
  950. return backbone_out
  951. def _forward_sam_heads(
  952. self,
  953. backbone_features,
  954. point_inputs=None,
  955. mask_inputs=None,
  956. high_res_features=None,
  957. multimask_output=False,
  958. ):
  959. """
  960. Identical to the corresponding method in the parent (SAM2VideoPredictor), but
  961. cloning the outputs of prompt_encoder and mask_decoder to enable compilation.
  962. """
  963. B = backbone_features.size(0)
  964. device = backbone_features.device
  965. assert backbone_features.size(1) == self.sam_prompt_embed_dim
  966. assert backbone_features.size(2) == self.sam_image_embedding_size
  967. assert backbone_features.size(3) == self.sam_image_embedding_size
  968. # a) Handle point prompts
  969. if point_inputs is not None:
  970. sam_point_coords = point_inputs["point_coords"]
  971. sam_point_labels = point_inputs["point_labels"]
  972. assert sam_point_coords.size(0) == B and sam_point_labels.size(0) == B
  973. else:
  974. # If no points are provide, pad with an empty point (with label -1)
  975. sam_point_coords = torch.zeros(B, 1, 2, device=device)
  976. sam_point_labels = -torch.ones(B, 1, dtype=torch.int32, device=device)
  977. # b) Handle mask prompts
  978. if mask_inputs is not None:
  979. # If mask_inputs is provided, downsize it into low-res mask input if needed
  980. # and feed it as a dense mask prompt into the SAM mask encoder
  981. assert len(mask_inputs.shape) == 4 and mask_inputs.shape[:2] == (B, 1)
  982. if mask_inputs.shape[-2:] != self.sam_prompt_encoder.mask_input_size:
  983. sam_mask_prompt = F.interpolate(
  984. mask_inputs.float(),
  985. size=self.sam_prompt_encoder.mask_input_size,
  986. align_corners=False,
  987. mode="bilinear",
  988. antialias=True, # use antialias for downsampling
  989. )
  990. else:
  991. sam_mask_prompt = mask_inputs
  992. else:
  993. # Otherwise, simply feed None (and SAM's prompt encoder will add
  994. # a learned `no_mask_embed` to indicate no mask input in this case).
  995. sam_mask_prompt = None
  996. sparse_embeddings, dense_embeddings = self.sam_prompt_encoder(
  997. points=(sam_point_coords, sam_point_labels),
  998. boxes=None,
  999. masks=sam_mask_prompt,
  1000. )
  1001. # Clone image_pe and the outputs of sam_prompt_encoder
  1002. # to enable compilation
  1003. sparse_embeddings = sparse_embeddings.clone()
  1004. dense_embeddings = dense_embeddings.clone()
  1005. image_pe = self.sam_prompt_encoder.get_dense_pe().clone()
  1006. (
  1007. low_res_multimasks,
  1008. ious,
  1009. sam_output_tokens,
  1010. object_score_logits,
  1011. ) = self.sam_mask_decoder(
  1012. image_embeddings=backbone_features,
  1013. image_pe=image_pe,
  1014. sparse_prompt_embeddings=sparse_embeddings,
  1015. dense_prompt_embeddings=dense_embeddings,
  1016. multimask_output=multimask_output,
  1017. repeat_image=False, # the image is already batched
  1018. high_res_features=high_res_features,
  1019. )
  1020. # Clone the output of sam_mask_decoder
  1021. # to enable compilation
  1022. low_res_multimasks = low_res_multimasks.clone()
  1023. ious = ious.clone()
  1024. sam_output_tokens = sam_output_tokens.clone()
  1025. object_score_logits = object_score_logits.clone()
  1026. if self.pred_obj_scores:
  1027. is_obj_appearing = object_score_logits > 0
  1028. # Mask used for spatial memories is always a *hard* choice between obj and no obj,
  1029. # consistent with the actual mask prediction
  1030. low_res_multimasks = torch.where(
  1031. is_obj_appearing[:, None, None],
  1032. low_res_multimasks,
  1033. NO_OBJ_SCORE,
  1034. )
  1035. # convert masks from possibly bfloat16 (or float16) to float32
  1036. # (older PyTorch versions before 2.1 don't support `interpolate` on bf16)
  1037. low_res_multimasks = low_res_multimasks.float()
  1038. high_res_multimasks = F.interpolate(
  1039. low_res_multimasks,
  1040. size=(self.image_size, self.image_size),
  1041. mode="bilinear",
  1042. align_corners=False,
  1043. )
  1044. sam_output_token = sam_output_tokens[:, 0]
  1045. if multimask_output:
  1046. # take the best mask prediction (with the highest IoU estimation)
  1047. best_iou_inds = torch.argmax(ious, dim=-1)
  1048. batch_inds = torch.arange(B, device=device)
  1049. low_res_masks = low_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1)
  1050. high_res_masks = high_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1)
  1051. if sam_output_tokens.size(1) > 1:
  1052. sam_output_token = sam_output_tokens[batch_inds, best_iou_inds]
  1053. else:
  1054. low_res_masks, high_res_masks = low_res_multimasks, high_res_multimasks
  1055. # Extract object pointer from the SAM output token (with occlusion handling)
  1056. obj_ptr = self.obj_ptr_proj(sam_output_token)
  1057. if self.pred_obj_scores:
  1058. # Allow *soft* no obj ptr, unlike for masks
  1059. if self.soft_no_obj_ptr:
  1060. lambda_is_obj_appearing = object_score_logits.sigmoid()
  1061. else:
  1062. lambda_is_obj_appearing = is_obj_appearing.float()
  1063. if self.fixed_no_obj_ptr:
  1064. obj_ptr = lambda_is_obj_appearing * obj_ptr
  1065. obj_ptr = obj_ptr + (1 - lambda_is_obj_appearing) * self.no_obj_ptr
  1066. return (
  1067. low_res_multimasks,
  1068. high_res_multimasks,
  1069. ious,
  1070. low_res_masks,
  1071. high_res_masks,
  1072. obj_ptr,
  1073. object_score_logits,
  1074. )
  1075. def _encode_new_memory(
  1076. self,
  1077. current_vision_feats,
  1078. feat_sizes,
  1079. pred_masks_high_res,
  1080. object_score_logits,
  1081. is_mask_from_pts,
  1082. ):
  1083. """
  1084. Identical to the corresponding method in the parent (SAM2VideoPredictor), but
  1085. cloning the memories and their pos enc to enable compilation.
  1086. """
  1087. B = current_vision_feats[-1].size(1) # batch size on this frame
  1088. C = self.hidden_dim
  1089. H, W = feat_sizes[-1] # top-level (lowest-resolution) feature size
  1090. # top-level feature, (HW)BC => BCHW
  1091. pix_feat = current_vision_feats[-1].permute(1, 2, 0).view(B, C, H, W)
  1092. if self.non_overlap_masks_for_mem_enc and not self.training:
  1093. # optionally, apply non-overlapping constraints to the masks (it's applied
  1094. # in the batch dimension and should only be used during eval, where all
  1095. # the objects come from the same video under batch size 1).
  1096. pred_masks_high_res = self._apply_non_overlapping_constraints(
  1097. pred_masks_high_res
  1098. )
  1099. # scale the raw mask logits with a temperature before applying sigmoid
  1100. binarize = self.binarize_mask_from_pts_for_mem_enc and is_mask_from_pts
  1101. if binarize and not self.training:
  1102. mask_for_mem = (pred_masks_high_res > 0).float()
  1103. else:
  1104. # apply sigmoid on the raw mask logits to turn them into range (0, 1)
  1105. mask_for_mem = torch.sigmoid(pred_masks_high_res)
  1106. # apply scale and bias terms to the sigmoid probabilities
  1107. if self.sigmoid_scale_for_mem_enc != 1.0:
  1108. mask_for_mem = mask_for_mem * self.sigmoid_scale_for_mem_enc
  1109. if self.sigmoid_bias_for_mem_enc != 0.0:
  1110. mask_for_mem = mask_for_mem + self.sigmoid_bias_for_mem_enc
  1111. maskmem_out = self.memory_encoder(
  1112. pix_feat, mask_for_mem, skip_mask_sigmoid=True # sigmoid already applied
  1113. )
  1114. # Clone the feats and pos_enc to enable compilation
  1115. maskmem_features = maskmem_out["vision_features"].clone()
  1116. maskmem_pos_enc = [m.clone() for m in maskmem_out["vision_pos_enc"]]
  1117. # add a no-object embedding to the spatial memory to indicate that the frame
  1118. # is predicted to be occluded (i.e. no object is appearing in the frame)
  1119. if self.no_obj_embed_spatial is not None:
  1120. is_obj_appearing = (object_score_logits > 0).float()
  1121. maskmem_features += (
  1122. 1 - is_obj_appearing[..., None, None]
  1123. ) * self.no_obj_embed_spatial[..., None, None].expand(
  1124. *maskmem_features.shape
  1125. )
  1126. return maskmem_features, maskmem_pos_enc