sam2_video_predictor.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  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. from tqdm import tqdm
  9. from sam2.modeling.sam2_base import NO_OBJ_SCORE, SAM2Base
  10. from sam2.utils.misc import concat_points, fill_holes_in_mask_scores, load_video_frames
  11. class SAM2VideoPredictor(SAM2Base):
  12. """The predictor class to handle user interactions and manage inference states."""
  13. def __init__(
  14. self,
  15. fill_hole_area=0,
  16. # whether to apply non-overlapping constraints on the output object masks
  17. non_overlap_masks=False,
  18. # whether to clear non-conditioning memory of the surrounding frames (which may contain outdated information) after adding correction clicks;
  19. # note that this would only apply to *single-object tracking* unless `clear_non_cond_mem_for_multi_obj` is also set to True)
  20. clear_non_cond_mem_around_input=False,
  21. # whether to also clear non-conditioning memory of the surrounding frames (only effective when `clear_non_cond_mem_around_input` is True).
  22. clear_non_cond_mem_for_multi_obj=False,
  23. **kwargs,
  24. ):
  25. super().__init__(**kwargs)
  26. self.fill_hole_area = fill_hole_area
  27. self.non_overlap_masks = non_overlap_masks
  28. self.clear_non_cond_mem_around_input = clear_non_cond_mem_around_input
  29. self.clear_non_cond_mem_for_multi_obj = clear_non_cond_mem_for_multi_obj
  30. @torch.inference_mode()
  31. def init_state(
  32. self,
  33. video_path,
  34. offload_video_to_cpu=False,
  35. offload_state_to_cpu=False,
  36. async_loading_frames=False,
  37. ):
  38. """Initialize an inference state."""
  39. compute_device = self.device # device of the model
  40. images, video_height, video_width = load_video_frames(
  41. video_path=video_path,
  42. image_size=self.image_size,
  43. offload_video_to_cpu=offload_video_to_cpu,
  44. async_loading_frames=async_loading_frames,
  45. compute_device=compute_device,
  46. )
  47. inference_state = {}
  48. inference_state["images"] = images
  49. inference_state["num_frames"] = len(images)
  50. # whether to offload the video frames to CPU memory
  51. # turning on this option saves the GPU memory with only a very small overhead
  52. inference_state["offload_video_to_cpu"] = offload_video_to_cpu
  53. # whether to offload the inference state to CPU memory
  54. # turning on this option saves the GPU memory at the cost of a lower tracking fps
  55. # (e.g. in a test case of 768x768 model, fps dropped from 27 to 24 when tracking one object
  56. # and from 24 to 21 when tracking two objects)
  57. inference_state["offload_state_to_cpu"] = offload_state_to_cpu
  58. # the original video height and width, used for resizing final output scores
  59. inference_state["video_height"] = video_height
  60. inference_state["video_width"] = video_width
  61. inference_state["device"] = compute_device
  62. if offload_state_to_cpu:
  63. inference_state["storage_device"] = torch.device("cpu")
  64. else:
  65. inference_state["storage_device"] = compute_device
  66. # inputs on each frame
  67. inference_state["point_inputs_per_obj"] = {}
  68. inference_state["mask_inputs_per_obj"] = {}
  69. # visual features on a small number of recently visited frames for quick interactions
  70. inference_state["cached_features"] = {}
  71. # values that don't change across frames (so we only need to hold one copy of them)
  72. inference_state["constants"] = {}
  73. # mapping between client-side object id and model-side object index
  74. inference_state["obj_id_to_idx"] = OrderedDict()
  75. inference_state["obj_idx_to_id"] = OrderedDict()
  76. inference_state["obj_ids"] = []
  77. # A storage to hold the model's tracking results and states on each frame
  78. inference_state["output_dict"] = {
  79. "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
  80. "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
  81. }
  82. # Slice (view) of each object tracking results, sharing the same memory with "output_dict"
  83. inference_state["output_dict_per_obj"] = {}
  84. # A temporary storage to hold new outputs when user interact with a frame
  85. # to add clicks or mask (it's merged into "output_dict" before propagation starts)
  86. inference_state["temp_output_dict_per_obj"] = {}
  87. # Frames that already holds consolidated outputs from click or mask inputs
  88. # (we directly use their consolidated outputs during tracking)
  89. inference_state["consolidated_frame_inds"] = {
  90. "cond_frame_outputs": set(), # set containing frame indices
  91. "non_cond_frame_outputs": set(), # set containing frame indices
  92. }
  93. # metadata for each tracking frame (e.g. which direction it's tracked)
  94. inference_state["tracking_has_started"] = False
  95. inference_state["frames_already_tracked"] = {}
  96. # Warm up the visual backbone and cache the image feature on frame 0
  97. self._get_image_feature(inference_state, frame_idx=0, batch_size=1)
  98. return inference_state
  99. @classmethod
  100. def from_pretrained(cls, model_id: str, **kwargs) -> "SAM2VideoPredictor":
  101. """
  102. Load a pretrained model from the Hugging Face hub.
  103. Arguments:
  104. model_id (str): The Hugging Face repository ID.
  105. **kwargs: Additional arguments to pass to the model constructor.
  106. Returns:
  107. (SAM2VideoPredictor): The loaded model.
  108. """
  109. from sam2.build_sam import build_sam2_video_predictor_hf
  110. sam_model = build_sam2_video_predictor_hf(model_id, **kwargs)
  111. return sam_model
  112. def _obj_id_to_idx(self, inference_state, obj_id):
  113. """Map client-side object id to model-side object index."""
  114. obj_idx = inference_state["obj_id_to_idx"].get(obj_id, None)
  115. if obj_idx is not None:
  116. return obj_idx
  117. # This is a new object id not sent to the server before. We only allow adding
  118. # new objects *before* the tracking starts.
  119. allow_new_object = not inference_state["tracking_has_started"]
  120. if allow_new_object:
  121. # get the next object slot
  122. obj_idx = len(inference_state["obj_id_to_idx"])
  123. inference_state["obj_id_to_idx"][obj_id] = obj_idx
  124. inference_state["obj_idx_to_id"][obj_idx] = obj_id
  125. inference_state["obj_ids"] = list(inference_state["obj_id_to_idx"])
  126. # set up input and output structures for this object
  127. inference_state["point_inputs_per_obj"][obj_idx] = {}
  128. inference_state["mask_inputs_per_obj"][obj_idx] = {}
  129. inference_state["output_dict_per_obj"][obj_idx] = {
  130. "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
  131. "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
  132. }
  133. inference_state["temp_output_dict_per_obj"][obj_idx] = {
  134. "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
  135. "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
  136. }
  137. return obj_idx
  138. else:
  139. raise RuntimeError(
  140. f"Cannot add new object id {obj_id} after tracking starts. "
  141. f"All existing object ids: {inference_state['obj_ids']}. "
  142. f"Please call 'reset_state' to restart from scratch."
  143. )
  144. def _obj_idx_to_id(self, inference_state, obj_idx):
  145. """Map model-side object index to client-side object id."""
  146. return inference_state["obj_idx_to_id"][obj_idx]
  147. def _get_obj_num(self, inference_state):
  148. """Get the total number of unique object ids received so far in this session."""
  149. return len(inference_state["obj_idx_to_id"])
  150. @torch.inference_mode()
  151. def add_new_points_or_box(
  152. self,
  153. inference_state,
  154. frame_idx,
  155. obj_id,
  156. points=None,
  157. labels=None,
  158. clear_old_points=True,
  159. normalize_coords=True,
  160. box=None,
  161. ):
  162. """Add new points to a frame."""
  163. obj_idx = self._obj_id_to_idx(inference_state, obj_id)
  164. point_inputs_per_frame = inference_state["point_inputs_per_obj"][obj_idx]
  165. mask_inputs_per_frame = inference_state["mask_inputs_per_obj"][obj_idx]
  166. if (points is not None) != (labels is not None):
  167. raise ValueError("points and labels must be provided together")
  168. if points is None and box is None:
  169. raise ValueError("at least one of points or box must be provided as input")
  170. if points is None:
  171. points = torch.zeros(0, 2, dtype=torch.float32)
  172. elif not isinstance(points, torch.Tensor):
  173. points = torch.tensor(points, dtype=torch.float32)
  174. if labels is None:
  175. labels = torch.zeros(0, dtype=torch.int32)
  176. elif not isinstance(labels, torch.Tensor):
  177. labels = torch.tensor(labels, dtype=torch.int32)
  178. if points.dim() == 2:
  179. points = points.unsqueeze(0) # add batch dimension
  180. if labels.dim() == 1:
  181. labels = labels.unsqueeze(0) # add batch dimension
  182. # If `box` is provided, we add it as the first two points with labels 2 and 3
  183. # along with the user-provided points (consistent with how SAM 2 is trained).
  184. if box is not None:
  185. if not clear_old_points:
  186. raise ValueError(
  187. "cannot add box without clearing old points, since "
  188. "box prompt must be provided before any point prompt "
  189. "(please use clear_old_points=True instead)"
  190. )
  191. if inference_state["tracking_has_started"]:
  192. warnings.warn(
  193. "You are adding a box after tracking starts. SAM 2 may not always be "
  194. "able to incorporate a box prompt for *refinement*. If you intend to "
  195. "use box prompt as an *initial* input before tracking, please call "
  196. "'reset_state' on the inference state to restart from scratch.",
  197. category=UserWarning,
  198. stacklevel=2,
  199. )
  200. if not isinstance(box, torch.Tensor):
  201. box = torch.tensor(box, dtype=torch.float32, device=points.device)
  202. box_coords = box.reshape(1, 2, 2)
  203. box_labels = torch.tensor([2, 3], dtype=torch.int32, device=labels.device)
  204. box_labels = box_labels.reshape(1, 2)
  205. points = torch.cat([box_coords, points], dim=1)
  206. labels = torch.cat([box_labels, labels], dim=1)
  207. if normalize_coords:
  208. video_H = inference_state["video_height"]
  209. video_W = inference_state["video_width"]
  210. points = points / torch.tensor([video_W, video_H]).to(points.device)
  211. # scale the (normalized) coordinates by the model's internal image size
  212. points = points * self.image_size
  213. points = points.to(inference_state["device"])
  214. labels = labels.to(inference_state["device"])
  215. if not clear_old_points:
  216. point_inputs = point_inputs_per_frame.get(frame_idx, None)
  217. else:
  218. point_inputs = None
  219. point_inputs = concat_points(point_inputs, points, labels)
  220. point_inputs_per_frame[frame_idx] = point_inputs
  221. mask_inputs_per_frame.pop(frame_idx, None)
  222. # If this frame hasn't been tracked before, we treat it as an initial conditioning
  223. # frame, meaning that the inputs points are to generate segments on this frame without
  224. # using any memory from other frames, like in SAM. Otherwise (if it has been tracked),
  225. # the input points will be used to correct the already tracked masks.
  226. is_init_cond_frame = frame_idx not in inference_state["frames_already_tracked"]
  227. # whether to track in reverse time order
  228. if is_init_cond_frame:
  229. reverse = False
  230. else:
  231. reverse = inference_state["frames_already_tracked"][frame_idx]["reverse"]
  232. obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
  233. obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
  234. # Add a frame to conditioning output if it's an initial conditioning frame or
  235. # if the model sees all frames receiving clicks/mask as conditioning frames.
  236. is_cond = is_init_cond_frame or self.add_all_frames_to_correct_as_cond
  237. storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
  238. # Get any previously predicted mask logits on this object and feed it along with
  239. # the new clicks into the SAM mask decoder.
  240. prev_sam_mask_logits = None
  241. # lookup temporary output dict first, which contains the most recent output
  242. # (if not found, then lookup conditioning and non-conditioning frame output)
  243. prev_out = obj_temp_output_dict[storage_key].get(frame_idx)
  244. if prev_out is None:
  245. prev_out = obj_output_dict["cond_frame_outputs"].get(frame_idx)
  246. if prev_out is None:
  247. prev_out = obj_output_dict["non_cond_frame_outputs"].get(frame_idx)
  248. if prev_out is not None and prev_out["pred_masks"] is not None:
  249. device = inference_state["device"]
  250. prev_sam_mask_logits = prev_out["pred_masks"].to(device, non_blocking=True)
  251. # Clamp the scale of prev_sam_mask_logits to avoid rare numerical issues.
  252. prev_sam_mask_logits = torch.clamp(prev_sam_mask_logits, -32.0, 32.0)
  253. current_out, _ = self._run_single_frame_inference(
  254. inference_state=inference_state,
  255. output_dict=obj_output_dict, # run on the slice of a single object
  256. frame_idx=frame_idx,
  257. batch_size=1, # run on the slice of a single object
  258. is_init_cond_frame=is_init_cond_frame,
  259. point_inputs=point_inputs,
  260. mask_inputs=None,
  261. reverse=reverse,
  262. # Skip the memory encoder when adding clicks or mask. We execute the memory encoder
  263. # at the beginning of `propagate_in_video` (after user finalize their clicks). This
  264. # allows us to enforce non-overlapping constraints on all objects before encoding
  265. # them into memory.
  266. run_mem_encoder=False,
  267. prev_sam_mask_logits=prev_sam_mask_logits,
  268. )
  269. # Add the output to the output dict (to be used as future memory)
  270. obj_temp_output_dict[storage_key][frame_idx] = current_out
  271. # Resize the output mask to the original video resolution
  272. obj_ids = inference_state["obj_ids"]
  273. consolidated_out = self._consolidate_temp_output_across_obj(
  274. inference_state,
  275. frame_idx,
  276. is_cond=is_cond,
  277. run_mem_encoder=False,
  278. consolidate_at_video_res=True,
  279. )
  280. _, video_res_masks = self._get_orig_video_res_output(
  281. inference_state, consolidated_out["pred_masks_video_res"]
  282. )
  283. return frame_idx, obj_ids, video_res_masks
  284. def add_new_points(self, *args, **kwargs):
  285. """Deprecated method. Please use `add_new_points_or_box` instead."""
  286. return self.add_new_points_or_box(*args, **kwargs)
  287. @torch.inference_mode()
  288. def add_new_mask(
  289. self,
  290. inference_state,
  291. frame_idx,
  292. obj_id,
  293. mask,
  294. ):
  295. """Add new mask to a frame."""
  296. obj_idx = self._obj_id_to_idx(inference_state, obj_id)
  297. point_inputs_per_frame = inference_state["point_inputs_per_obj"][obj_idx]
  298. mask_inputs_per_frame = inference_state["mask_inputs_per_obj"][obj_idx]
  299. if not isinstance(mask, torch.Tensor):
  300. mask = torch.tensor(mask, dtype=torch.bool)
  301. assert mask.dim() == 2
  302. mask_H, mask_W = mask.shape
  303. mask_inputs_orig = mask[None, None] # add batch and channel dimension
  304. mask_inputs_orig = mask_inputs_orig.float().to(inference_state["device"])
  305. # resize the mask if it doesn't match the model's image size
  306. if mask_H != self.image_size or mask_W != self.image_size:
  307. mask_inputs = torch.nn.functional.interpolate(
  308. mask_inputs_orig,
  309. size=(self.image_size, self.image_size),
  310. align_corners=False,
  311. mode="bilinear",
  312. antialias=True, # use antialias for downsampling
  313. )
  314. mask_inputs = (mask_inputs >= 0.5).float()
  315. else:
  316. mask_inputs = mask_inputs_orig
  317. mask_inputs_per_frame[frame_idx] = mask_inputs
  318. point_inputs_per_frame.pop(frame_idx, None)
  319. # If this frame hasn't been tracked before, we treat it as an initial conditioning
  320. # frame, meaning that the inputs points are to generate segments on this frame without
  321. # using any memory from other frames, like in SAM. Otherwise (if it has been tracked),
  322. # the input points will be used to correct the already tracked masks.
  323. is_init_cond_frame = frame_idx not in inference_state["frames_already_tracked"]
  324. # whether to track in reverse time order
  325. if is_init_cond_frame:
  326. reverse = False
  327. else:
  328. reverse = inference_state["frames_already_tracked"][frame_idx]["reverse"]
  329. obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
  330. obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
  331. # Add a frame to conditioning output if it's an initial conditioning frame or
  332. # if the model sees all frames receiving clicks/mask as conditioning frames.
  333. is_cond = is_init_cond_frame or self.add_all_frames_to_correct_as_cond
  334. storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
  335. current_out, _ = self._run_single_frame_inference(
  336. inference_state=inference_state,
  337. output_dict=obj_output_dict, # run on the slice of a single object
  338. frame_idx=frame_idx,
  339. batch_size=1, # run on the slice of a single object
  340. is_init_cond_frame=is_init_cond_frame,
  341. point_inputs=None,
  342. mask_inputs=mask_inputs,
  343. reverse=reverse,
  344. # Skip the memory encoder when adding clicks or mask. We execute the memory encoder
  345. # at the beginning of `propagate_in_video` (after user finalize their clicks). This
  346. # allows us to enforce non-overlapping constraints on all objects before encoding
  347. # them into memory.
  348. run_mem_encoder=False,
  349. )
  350. # Add the output to the output dict (to be used as future memory)
  351. obj_temp_output_dict[storage_key][frame_idx] = current_out
  352. # Resize the output mask to the original video resolution
  353. obj_ids = inference_state["obj_ids"]
  354. consolidated_out = self._consolidate_temp_output_across_obj(
  355. inference_state,
  356. frame_idx,
  357. is_cond=is_cond,
  358. run_mem_encoder=False,
  359. consolidate_at_video_res=True,
  360. )
  361. _, video_res_masks = self._get_orig_video_res_output(
  362. inference_state, consolidated_out["pred_masks_video_res"]
  363. )
  364. return frame_idx, obj_ids, video_res_masks
  365. def _get_orig_video_res_output(self, inference_state, any_res_masks):
  366. """
  367. Resize the object scores to the original video resolution (video_res_masks)
  368. and apply non-overlapping constraints for final output.
  369. """
  370. device = inference_state["device"]
  371. video_H = inference_state["video_height"]
  372. video_W = inference_state["video_width"]
  373. any_res_masks = any_res_masks.to(device, non_blocking=True)
  374. if any_res_masks.shape[-2:] == (video_H, video_W):
  375. video_res_masks = any_res_masks
  376. else:
  377. video_res_masks = torch.nn.functional.interpolate(
  378. any_res_masks,
  379. size=(video_H, video_W),
  380. mode="bilinear",
  381. align_corners=False,
  382. )
  383. if self.non_overlap_masks:
  384. video_res_masks = self._apply_non_overlapping_constraints(video_res_masks)
  385. return any_res_masks, video_res_masks
  386. def _consolidate_temp_output_across_obj(
  387. self,
  388. inference_state,
  389. frame_idx,
  390. is_cond,
  391. run_mem_encoder,
  392. consolidate_at_video_res=False,
  393. ):
  394. """
  395. Consolidate the per-object temporary outputs in `temp_output_dict_per_obj` on
  396. a frame into a single output for all objects, including
  397. 1) fill any missing objects either from `output_dict_per_obj` (if they exist in
  398. `output_dict_per_obj` for this frame) or leave them as placeholder values
  399. (if they don't exist in `output_dict_per_obj` for this frame);
  400. 2) if specified, rerun memory encoder after apply non-overlapping constraints
  401. on the object scores.
  402. """
  403. batch_size = self._get_obj_num(inference_state)
  404. storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
  405. # Optionally, we allow consolidating the temporary outputs at the original
  406. # video resolution (to provide a better editing experience for mask prompts).
  407. if consolidate_at_video_res:
  408. assert not run_mem_encoder, "memory encoder cannot run at video resolution"
  409. consolidated_H = inference_state["video_height"]
  410. consolidated_W = inference_state["video_width"]
  411. consolidated_mask_key = "pred_masks_video_res"
  412. else:
  413. consolidated_H = consolidated_W = self.image_size // 4
  414. consolidated_mask_key = "pred_masks"
  415. # Initialize `consolidated_out`. Its "maskmem_features" and "maskmem_pos_enc"
  416. # will be added when rerunning the memory encoder after applying non-overlapping
  417. # constraints to object scores. Its "pred_masks" are prefilled with a large
  418. # negative value (NO_OBJ_SCORE) to represent missing objects.
  419. consolidated_out = {
  420. "maskmem_features": None,
  421. "maskmem_pos_enc": None,
  422. consolidated_mask_key: torch.full(
  423. size=(batch_size, 1, consolidated_H, consolidated_W),
  424. fill_value=NO_OBJ_SCORE,
  425. dtype=torch.float32,
  426. device=inference_state["storage_device"],
  427. ),
  428. "obj_ptr": torch.full(
  429. size=(batch_size, self.hidden_dim),
  430. fill_value=NO_OBJ_SCORE,
  431. dtype=torch.float32,
  432. device=inference_state["device"],
  433. ),
  434. }
  435. empty_mask_ptr = None
  436. for obj_idx in range(batch_size):
  437. obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
  438. obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
  439. out = obj_temp_output_dict[storage_key].get(frame_idx, None)
  440. # If the object doesn't appear in "temp_output_dict_per_obj" on this frame,
  441. # we fall back and look up its previous output in "output_dict_per_obj".
  442. # We look up both "cond_frame_outputs" and "non_cond_frame_outputs" in
  443. # "output_dict_per_obj" to find a previous output for this object.
  444. if out is None:
  445. out = obj_output_dict["cond_frame_outputs"].get(frame_idx, None)
  446. if out is None:
  447. out = obj_output_dict["non_cond_frame_outputs"].get(frame_idx, None)
  448. # If the object doesn't appear in "output_dict_per_obj" either, we skip it
  449. # and leave its mask scores to the default scores (i.e. the NO_OBJ_SCORE
  450. # placeholder above) and set its object pointer to be a dummy pointer.
  451. if out is None:
  452. # Fill in dummy object pointers for those objects without any inputs or
  453. # tracking outcomes on this frame (only do it under `run_mem_encoder=True`,
  454. # i.e. when we need to build the memory for tracking).
  455. if run_mem_encoder:
  456. if empty_mask_ptr is None:
  457. empty_mask_ptr = self._get_empty_mask_ptr(
  458. inference_state, frame_idx
  459. )
  460. # fill object pointer with a dummy pointer (based on an empty mask)
  461. consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = empty_mask_ptr
  462. continue
  463. # Add the temporary object output mask to consolidated output mask
  464. obj_mask = out["pred_masks"]
  465. consolidated_pred_masks = consolidated_out[consolidated_mask_key]
  466. if obj_mask.shape[-2:] == consolidated_pred_masks.shape[-2:]:
  467. consolidated_pred_masks[obj_idx : obj_idx + 1] = obj_mask
  468. else:
  469. # Resize first if temporary object mask has a different resolution
  470. resized_obj_mask = torch.nn.functional.interpolate(
  471. obj_mask,
  472. size=consolidated_pred_masks.shape[-2:],
  473. mode="bilinear",
  474. align_corners=False,
  475. )
  476. consolidated_pred_masks[obj_idx : obj_idx + 1] = resized_obj_mask
  477. consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = out["obj_ptr"]
  478. # Optionally, apply non-overlapping constraints on the consolidated scores
  479. # and rerun the memory encoder
  480. if run_mem_encoder:
  481. device = inference_state["device"]
  482. high_res_masks = torch.nn.functional.interpolate(
  483. consolidated_out["pred_masks"].to(device, non_blocking=True),
  484. size=(self.image_size, self.image_size),
  485. mode="bilinear",
  486. align_corners=False,
  487. )
  488. if self.non_overlap_masks_for_mem_enc:
  489. high_res_masks = self._apply_non_overlapping_constraints(high_res_masks)
  490. maskmem_features, maskmem_pos_enc = self._run_memory_encoder(
  491. inference_state=inference_state,
  492. frame_idx=frame_idx,
  493. batch_size=batch_size,
  494. high_res_masks=high_res_masks,
  495. is_mask_from_pts=True, # these frames are what the user interacted with
  496. )
  497. consolidated_out["maskmem_features"] = maskmem_features
  498. consolidated_out["maskmem_pos_enc"] = maskmem_pos_enc
  499. return consolidated_out
  500. def _get_empty_mask_ptr(self, inference_state, frame_idx):
  501. """Get a dummy object pointer based on an empty mask on the current frame."""
  502. # A dummy (empty) mask with a single object
  503. batch_size = 1
  504. mask_inputs = torch.zeros(
  505. (batch_size, 1, self.image_size, self.image_size),
  506. dtype=torch.float32,
  507. device=inference_state["device"],
  508. )
  509. # Retrieve correct image features
  510. (
  511. _,
  512. _,
  513. current_vision_feats,
  514. current_vision_pos_embeds,
  515. feat_sizes,
  516. ) = self._get_image_feature(inference_state, frame_idx, batch_size)
  517. # Feed the empty mask and image feature above to get a dummy object pointer
  518. current_out = self.track_step(
  519. frame_idx=frame_idx,
  520. is_init_cond_frame=True,
  521. current_vision_feats=current_vision_feats,
  522. current_vision_pos_embeds=current_vision_pos_embeds,
  523. feat_sizes=feat_sizes,
  524. point_inputs=None,
  525. mask_inputs=mask_inputs,
  526. output_dict={},
  527. num_frames=inference_state["num_frames"],
  528. track_in_reverse=False,
  529. run_mem_encoder=False,
  530. prev_sam_mask_logits=None,
  531. )
  532. return current_out["obj_ptr"]
  533. @torch.inference_mode()
  534. def propagate_in_video_preflight(self, inference_state):
  535. """Prepare inference_state and consolidate temporary outputs before tracking."""
  536. # Tracking has started and we don't allow adding new objects until session is reset.
  537. inference_state["tracking_has_started"] = True
  538. batch_size = self._get_obj_num(inference_state)
  539. # Consolidate per-object temporary outputs in "temp_output_dict_per_obj" and
  540. # add them into "output_dict".
  541. temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"]
  542. output_dict = inference_state["output_dict"]
  543. # "consolidated_frame_inds" contains indices of those frames where consolidated
  544. # temporary outputs have been added (either in this call or any previous calls
  545. # to `propagate_in_video_preflight`).
  546. consolidated_frame_inds = inference_state["consolidated_frame_inds"]
  547. for is_cond in [False, True]:
  548. # Separately consolidate conditioning and non-conditioning temp outputs
  549. storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
  550. # Find all the frames that contain temporary outputs for any objects
  551. # (these should be the frames that have just received clicks for mask inputs
  552. # via `add_new_points_or_box` or `add_new_mask`)
  553. temp_frame_inds = set()
  554. for obj_temp_output_dict in temp_output_dict_per_obj.values():
  555. temp_frame_inds.update(obj_temp_output_dict[storage_key].keys())
  556. consolidated_frame_inds[storage_key].update(temp_frame_inds)
  557. # consolidate the temporary output across all objects on this frame
  558. for frame_idx in temp_frame_inds:
  559. consolidated_out = self._consolidate_temp_output_across_obj(
  560. inference_state, frame_idx, is_cond=is_cond, run_mem_encoder=True
  561. )
  562. # merge them into "output_dict" and also create per-object slices
  563. output_dict[storage_key][frame_idx] = consolidated_out
  564. self._add_output_per_object(
  565. inference_state, frame_idx, consolidated_out, storage_key
  566. )
  567. clear_non_cond_mem = self.clear_non_cond_mem_around_input and (
  568. self.clear_non_cond_mem_for_multi_obj or batch_size <= 1
  569. )
  570. if clear_non_cond_mem:
  571. # clear non-conditioning memory of the surrounding frames
  572. self._clear_non_cond_mem_around_input(inference_state, frame_idx)
  573. # clear temporary outputs in `temp_output_dict_per_obj`
  574. for obj_temp_output_dict in temp_output_dict_per_obj.values():
  575. obj_temp_output_dict[storage_key].clear()
  576. # edge case: if an output is added to "cond_frame_outputs", we remove any prior
  577. # output on the same frame in "non_cond_frame_outputs"
  578. for frame_idx in output_dict["cond_frame_outputs"]:
  579. output_dict["non_cond_frame_outputs"].pop(frame_idx, None)
  580. for obj_output_dict in inference_state["output_dict_per_obj"].values():
  581. for frame_idx in obj_output_dict["cond_frame_outputs"]:
  582. obj_output_dict["non_cond_frame_outputs"].pop(frame_idx, None)
  583. for frame_idx in consolidated_frame_inds["cond_frame_outputs"]:
  584. assert frame_idx in output_dict["cond_frame_outputs"]
  585. consolidated_frame_inds["non_cond_frame_outputs"].discard(frame_idx)
  586. # Make sure that the frame indices in "consolidated_frame_inds" are exactly those frames
  587. # with either points or mask inputs (which should be true under a correct workflow).
  588. all_consolidated_frame_inds = (
  589. consolidated_frame_inds["cond_frame_outputs"]
  590. | consolidated_frame_inds["non_cond_frame_outputs"]
  591. )
  592. input_frames_inds = set()
  593. for point_inputs_per_frame in inference_state["point_inputs_per_obj"].values():
  594. input_frames_inds.update(point_inputs_per_frame.keys())
  595. for mask_inputs_per_frame in inference_state["mask_inputs_per_obj"].values():
  596. input_frames_inds.update(mask_inputs_per_frame.keys())
  597. assert all_consolidated_frame_inds == input_frames_inds
  598. @torch.inference_mode()
  599. def propagate_in_video(
  600. self,
  601. inference_state,
  602. start_frame_idx=None,
  603. max_frame_num_to_track=None,
  604. reverse=False,
  605. ):
  606. """Propagate the input points across frames to track in the entire video."""
  607. self.propagate_in_video_preflight(inference_state)
  608. output_dict = inference_state["output_dict"]
  609. consolidated_frame_inds = inference_state["consolidated_frame_inds"]
  610. obj_ids = inference_state["obj_ids"]
  611. num_frames = inference_state["num_frames"]
  612. batch_size = self._get_obj_num(inference_state)
  613. if len(output_dict["cond_frame_outputs"]) == 0:
  614. raise RuntimeError("No points are provided; please add points first")
  615. clear_non_cond_mem = self.clear_non_cond_mem_around_input and (
  616. self.clear_non_cond_mem_for_multi_obj or batch_size <= 1
  617. )
  618. # set start index, end index, and processing order
  619. if start_frame_idx is None:
  620. # default: start from the earliest frame with input points
  621. start_frame_idx = min(output_dict["cond_frame_outputs"])
  622. if max_frame_num_to_track is None:
  623. # default: track all the frames in the video
  624. max_frame_num_to_track = num_frames
  625. if reverse:
  626. end_frame_idx = max(start_frame_idx - max_frame_num_to_track, 0)
  627. if start_frame_idx > 0:
  628. processing_order = range(start_frame_idx, end_frame_idx - 1, -1)
  629. else:
  630. processing_order = [] # skip reverse tracking if starting from frame 0
  631. else:
  632. end_frame_idx = min(
  633. start_frame_idx + max_frame_num_to_track, num_frames - 1
  634. )
  635. processing_order = range(start_frame_idx, end_frame_idx + 1)
  636. for frame_idx in tqdm(processing_order, desc="propagate in video"):
  637. # We skip those frames already in consolidated outputs (these are frames
  638. # that received input clicks or mask). Note that we cannot directly run
  639. # batched forward on them via `_run_single_frame_inference` because the
  640. # number of clicks on each object might be different.
  641. if frame_idx in consolidated_frame_inds["cond_frame_outputs"]:
  642. storage_key = "cond_frame_outputs"
  643. current_out = output_dict[storage_key][frame_idx]
  644. pred_masks = current_out["pred_masks"]
  645. if clear_non_cond_mem:
  646. # clear non-conditioning memory of the surrounding frames
  647. self._clear_non_cond_mem_around_input(inference_state, frame_idx)
  648. elif frame_idx in consolidated_frame_inds["non_cond_frame_outputs"]:
  649. storage_key = "non_cond_frame_outputs"
  650. current_out = output_dict[storage_key][frame_idx]
  651. pred_masks = current_out["pred_masks"]
  652. else:
  653. storage_key = "non_cond_frame_outputs"
  654. current_out, pred_masks = self._run_single_frame_inference(
  655. inference_state=inference_state,
  656. output_dict=output_dict,
  657. frame_idx=frame_idx,
  658. batch_size=batch_size,
  659. is_init_cond_frame=False,
  660. point_inputs=None,
  661. mask_inputs=None,
  662. reverse=reverse,
  663. run_mem_encoder=True,
  664. )
  665. output_dict[storage_key][frame_idx] = current_out
  666. # Create slices of per-object outputs for subsequent interaction with each
  667. # individual object after tracking.
  668. self._add_output_per_object(
  669. inference_state, frame_idx, current_out, storage_key
  670. )
  671. inference_state["frames_already_tracked"][frame_idx] = {"reverse": reverse}
  672. # Resize the output mask to the original video resolution (we directly use
  673. # the mask scores on GPU for output to avoid any CPU conversion in between)
  674. _, video_res_masks = self._get_orig_video_res_output(
  675. inference_state, pred_masks
  676. )
  677. yield frame_idx, obj_ids, video_res_masks
  678. def _add_output_per_object(
  679. self, inference_state, frame_idx, current_out, storage_key
  680. ):
  681. """
  682. Split a multi-object output into per-object output slices and add them into
  683. `output_dict_per_obj`. The resulting slices share the same tensor storage.
  684. """
  685. maskmem_features = current_out["maskmem_features"]
  686. assert maskmem_features is None or isinstance(maskmem_features, torch.Tensor)
  687. maskmem_pos_enc = current_out["maskmem_pos_enc"]
  688. assert maskmem_pos_enc is None or isinstance(maskmem_pos_enc, list)
  689. output_dict_per_obj = inference_state["output_dict_per_obj"]
  690. for obj_idx, obj_output_dict in output_dict_per_obj.items():
  691. obj_slice = slice(obj_idx, obj_idx + 1)
  692. obj_out = {
  693. "maskmem_features": None,
  694. "maskmem_pos_enc": None,
  695. "pred_masks": current_out["pred_masks"][obj_slice],
  696. "obj_ptr": current_out["obj_ptr"][obj_slice],
  697. }
  698. if maskmem_features is not None:
  699. obj_out["maskmem_features"] = maskmem_features[obj_slice]
  700. if maskmem_pos_enc is not None:
  701. obj_out["maskmem_pos_enc"] = [x[obj_slice] for x in maskmem_pos_enc]
  702. obj_output_dict[storage_key][frame_idx] = obj_out
  703. @torch.inference_mode()
  704. def reset_state(self, inference_state):
  705. """Remove all input points or mask in all frames throughout the video."""
  706. self._reset_tracking_results(inference_state)
  707. # Remove all object ids
  708. inference_state["obj_id_to_idx"].clear()
  709. inference_state["obj_idx_to_id"].clear()
  710. inference_state["obj_ids"].clear()
  711. inference_state["point_inputs_per_obj"].clear()
  712. inference_state["mask_inputs_per_obj"].clear()
  713. inference_state["output_dict_per_obj"].clear()
  714. inference_state["temp_output_dict_per_obj"].clear()
  715. def _reset_tracking_results(self, inference_state):
  716. """Reset all tracking inputs and results across the videos."""
  717. for v in inference_state["point_inputs_per_obj"].values():
  718. v.clear()
  719. for v in inference_state["mask_inputs_per_obj"].values():
  720. v.clear()
  721. for v in inference_state["output_dict_per_obj"].values():
  722. v["cond_frame_outputs"].clear()
  723. v["non_cond_frame_outputs"].clear()
  724. for v in inference_state["temp_output_dict_per_obj"].values():
  725. v["cond_frame_outputs"].clear()
  726. v["non_cond_frame_outputs"].clear()
  727. inference_state["output_dict"]["cond_frame_outputs"].clear()
  728. inference_state["output_dict"]["non_cond_frame_outputs"].clear()
  729. inference_state["consolidated_frame_inds"]["cond_frame_outputs"].clear()
  730. inference_state["consolidated_frame_inds"]["non_cond_frame_outputs"].clear()
  731. inference_state["tracking_has_started"] = False
  732. inference_state["frames_already_tracked"].clear()
  733. def _get_image_feature(self, inference_state, frame_idx, batch_size):
  734. """Compute the image features on a given frame."""
  735. # Look up in the cache first
  736. image, backbone_out = inference_state["cached_features"].get(
  737. frame_idx, (None, None)
  738. )
  739. if backbone_out is None:
  740. # Cache miss -- we will run inference on a single image
  741. device = inference_state["device"]
  742. image = inference_state["images"][frame_idx].to(device).float().unsqueeze(0)
  743. backbone_out = self.forward_image(image)
  744. # Cache the most recent frame's feature (for repeated interactions with
  745. # a frame; we can use an LRU cache for more frames in the future).
  746. inference_state["cached_features"] = {frame_idx: (image, backbone_out)}
  747. # expand the features to have the same dimension as the number of objects
  748. expanded_image = image.expand(batch_size, -1, -1, -1)
  749. expanded_backbone_out = {
  750. "backbone_fpn": backbone_out["backbone_fpn"].copy(),
  751. "vision_pos_enc": backbone_out["vision_pos_enc"].copy(),
  752. }
  753. for i, feat in enumerate(expanded_backbone_out["backbone_fpn"]):
  754. expanded_backbone_out["backbone_fpn"][i] = feat.expand(
  755. batch_size, -1, -1, -1
  756. )
  757. for i, pos in enumerate(expanded_backbone_out["vision_pos_enc"]):
  758. pos = pos.expand(batch_size, -1, -1, -1)
  759. expanded_backbone_out["vision_pos_enc"][i] = pos
  760. features = self._prepare_backbone_features(expanded_backbone_out)
  761. features = (expanded_image,) + features
  762. return features
  763. def _run_single_frame_inference(
  764. self,
  765. inference_state,
  766. output_dict,
  767. frame_idx,
  768. batch_size,
  769. is_init_cond_frame,
  770. point_inputs,
  771. mask_inputs,
  772. reverse,
  773. run_mem_encoder,
  774. prev_sam_mask_logits=None,
  775. ):
  776. """Run tracking on a single frame based on current inputs and previous memory."""
  777. # Retrieve correct image features
  778. (
  779. _,
  780. _,
  781. current_vision_feats,
  782. current_vision_pos_embeds,
  783. feat_sizes,
  784. ) = self._get_image_feature(inference_state, frame_idx, batch_size)
  785. # point and mask should not appear as input simultaneously on the same frame
  786. assert point_inputs is None or mask_inputs is None
  787. current_out = self.track_step(
  788. frame_idx=frame_idx,
  789. is_init_cond_frame=is_init_cond_frame,
  790. current_vision_feats=current_vision_feats,
  791. current_vision_pos_embeds=current_vision_pos_embeds,
  792. feat_sizes=feat_sizes,
  793. point_inputs=point_inputs,
  794. mask_inputs=mask_inputs,
  795. output_dict=output_dict,
  796. num_frames=inference_state["num_frames"],
  797. track_in_reverse=reverse,
  798. run_mem_encoder=run_mem_encoder,
  799. prev_sam_mask_logits=prev_sam_mask_logits,
  800. )
  801. # optionally offload the output to CPU memory to save GPU space
  802. storage_device = inference_state["storage_device"]
  803. maskmem_features = current_out["maskmem_features"]
  804. if maskmem_features is not None:
  805. maskmem_features = maskmem_features.to(torch.bfloat16)
  806. maskmem_features = maskmem_features.to(storage_device, non_blocking=True)
  807. pred_masks_gpu = current_out["pred_masks"]
  808. # potentially fill holes in the predicted masks
  809. if self.fill_hole_area > 0:
  810. pred_masks_gpu = fill_holes_in_mask_scores(
  811. pred_masks_gpu, self.fill_hole_area
  812. )
  813. pred_masks = pred_masks_gpu.to(storage_device, non_blocking=True)
  814. # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
  815. maskmem_pos_enc = self._get_maskmem_pos_enc(inference_state, current_out)
  816. # object pointer is a small tensor, so we always keep it on GPU memory for fast access
  817. obj_ptr = current_out["obj_ptr"]
  818. # make a compact version of this frame's output to reduce the state size
  819. compact_current_out = {
  820. "maskmem_features": maskmem_features,
  821. "maskmem_pos_enc": maskmem_pos_enc,
  822. "pred_masks": pred_masks,
  823. "obj_ptr": obj_ptr,
  824. }
  825. return compact_current_out, pred_masks_gpu
  826. def _run_memory_encoder(
  827. self, inference_state, frame_idx, batch_size, high_res_masks, is_mask_from_pts
  828. ):
  829. """
  830. Run the memory encoder on `high_res_masks`. This is usually after applying
  831. non-overlapping constraints to object scores. Since their scores changed, their
  832. memory also need to be computed again with the memory encoder.
  833. """
  834. # Retrieve correct image features
  835. _, _, current_vision_feats, _, feat_sizes = self._get_image_feature(
  836. inference_state, frame_idx, batch_size
  837. )
  838. maskmem_features, maskmem_pos_enc = self._encode_new_memory(
  839. current_vision_feats=current_vision_feats,
  840. feat_sizes=feat_sizes,
  841. pred_masks_high_res=high_res_masks,
  842. is_mask_from_pts=is_mask_from_pts,
  843. )
  844. # optionally offload the output to CPU memory to save GPU space
  845. storage_device = inference_state["storage_device"]
  846. maskmem_features = maskmem_features.to(torch.bfloat16)
  847. maskmem_features = maskmem_features.to(storage_device, non_blocking=True)
  848. # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
  849. maskmem_pos_enc = self._get_maskmem_pos_enc(
  850. inference_state, {"maskmem_pos_enc": maskmem_pos_enc}
  851. )
  852. return maskmem_features, maskmem_pos_enc
  853. def _get_maskmem_pos_enc(self, inference_state, current_out):
  854. """
  855. `maskmem_pos_enc` is the same across frames and objects, so we cache it as
  856. a constant in the inference session to reduce session storage size.
  857. """
  858. model_constants = inference_state["constants"]
  859. # "out_maskmem_pos_enc" should be either a list of tensors or None
  860. out_maskmem_pos_enc = current_out["maskmem_pos_enc"]
  861. if out_maskmem_pos_enc is not None:
  862. if "maskmem_pos_enc" not in model_constants:
  863. assert isinstance(out_maskmem_pos_enc, list)
  864. # only take the slice for one object, since it's same across objects
  865. maskmem_pos_enc = [x[0:1].clone() for x in out_maskmem_pos_enc]
  866. model_constants["maskmem_pos_enc"] = maskmem_pos_enc
  867. else:
  868. maskmem_pos_enc = model_constants["maskmem_pos_enc"]
  869. # expand the cached maskmem_pos_enc to the actual batch size
  870. batch_size = out_maskmem_pos_enc[0].size(0)
  871. expanded_maskmem_pos_enc = [
  872. x.expand(batch_size, -1, -1, -1) for x in maskmem_pos_enc
  873. ]
  874. else:
  875. expanded_maskmem_pos_enc = None
  876. return expanded_maskmem_pos_enc
  877. def _clear_non_cond_mem_around_input(self, inference_state, frame_idx):
  878. """
  879. Remove the non-conditioning memory around the input frame. When users provide
  880. correction clicks, the surrounding frames' non-conditioning memories can still
  881. contain outdated object appearance information and could confuse the model.
  882. This method clears those non-conditioning memories surrounding the interacted
  883. frame to avoid giving the model both old and new information about the object.
  884. """
  885. r = self.memory_temporal_stride_for_eval
  886. frame_idx_begin = frame_idx - r * self.num_maskmem
  887. frame_idx_end = frame_idx + r * self.num_maskmem
  888. output_dict = inference_state["output_dict"]
  889. non_cond_frame_outputs = output_dict["non_cond_frame_outputs"]
  890. for t in range(frame_idx_begin, frame_idx_end + 1):
  891. non_cond_frame_outputs.pop(t, None)
  892. for obj_output_dict in inference_state["output_dict_per_obj"].values():
  893. obj_output_dict["non_cond_frame_outputs"].pop(t, None)