ultralytics 8.3.37__py3-none-any.whl → 8.3.38__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,6 +8,8 @@ using SAM. It forms an integral part of the Ultralytics framework and is designe
8
8
  segmentation tasks.
9
9
  """
10
10
 
11
+ from collections import OrderedDict
12
+
11
13
  import numpy as np
12
14
  import torch
13
15
  import torch.nn.functional as F
@@ -16,7 +18,7 @@ from ultralytics.data.augment import LetterBox
16
18
  from ultralytics.engine.predictor import BasePredictor
17
19
  from ultralytics.engine.results import Results
18
20
  from ultralytics.utils import DEFAULT_CFG, ops
19
- from ultralytics.utils.torch_utils import select_device
21
+ from ultralytics.utils.torch_utils import select_device, smart_inference_mode
20
22
 
21
23
  from .amg import (
22
24
  batch_iterator,
@@ -95,7 +97,7 @@ class Predictor(BasePredictor):
95
97
  """
96
98
  if overrides is None:
97
99
  overrides = {}
98
- overrides.update(dict(task="segment", mode="predict"))
100
+ overrides.update(dict(task="segment", mode="predict", batch=1))
99
101
  super().__init__(cfg, overrides, _callbacks)
100
102
  self.args.retina_masks = True
101
103
  self.im = None
@@ -114,7 +116,7 @@ class Predictor(BasePredictor):
114
116
  im (torch.Tensor | List[np.ndarray]): Input image(s) in BCHW tensor format or list of HWC numpy arrays.
115
117
 
116
118
  Returns:
117
- (torch.Tensor): The preprocessed image tensor, normalized and converted to the appropriate dtype.
119
+ im (torch.Tensor): The preprocessed image tensor, normalized and converted to the appropriate dtype.
118
120
 
119
121
  Examples:
120
122
  >>> predictor = Predictor()
@@ -181,10 +183,9 @@ class Predictor(BasePredictor):
181
183
  **kwargs (Any): Additional keyword arguments.
182
184
 
183
185
  Returns:
184
- (tuple): Contains the following three elements:
185
- - np.ndarray: The output masks in shape (C, H, W), where C is the number of generated masks.
186
- - np.ndarray: An array of length C containing quality scores predicted by the model for each mask.
187
- - np.ndarray: Low-resolution logits of shape (C, H, W) for subsequent inference, where H=W=256.
186
+ (np.ndarray): The output masks in shape (C, H, W), where C is the number of generated masks.
187
+ (np.ndarray): An array of length C containing quality scores predicted by the model for each mask.
188
+ (np.ndarray): Low-resolution logits of shape (C, H, W) for subsequent inference, where H=W=256.
188
189
 
189
190
  Examples:
190
191
  >>> predictor = Predictor()
@@ -222,10 +223,8 @@ class Predictor(BasePredictor):
222
223
  AssertionError: If the number of points don't match the number of labels, in case labels were passed.
223
224
 
224
225
  Returns:
225
- (tuple): Tuple containing:
226
- - np.ndarray: Output masks with shape (C, H, W), where C is the number of generated masks.
227
- - np.ndarray: Quality scores predicted by the model for each mask, with length C.
228
- - np.ndarray: Low-resolution logits with shape (C, H, W) for subsequent inference, where H=W=256.
226
+ (np.ndarray): Output masks with shape (C, H, W), where C is the number of generated masks.
227
+ (np.ndarray): Quality scores predicted by the model for each mask, with length C.
229
228
 
230
229
  Examples:
231
230
  >>> predictor = Predictor()
@@ -329,10 +328,9 @@ class Predictor(BasePredictor):
329
328
  crop_nms_thresh (float): IoU cutoff for NMS to remove duplicate masks between crops.
330
329
 
331
330
  Returns:
332
- (Tuple[torch.Tensor, torch.Tensor, torch.Tensor]): A tuple containing:
333
- - pred_masks (torch.Tensor): Segmented masks with shape (N, H, W).
334
- - pred_scores (torch.Tensor): Confidence scores for each mask with shape (N,).
335
- - pred_bboxes (torch.Tensor): Bounding boxes for each mask with shape (N, 4).
331
+ pred_masks (torch.Tensor): Segmented masks with shape (N, H, W).
332
+ pred_scores (torch.Tensor): Confidence scores for each mask with shape (N,).
333
+ pred_bboxes (torch.Tensor): Bounding boxes for each mask with shape (N, 4).
336
334
 
337
335
  Examples:
338
336
  >>> predictor = Predictor()
@@ -408,7 +406,7 @@ class Predictor(BasePredictor):
408
406
 
409
407
  return pred_masks, pred_scores, pred_bboxes
410
408
 
411
- def setup_model(self, model, verbose=True):
409
+ def setup_model(self, model=None, verbose=True):
412
410
  """
413
411
  Initializes the Segment Anything Model (SAM) for inference.
414
412
 
@@ -416,7 +414,7 @@ class Predictor(BasePredictor):
416
414
  parameters for image normalization and other Ultralytics compatibility settings.
417
415
 
418
416
  Args:
419
- model (torch.nn.Module): A pre-trained SAM model. If None, a model will be built based on configuration.
417
+ model (torch.nn.Module | None): A pretrained SAM model. If None, a new model is built based on config.
420
418
  verbose (bool): If True, prints selected device information.
421
419
 
422
420
  Examples:
@@ -459,7 +457,7 @@ class Predictor(BasePredictor):
459
457
  orig_imgs (List[np.ndarray] | torch.Tensor): The original, unprocessed images.
460
458
 
461
459
  Returns:
462
- (List[Results]): List of Results objects containing detection masks, bounding boxes, and other
460
+ results (List[Results]): List of Results objects containing detection masks, bounding boxes, and other
463
461
  metadata for each processed image.
464
462
 
465
463
  Examples:
@@ -586,9 +584,8 @@ class Predictor(BasePredictor):
586
584
  nms_thresh (float): IoU threshold for the NMS algorithm to remove duplicate boxes.
587
585
 
588
586
  Returns:
589
- (tuple):
590
- - new_masks (torch.Tensor): Processed masks with small regions removed, shape (N, H, W).
591
- - keep (List[int]): Indices of remaining masks after NMS, for filtering corresponding boxes.
587
+ new_masks (torch.Tensor): Processed masks with small regions removed, shape (N, H, W).
588
+ keep (List[int]): Indices of remaining masks after NMS, for filtering corresponding boxes.
592
589
 
593
590
  Examples:
594
591
  >>> masks = torch.rand(5, 640, 640) > 0.5 # 5 random binary masks
@@ -690,10 +687,8 @@ class SAM2Predictor(Predictor):
690
687
  img_idx (int): Index of the image in the batch to process.
691
688
 
692
689
  Returns:
693
- (tuple): Tuple containing:
694
- - np.ndarray: Output masks with shape (C, H, W), where C is the number of generated masks.
695
- - np.ndarray: Quality scores for each mask, with length C.
696
- - np.ndarray: Low-resolution logits with shape (C, 256, 256) for subsequent inference.
690
+ (np.ndarray): Output masks with shape (C, H, W), where C is the number of generated masks.
691
+ (np.ndarray): Quality scores for each mask, with length C.
697
692
 
698
693
  Examples:
699
694
  >>> predictor = SAM2Predictor(cfg)
@@ -712,7 +707,7 @@ class SAM2Predictor(Predictor):
712
707
  """
713
708
  features = self.get_im_features(im) if self.features is None else self.features
714
709
 
715
- bboxes, points, labels, masks = self._prepare_prompts(im.shape[2:], bboxes, points, labels, masks)
710
+ points, labels, masks = self._prepare_prompts(im.shape[2:], bboxes, points, labels, masks)
716
711
  points = (points, labels) if points is not None else None
717
712
 
718
713
  sparse_embeddings, dense_embeddings = self.model.sam_prompt_encoder(
@@ -751,7 +746,7 @@ class SAM2Predictor(Predictor):
751
746
  AssertionError: If the number of points don't match the number of labels, in case labels were passed.
752
747
 
753
748
  Returns:
754
- (tuple): A tuple containing transformed bounding boxes, points, labels, and masks.
749
+ (tuple): A tuple containing transformed points, labels, and masks.
755
750
  """
756
751
  bboxes, points, labels, masks = super()._prepare_prompts(dst_shape, bboxes, points, labels, masks)
757
752
  if bboxes is not None:
@@ -764,7 +759,7 @@ class SAM2Predictor(Predictor):
764
759
  labels = torch.cat([bbox_labels, labels], dim=1)
765
760
  else:
766
761
  points, labels = bboxes, bbox_labels
767
- return bboxes, points, labels, masks
762
+ return points, labels, masks
768
763
 
769
764
  def set_image(self, image):
770
765
  """
@@ -815,3 +810,797 @@ class SAM2Predictor(Predictor):
815
810
  for feat, feat_size in zip(vision_feats[::-1], self._bb_feat_sizes[::-1])
816
811
  ][::-1]
817
812
  return {"image_embed": feats[-1], "high_res_feats": feats[:-1]}
813
+
814
+
815
+ class SAM2VideoPredictor(SAM2Predictor):
816
+ """
817
+ SAM2VideoPredictor to handle user interactions with videos and manage inference states.
818
+
819
+ This class extends the functionality of SAM2Predictor to support video processing and maintains
820
+ the state of inference operations. It includes configurations for managing non-overlapping masks,
821
+ clearing memory for non-conditional inputs, and setting up callbacks for prediction events.
822
+
823
+ Attributes:
824
+ inference_state (Dict): A dictionary to store the current state of inference operations.
825
+ non_overlap_masks (bool): A flag indicating whether masks should be non-overlapping.
826
+ clear_non_cond_mem_around_input (bool): A flag to control clearing non-conditional memory around inputs.
827
+ clear_non_cond_mem_for_multi_obj (bool): A flag to control clearing non-conditional memory for multi-object scenarios.
828
+ callbacks (Dict): A dictionary of callbacks for various prediction lifecycle events.
829
+
830
+ Args:
831
+ cfg (Dict, Optional): Configuration settings for the predictor. Defaults to DEFAULT_CFG.
832
+ overrides (Dict, Optional): Additional configuration overrides. Defaults to None.
833
+ _callbacks (List, Optional): Custom callbacks to be added. Defaults to None.
834
+
835
+ Note:
836
+ The `fill_hole_area` attribute is defined but not used in the current implementation.
837
+ """
838
+
839
+ # fill_hole_area = 8 # not used
840
+
841
+ def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):
842
+ """
843
+ Initialize the predictor with configuration and optional overrides.
844
+
845
+ This constructor initializes the SAM2VideoPredictor with a given configuration, applies any
846
+ specified overrides, and sets up the inference state along with certain flags
847
+ that control the behavior of the predictor.
848
+
849
+ Args:
850
+ cfg (Dict): Configuration dictionary containing default settings.
851
+ overrides (Dict | None): Dictionary of values to override default configuration.
852
+ _callbacks (Dict | None): Dictionary of callback functions to customize behavior.
853
+
854
+ Examples:
855
+ >>> predictor = SAM2VideoPredictor(cfg=DEFAULT_CFG)
856
+ >>> predictor = SAM2VideoPredictor(overrides={"imgsz": 640})
857
+ >>> predictor = SAM2VideoPredictor(_callbacks={"on_predict_start": custom_callback})
858
+ """
859
+ super().__init__(cfg, overrides, _callbacks)
860
+ self.inference_state = {}
861
+ self.non_overlap_masks = True
862
+ self.clear_non_cond_mem_around_input = False
863
+ self.clear_non_cond_mem_for_multi_obj = False
864
+ self.callbacks["on_predict_start"].append(self.init_state)
865
+
866
+ def get_model(self):
867
+ """
868
+ Retrieves and configures the model with binarization enabled.
869
+
870
+ Note:
871
+ This method overrides the base class implementation to set the binarize flag to True.
872
+ """
873
+ model = super().get_model()
874
+ model.set_binarize(True)
875
+ return model
876
+
877
+ def inference(self, im, bboxes=None, points=None, labels=None, masks=None):
878
+ """
879
+ Perform image segmentation inference based on the given input cues, using the currently loaded image. This
880
+ method leverages SAM's (Segment Anything Model) architecture consisting of image encoder, prompt encoder, and
881
+ mask decoder for real-time and promptable segmentation tasks.
882
+
883
+ Args:
884
+ im (torch.Tensor): The preprocessed input image in tensor format, with shape (N, C, H, W).
885
+ bboxes (np.ndarray | List, optional): Bounding boxes with shape (N, 4), in XYXY format.
886
+ points (np.ndarray | List, optional): Points indicating object locations with shape (N, 2), in pixels.
887
+ labels (np.ndarray | List, optional): Labels for point prompts, shape (N, ). 1 = foreground, 0 = background.
888
+ masks (np.ndarray, optional): Low-resolution masks from previous predictions shape (N,H,W). For SAM H=W=256.
889
+
890
+ Returns:
891
+ (np.ndarray): The output masks in shape CxHxW, where C is the number of generated masks.
892
+ (np.ndarray): An array of length C containing quality scores predicted by the model for each mask.
893
+ """
894
+ # Override prompts if any stored in self.prompts
895
+ bboxes = self.prompts.pop("bboxes", bboxes)
896
+ points = self.prompts.pop("points", points)
897
+ masks = self.prompts.pop("masks", masks)
898
+
899
+ frame = self.dataset.frame
900
+ self.inference_state["im"] = im
901
+ output_dict = self.inference_state["output_dict"]
902
+ if len(output_dict["cond_frame_outputs"]) == 0: # initialize prompts
903
+ points, labels, masks = self._prepare_prompts(im.shape[2:], bboxes, points, labels, masks)
904
+ if points is not None:
905
+ for i in range(len(points)):
906
+ self.add_new_prompts(obj_id=i, points=points[[i]], labels=labels[[i]], frame_idx=frame)
907
+ elif masks is not None:
908
+ for i in range(len(masks)):
909
+ self.add_new_prompts(obj_id=i, masks=masks[[i]], frame_idx=frame)
910
+ self.propagate_in_video_preflight()
911
+
912
+ consolidated_frame_inds = self.inference_state["consolidated_frame_inds"]
913
+ batch_size = len(self.inference_state["obj_idx_to_id"])
914
+ if len(output_dict["cond_frame_outputs"]) == 0:
915
+ raise RuntimeError("No points are provided; please add points first")
916
+
917
+ if frame in consolidated_frame_inds["cond_frame_outputs"]:
918
+ storage_key = "cond_frame_outputs"
919
+ current_out = output_dict[storage_key][frame]
920
+ if self.clear_non_cond_mem_around_input and (self.clear_non_cond_mem_for_multi_obj or batch_size <= 1):
921
+ # clear non-conditioning memory of the surrounding frames
922
+ self._clear_non_cond_mem_around_input(frame)
923
+ elif frame in consolidated_frame_inds["non_cond_frame_outputs"]:
924
+ storage_key = "non_cond_frame_outputs"
925
+ current_out = output_dict[storage_key][frame]
926
+ else:
927
+ storage_key = "non_cond_frame_outputs"
928
+ current_out = self._run_single_frame_inference(
929
+ output_dict=output_dict,
930
+ frame_idx=frame,
931
+ batch_size=batch_size,
932
+ is_init_cond_frame=False,
933
+ point_inputs=None,
934
+ mask_inputs=None,
935
+ reverse=False,
936
+ run_mem_encoder=True,
937
+ )
938
+ output_dict[storage_key][frame] = current_out
939
+ # Create slices of per-object outputs for subsequent interaction with each
940
+ # individual object after tracking.
941
+ self._add_output_per_object(frame, current_out, storage_key)
942
+ self.inference_state["frames_already_tracked"].append(frame)
943
+ pred_masks = current_out["pred_masks"].flatten(0, 1)
944
+ pred_masks = pred_masks[(pred_masks > self.model.mask_threshold).sum((1, 2)) > 0] # filter blank masks
945
+
946
+ return pred_masks, torch.ones(len(pred_masks), dtype=pred_masks.dtype, device=pred_masks.device)
947
+
948
+ def postprocess(self, preds, img, orig_imgs):
949
+ """
950
+ Post-processes the predictions to apply non-overlapping constraints if required.
951
+
952
+ This method extends the post-processing functionality by applying non-overlapping constraints
953
+ to the predicted masks if the `non_overlap_masks` flag is set to True. This ensures that
954
+ the masks do not overlap, which can be useful for certain applications.
955
+
956
+ Args:
957
+ preds (Tuple[torch.Tensor]): The predictions from the model.
958
+ img (torch.Tensor): The processed image tensor.
959
+ orig_imgs (List[np.ndarray]): The original images before processing.
960
+
961
+ Returns:
962
+ results (list): The post-processed predictions.
963
+
964
+ Note:
965
+ If `non_overlap_masks` is True, the method applies constraints to ensure non-overlapping masks.
966
+ """
967
+ results = super().postprocess(preds, img, orig_imgs)
968
+ if self.non_overlap_masks:
969
+ for result in results:
970
+ if result.masks is None or len(result.masks) == 0:
971
+ continue
972
+ result.masks.data = self.model._apply_non_overlapping_constraints(result.masks.data.unsqueeze(0))[0]
973
+ return results
974
+
975
+ @smart_inference_mode()
976
+ def add_new_prompts(
977
+ self,
978
+ obj_id,
979
+ points=None,
980
+ labels=None,
981
+ masks=None,
982
+ frame_idx=0,
983
+ ):
984
+ """
985
+ Adds new points or masks to a specific frame for a given object ID.
986
+
987
+ This method updates the inference state with new prompts (points or masks) for a specified
988
+ object and frame index. It ensures that the prompts are either points or masks, but not both,
989
+ and updates the internal state accordingly. It also handles the generation of new segmentations
990
+ based on the provided prompts and the existing state.
991
+
992
+ Args:
993
+ obj_id (int): The ID of the object to which the prompts are associated.
994
+ points (torch.Tensor, Optional): The coordinates of the points of interest. Defaults to None.
995
+ labels (torch.Tensor, Optional): The labels corresponding to the points. Defaults to None.
996
+ masks (torch.Tensor, optional): Binary masks for the object. Defaults to None.
997
+ frame_idx (int, optional): The index of the frame to which the prompts are applied. Defaults to 0.
998
+
999
+ Returns:
1000
+ (tuple): A tuple containing the flattened predicted masks and a tensor of ones indicating the number of objects.
1001
+
1002
+ Raises:
1003
+ AssertionError: If both `masks` and `points` are provided, or neither is provided.
1004
+
1005
+ Note:
1006
+ - Only one type of prompt (either points or masks) can be added per call.
1007
+ - If the frame is being tracked for the first time, it is treated as an initial conditioning frame.
1008
+ - The method handles the consolidation of outputs and resizing of masks to the original video resolution.
1009
+ """
1010
+ assert (masks is None) ^ (points is None), "'masks' and 'points' prompts are not compatible with each other."
1011
+ obj_idx = self._obj_id_to_idx(obj_id)
1012
+
1013
+ point_inputs = None
1014
+ pop_key = "point_inputs_per_obj"
1015
+ if points is not None:
1016
+ point_inputs = {"point_coords": points, "point_labels": labels}
1017
+ self.inference_state["point_inputs_per_obj"][obj_idx][frame_idx] = point_inputs
1018
+ pop_key = "mask_inputs_per_obj"
1019
+ self.inference_state["mask_inputs_per_obj"][obj_idx][frame_idx] = masks
1020
+ self.inference_state[pop_key][obj_idx].pop(frame_idx, None)
1021
+ # If this frame hasn't been tracked before, we treat it as an initial conditioning
1022
+ # frame, meaning that the inputs points are to generate segments on this frame without
1023
+ # using any memory from other frames, like in SAM. Otherwise (if it has been tracked),
1024
+ # the input points will be used to correct the already tracked masks.
1025
+ is_init_cond_frame = frame_idx not in self.inference_state["frames_already_tracked"]
1026
+ obj_output_dict = self.inference_state["output_dict_per_obj"][obj_idx]
1027
+ obj_temp_output_dict = self.inference_state["temp_output_dict_per_obj"][obj_idx]
1028
+ # Add a frame to conditioning output if it's an initial conditioning frame or
1029
+ # if the model sees all frames receiving clicks/mask as conditioning frames.
1030
+ is_cond = is_init_cond_frame or self.model.add_all_frames_to_correct_as_cond
1031
+ storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
1032
+
1033
+ # Get any previously predicted mask logits on this object and feed it along with
1034
+ # the new clicks into the SAM mask decoder.
1035
+ prev_sam_mask_logits = None
1036
+ # lookup temporary output dict first, which contains the most recent output
1037
+ # (if not found, then lookup conditioning and non-conditioning frame output)
1038
+ if point_inputs is not None:
1039
+ prev_out = (
1040
+ obj_temp_output_dict[storage_key].get(frame_idx)
1041
+ or obj_output_dict["cond_frame_outputs"].get(frame_idx)
1042
+ or obj_output_dict["non_cond_frame_outputs"].get(frame_idx)
1043
+ )
1044
+
1045
+ if prev_out is not None and prev_out.get("pred_masks") is not None:
1046
+ prev_sam_mask_logits = prev_out["pred_masks"].to(device=self.device, non_blocking=True)
1047
+ # Clamp the scale of prev_sam_mask_logits to avoid rare numerical issues.
1048
+ prev_sam_mask_logits.clamp_(-32.0, 32.0)
1049
+ current_out = self._run_single_frame_inference(
1050
+ output_dict=obj_output_dict, # run on the slice of a single object
1051
+ frame_idx=frame_idx,
1052
+ batch_size=1, # run on the slice of a single object
1053
+ is_init_cond_frame=is_init_cond_frame,
1054
+ point_inputs=point_inputs,
1055
+ mask_inputs=masks,
1056
+ reverse=False,
1057
+ # Skip the memory encoder when adding clicks or mask. We execute the memory encoder
1058
+ # at the beginning of `propagate_in_video` (after user finalize their clicks). This
1059
+ # allows us to enforce non-overlapping constraints on all objects before encoding
1060
+ # them into memory.
1061
+ run_mem_encoder=False,
1062
+ prev_sam_mask_logits=prev_sam_mask_logits,
1063
+ )
1064
+ # Add the output to the output dict (to be used as future memory)
1065
+ obj_temp_output_dict[storage_key][frame_idx] = current_out
1066
+
1067
+ # Resize the output mask to the original video resolution
1068
+ consolidated_out = self._consolidate_temp_output_across_obj(
1069
+ frame_idx,
1070
+ is_cond=is_cond,
1071
+ run_mem_encoder=False,
1072
+ )
1073
+ pred_masks = consolidated_out["pred_masks"].flatten(0, 1)
1074
+ return pred_masks.flatten(0, 1), torch.ones(1, dtype=pred_masks.dtype, device=pred_masks.device)
1075
+
1076
+ @smart_inference_mode()
1077
+ def propagate_in_video_preflight(self):
1078
+ """
1079
+ Prepare inference_state and consolidate temporary outputs before tracking.
1080
+
1081
+ This method marks the start of tracking, disallowing the addition of new objects until the session is reset.
1082
+ It consolidates temporary outputs from `temp_output_dict_per_obj` and merges them into `output_dict`.
1083
+ Additionally, it clears non-conditioning memory around input frames and ensures that the state is consistent
1084
+ with the provided inputs.
1085
+ """
1086
+ # Tracking has started and we don't allow adding new objects until session is reset.
1087
+ self.inference_state["tracking_has_started"] = True
1088
+ batch_size = len(self.inference_state["obj_idx_to_id"])
1089
+
1090
+ # Consolidate per-object temporary outputs in "temp_output_dict_per_obj" and
1091
+ # add them into "output_dict".
1092
+ temp_output_dict_per_obj = self.inference_state["temp_output_dict_per_obj"]
1093
+ output_dict = self.inference_state["output_dict"]
1094
+ # "consolidated_frame_inds" contains indices of those frames where consolidated
1095
+ # temporary outputs have been added (either in this call or any previous calls
1096
+ # to `propagate_in_video_preflight`).
1097
+ consolidated_frame_inds = self.inference_state["consolidated_frame_inds"]
1098
+ for is_cond in {False, True}:
1099
+ # Separately consolidate conditioning and non-conditioning temp outptus
1100
+ storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
1101
+ # Find all the frames that contain temporary outputs for any objects
1102
+ # (these should be the frames that have just received clicks for mask inputs
1103
+ # via `add_new_points` or `add_new_mask`)
1104
+ temp_frame_inds = set()
1105
+ for obj_temp_output_dict in temp_output_dict_per_obj.values():
1106
+ temp_frame_inds.update(obj_temp_output_dict[storage_key].keys())
1107
+ consolidated_frame_inds[storage_key].update(temp_frame_inds)
1108
+ # consolidate the temprary output across all objects on this frame
1109
+ for frame_idx in temp_frame_inds:
1110
+ consolidated_out = self._consolidate_temp_output_across_obj(
1111
+ frame_idx, is_cond=is_cond, run_mem_encoder=True
1112
+ )
1113
+ # merge them into "output_dict" and also create per-object slices
1114
+ output_dict[storage_key][frame_idx] = consolidated_out
1115
+ self._add_output_per_object(frame_idx, consolidated_out, storage_key)
1116
+ if self.clear_non_cond_mem_around_input and (self.clear_non_cond_mem_for_multi_obj or batch_size <= 1):
1117
+ # clear non-conditioning memory of the surrounding frames
1118
+ self._clear_non_cond_mem_around_input(frame_idx)
1119
+
1120
+ # clear temporary outputs in `temp_output_dict_per_obj`
1121
+ for obj_temp_output_dict in temp_output_dict_per_obj.values():
1122
+ obj_temp_output_dict[storage_key].clear()
1123
+
1124
+ # edge case: if an output is added to "cond_frame_outputs", we remove any prior
1125
+ # output on the same frame in "non_cond_frame_outputs"
1126
+ for frame_idx in output_dict["cond_frame_outputs"]:
1127
+ output_dict["non_cond_frame_outputs"].pop(frame_idx, None)
1128
+ for obj_output_dict in self.inference_state["output_dict_per_obj"].values():
1129
+ for frame_idx in obj_output_dict["cond_frame_outputs"]:
1130
+ obj_output_dict["non_cond_frame_outputs"].pop(frame_idx, None)
1131
+ for frame_idx in consolidated_frame_inds["cond_frame_outputs"]:
1132
+ assert frame_idx in output_dict["cond_frame_outputs"]
1133
+ consolidated_frame_inds["non_cond_frame_outputs"].discard(frame_idx)
1134
+
1135
+ # Make sure that the frame indices in "consolidated_frame_inds" are exactly those frames
1136
+ # with either points or mask inputs (which should be true under a correct workflow).
1137
+ all_consolidated_frame_inds = (
1138
+ consolidated_frame_inds["cond_frame_outputs"] | consolidated_frame_inds["non_cond_frame_outputs"]
1139
+ )
1140
+ input_frames_inds = set()
1141
+ for point_inputs_per_frame in self.inference_state["point_inputs_per_obj"].values():
1142
+ input_frames_inds.update(point_inputs_per_frame.keys())
1143
+ for mask_inputs_per_frame in self.inference_state["mask_inputs_per_obj"].values():
1144
+ input_frames_inds.update(mask_inputs_per_frame.keys())
1145
+ assert all_consolidated_frame_inds == input_frames_inds
1146
+
1147
+ @staticmethod
1148
+ def init_state(predictor):
1149
+ """
1150
+ Initialize an inference state for the predictor.
1151
+
1152
+ This function sets up the initial state required for performing inference on video data.
1153
+ It includes initializing various dictionaries and ordered dictionaries that will store
1154
+ inputs, outputs, and other metadata relevant to the tracking process.
1155
+
1156
+ Args:
1157
+ predictor (SAM2VideoPredictor): The predictor object for which to initialize the state.
1158
+ """
1159
+ if len(predictor.inference_state) > 0: # means initialized
1160
+ return
1161
+ assert predictor.dataset is not None
1162
+ assert predictor.dataset.mode == "video"
1163
+
1164
+ inference_state = {}
1165
+ inference_state["num_frames"] = predictor.dataset.frames
1166
+ # inputs on each frame
1167
+ inference_state["point_inputs_per_obj"] = {}
1168
+ inference_state["mask_inputs_per_obj"] = {}
1169
+ # values that don't change across frames (so we only need to hold one copy of them)
1170
+ inference_state["constants"] = {}
1171
+ # mapping between client-side object id and model-side object index
1172
+ inference_state["obj_id_to_idx"] = OrderedDict()
1173
+ inference_state["obj_idx_to_id"] = OrderedDict()
1174
+ inference_state["obj_ids"] = []
1175
+ # A storage to hold the model's tracking results and states on each frame
1176
+ inference_state["output_dict"] = {
1177
+ "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
1178
+ "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
1179
+ }
1180
+ # Slice (view) of each object tracking results, sharing the same memory with "output_dict"
1181
+ inference_state["output_dict_per_obj"] = {}
1182
+ # A temporary storage to hold new outputs when user interact with a frame
1183
+ # to add clicks or mask (it's merged into "output_dict" before propagation starts)
1184
+ inference_state["temp_output_dict_per_obj"] = {}
1185
+ # Frames that already holds consolidated outputs from click or mask inputs
1186
+ # (we directly use their consolidated outputs during tracking)
1187
+ inference_state["consolidated_frame_inds"] = {
1188
+ "cond_frame_outputs": set(), # set containing frame indices
1189
+ "non_cond_frame_outputs": set(), # set containing frame indices
1190
+ }
1191
+ # metadata for each tracking frame (e.g. which direction it's tracked)
1192
+ inference_state["tracking_has_started"] = False
1193
+ inference_state["frames_already_tracked"] = []
1194
+ predictor.inference_state = inference_state
1195
+
1196
+ def get_im_features(self, im, batch=1):
1197
+ """
1198
+ Extracts and processes image features using SAM2's image encoder for subsequent segmentation tasks.
1199
+
1200
+ Args:
1201
+ im (torch.Tensor): The input image tensor.
1202
+ batch (int, optional): The batch size for expanding features if there are multiple prompts. Defaults to 1.
1203
+
1204
+ Returns:
1205
+ vis_feats (torch.Tensor): The visual features extracted from the image.
1206
+ vis_pos_embed (torch.Tensor): The positional embeddings for the visual features.
1207
+ feat_sizes (List(Tuple[int])): A list containing the sizes of the extracted features.
1208
+
1209
+ Note:
1210
+ - If `batch` is greater than 1, the features are expanded to fit the batch size.
1211
+ - The method leverages the model's `_prepare_backbone_features` method to prepare the backbone features.
1212
+ """
1213
+ backbone_out = self.model.forward_image(im)
1214
+ if batch > 1: # expand features if there's more than one prompt
1215
+ for i, feat in enumerate(backbone_out["backbone_fpn"]):
1216
+ backbone_out["backbone_fpn"][i] = feat.expand(batch, -1, -1, -1)
1217
+ for i, pos in enumerate(backbone_out["vision_pos_enc"]):
1218
+ pos = pos.expand(batch, -1, -1, -1)
1219
+ backbone_out["vision_pos_enc"][i] = pos
1220
+ _, vis_feats, vis_pos_embed, feat_sizes = self.model._prepare_backbone_features(backbone_out)
1221
+ return vis_feats, vis_pos_embed, feat_sizes
1222
+
1223
+ def _obj_id_to_idx(self, obj_id):
1224
+ """
1225
+ Map client-side object id to model-side object index.
1226
+
1227
+ Args:
1228
+ obj_id (int): The unique identifier of the object provided by the client side.
1229
+
1230
+ Returns:
1231
+ obj_idx (int): The index of the object on the model side.
1232
+
1233
+ Raises:
1234
+ RuntimeError: If an attempt is made to add a new object after tracking has started.
1235
+
1236
+ Note:
1237
+ - The method updates or retrieves mappings between object IDs and indices stored in
1238
+ `inference_state`.
1239
+ - It ensures that new objects can only be added before tracking commences.
1240
+ - It maintains two-way mappings between IDs and indices (`obj_id_to_idx` and `obj_idx_to_id`).
1241
+ - Additional data structures are initialized for the new object to store inputs and outputs.
1242
+ """
1243
+ obj_idx = self.inference_state["obj_id_to_idx"].get(obj_id, None)
1244
+ if obj_idx is not None:
1245
+ return obj_idx
1246
+
1247
+ # This is a new object id not sent to the server before. We only allow adding
1248
+ # new objects *before* the tracking starts.
1249
+ allow_new_object = not self.inference_state["tracking_has_started"]
1250
+ if allow_new_object:
1251
+ # get the next object slot
1252
+ obj_idx = len(self.inference_state["obj_id_to_idx"])
1253
+ self.inference_state["obj_id_to_idx"][obj_id] = obj_idx
1254
+ self.inference_state["obj_idx_to_id"][obj_idx] = obj_id
1255
+ self.inference_state["obj_ids"] = list(self.inference_state["obj_id_to_idx"])
1256
+ # set up input and output structures for this object
1257
+ self.inference_state["point_inputs_per_obj"][obj_idx] = {}
1258
+ self.inference_state["mask_inputs_per_obj"][obj_idx] = {}
1259
+ self.inference_state["output_dict_per_obj"][obj_idx] = {
1260
+ "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
1261
+ "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
1262
+ }
1263
+ self.inference_state["temp_output_dict_per_obj"][obj_idx] = {
1264
+ "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
1265
+ "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
1266
+ }
1267
+ return obj_idx
1268
+ else:
1269
+ raise RuntimeError(
1270
+ f"Cannot add new object id {obj_id} after tracking starts. "
1271
+ f"All existing object ids: {self.inference_state['obj_ids']}. "
1272
+ f"Please call 'reset_state' to restart from scratch."
1273
+ )
1274
+
1275
+ def _run_single_frame_inference(
1276
+ self,
1277
+ output_dict,
1278
+ frame_idx,
1279
+ batch_size,
1280
+ is_init_cond_frame,
1281
+ point_inputs,
1282
+ mask_inputs,
1283
+ reverse,
1284
+ run_mem_encoder,
1285
+ prev_sam_mask_logits=None,
1286
+ ):
1287
+ """
1288
+ Run tracking on a single frame based on current inputs and previous memory.
1289
+
1290
+ Args:
1291
+ output_dict (Dict): The dictionary containing the output states of the tracking process.
1292
+ frame_idx (int): The index of the current frame.
1293
+ batch_size (int): The batch size for processing the frame.
1294
+ is_init_cond_frame (bool): Indicates if the current frame is an initial conditioning frame.
1295
+ point_inputs (Dict, Optional): Input points and their labels. Defaults to None.
1296
+ mask_inputs (torch.Tensor, Optional): Input binary masks. Defaults to None.
1297
+ reverse (bool): Indicates if the tracking should be performed in reverse order.
1298
+ run_mem_encoder (bool): Indicates if the memory encoder should be executed.
1299
+ prev_sam_mask_logits (torch.Tensor, Optional): Previous mask logits for the current object. Defaults to None.
1300
+
1301
+ Returns:
1302
+ current_out (dict): A dictionary containing the output of the tracking step, including updated features and predictions.
1303
+
1304
+ Raises:
1305
+ AssertionError: If both `point_inputs` and `mask_inputs` are provided, or neither is provided.
1306
+
1307
+ Note:
1308
+ - The method assumes that `point_inputs` and `mask_inputs` are mutually exclusive.
1309
+ - The method retrieves image features using the `get_im_features` method.
1310
+ - The `maskmem_pos_enc` is assumed to be constant across frames, hence only one copy is stored.
1311
+ - The `fill_holes_in_mask_scores` function is commented out and currently unsupported due to CUDA extension requirements.
1312
+ """
1313
+ # Retrieve correct image features
1314
+ current_vision_feats, current_vision_pos_embeds, feat_sizes = self.get_im_features(
1315
+ self.inference_state["im"], batch_size
1316
+ )
1317
+
1318
+ # point and mask should not appear as input simultaneously on the same frame
1319
+ assert point_inputs is None or mask_inputs is None
1320
+ current_out = self.model.track_step(
1321
+ frame_idx=frame_idx,
1322
+ is_init_cond_frame=is_init_cond_frame,
1323
+ current_vision_feats=current_vision_feats,
1324
+ current_vision_pos_embeds=current_vision_pos_embeds,
1325
+ feat_sizes=feat_sizes,
1326
+ point_inputs=point_inputs,
1327
+ mask_inputs=mask_inputs,
1328
+ output_dict=output_dict,
1329
+ num_frames=self.inference_state["num_frames"],
1330
+ track_in_reverse=reverse,
1331
+ run_mem_encoder=run_mem_encoder,
1332
+ prev_sam_mask_logits=prev_sam_mask_logits,
1333
+ )
1334
+
1335
+ maskmem_features = current_out["maskmem_features"]
1336
+ if maskmem_features is not None:
1337
+ current_out["maskmem_features"] = maskmem_features.to(
1338
+ dtype=torch.float16, device=self.device, non_blocking=True
1339
+ )
1340
+ # NOTE: Do not support the `fill_holes_in_mask_scores` function since it needs cuda extensions
1341
+ # potentially fill holes in the predicted masks
1342
+ # if self.fill_hole_area > 0:
1343
+ # pred_masks = current_out["pred_masks"].to(self.device, non_blocking=True)
1344
+ # pred_masks = fill_holes_in_mask_scores(pred_masks, self.fill_hole_area)
1345
+
1346
+ # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
1347
+ current_out["maskmem_pos_enc"] = self._get_maskmem_pos_enc(current_out["maskmem_pos_enc"])
1348
+ return current_out
1349
+
1350
+ def _get_maskmem_pos_enc(self, out_maskmem_pos_enc):
1351
+ """
1352
+ Caches and manages the positional encoding for mask memory across frames and objects.
1353
+
1354
+ This method optimizes storage by caching the positional encoding (`maskmem_pos_enc`) for
1355
+ mask memory, which is constant across frames and objects, thus reducing the amount of
1356
+ redundant information stored during an inference session. It checks if the positional
1357
+ encoding has already been cached; if not, it caches a slice of the provided encoding.
1358
+ If the batch size is greater than one, it expands the cached positional encoding to match
1359
+ the current batch size.
1360
+
1361
+ Args:
1362
+ out_maskmem_pos_enc (List[torch.Tensor] or None): The positional encoding for mask memory.
1363
+ Should be a list of tensors or None.
1364
+
1365
+ Returns:
1366
+ out_maskmem_pos_enc (List[torch.Tensor]): The positional encoding for mask memory, either cached or expanded.
1367
+
1368
+ Note:
1369
+ - The method assumes that `out_maskmem_pos_enc` is a list of tensors or None.
1370
+ - Only a single object's slice is cached since the encoding is the same across objects.
1371
+ - The method checks if the positional encoding has already been cached in the session's constants.
1372
+ - If the batch size is greater than one, the cached encoding is expanded to fit the batch size.
1373
+ """
1374
+ model_constants = self.inference_state["constants"]
1375
+ # "out_maskmem_pos_enc" should be either a list of tensors or None
1376
+ if out_maskmem_pos_enc is not None:
1377
+ if "maskmem_pos_enc" not in model_constants:
1378
+ assert isinstance(out_maskmem_pos_enc, list)
1379
+ # only take the slice for one object, since it's same across objects
1380
+ maskmem_pos_enc = [x[0:1].clone() for x in out_maskmem_pos_enc]
1381
+ model_constants["maskmem_pos_enc"] = maskmem_pos_enc
1382
+ else:
1383
+ maskmem_pos_enc = model_constants["maskmem_pos_enc"]
1384
+ # expand the cached maskmem_pos_enc to the actual batch size
1385
+ batch_size = out_maskmem_pos_enc[0].size(0)
1386
+ if batch_size > 1:
1387
+ out_maskmem_pos_enc = [x.expand(batch_size, -1, -1, -1) for x in maskmem_pos_enc]
1388
+ return out_maskmem_pos_enc
1389
+
1390
+ def _consolidate_temp_output_across_obj(
1391
+ self,
1392
+ frame_idx,
1393
+ is_cond=False,
1394
+ run_mem_encoder=False,
1395
+ ):
1396
+ """
1397
+ Consolidates per-object temporary outputs into a single output for all objects.
1398
+
1399
+ This method combines the temporary outputs for each object on a given frame into a unified
1400
+ output. It fills in any missing objects either from the main output dictionary or leaves
1401
+ placeholders if they do not exist in the main output. Optionally, it can re-run the memory
1402
+ encoder after applying non-overlapping constraints to the object scores.
1403
+
1404
+ Args:
1405
+ frame_idx (int): The index of the frame for which to consolidate outputs.
1406
+ is_cond (bool, Optional): Indicates if the frame is considered a conditioning frame.
1407
+ Defaults to False.
1408
+ run_mem_encoder (bool, Optional): Specifies whether to run the memory encoder after
1409
+ consolidating the outputs. Defaults to False.
1410
+
1411
+ Returns:
1412
+ consolidated_out (dict): A consolidated output dictionary containing the combined results for all objects.
1413
+
1414
+ Note:
1415
+ - The method initializes the consolidated output with placeholder values for missing objects.
1416
+ - It searches for outputs in both the temporary and main output dictionaries.
1417
+ - If `run_mem_encoder` is True, it applies non-overlapping constraints and re-runs the memory encoder.
1418
+ - The `maskmem_features` and `maskmem_pos_enc` are only populated when `run_mem_encoder` is True.
1419
+ """
1420
+ batch_size = len(self.inference_state["obj_idx_to_id"])
1421
+ storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
1422
+
1423
+ # Initialize `consolidated_out`. Its "maskmem_features" and "maskmem_pos_enc"
1424
+ # will be added when rerunning the memory encoder after applying non-overlapping
1425
+ # constraints to object scores. Its "pred_masks" are prefilled with a large
1426
+ # negative value (NO_OBJ_SCORE) to represent missing objects.
1427
+ consolidated_out = {
1428
+ "maskmem_features": None,
1429
+ "maskmem_pos_enc": None,
1430
+ "pred_masks": torch.full(
1431
+ size=(batch_size, 1, self.imgsz[0] // 4, self.imgsz[1] // 4),
1432
+ fill_value=-1024.0,
1433
+ dtype=torch.float32,
1434
+ device=self.device,
1435
+ ),
1436
+ "obj_ptr": torch.full(
1437
+ size=(batch_size, self.model.hidden_dim),
1438
+ fill_value=-1024.0,
1439
+ dtype=torch.float32,
1440
+ device=self.device,
1441
+ ),
1442
+ "object_score_logits": torch.full(
1443
+ size=(batch_size, 1),
1444
+ # default to 10.0 for object_score_logits, i.e. assuming the object is
1445
+ # present as sigmoid(10)=1, same as in `predict_masks` of `MaskDecoder`
1446
+ fill_value=10.0,
1447
+ dtype=torch.float32,
1448
+ device=self.device,
1449
+ ),
1450
+ }
1451
+ for obj_idx in range(batch_size):
1452
+ obj_temp_output_dict = self.inference_state["temp_output_dict_per_obj"][obj_idx]
1453
+ obj_output_dict = self.inference_state["output_dict_per_obj"][obj_idx]
1454
+ out = (
1455
+ obj_temp_output_dict[storage_key].get(frame_idx)
1456
+ # If the object doesn't appear in "temp_output_dict_per_obj" on this frame,
1457
+ # we fall back and look up its previous output in "output_dict_per_obj".
1458
+ # We look up both "cond_frame_outputs" and "non_cond_frame_outputs" in
1459
+ # "output_dict_per_obj" to find a previous output for this object.
1460
+ or obj_output_dict["cond_frame_outputs"].get(frame_idx)
1461
+ or obj_output_dict["non_cond_frame_outputs"].get(frame_idx)
1462
+ )
1463
+ # If the object doesn't appear in "output_dict_per_obj" either, we skip it
1464
+ # and leave its mask scores to the default scores (i.e. the NO_OBJ_SCORE
1465
+ # placeholder above) and set its object pointer to be a dummy pointer.
1466
+ if out is None:
1467
+ # Fill in dummy object pointers for those objects without any inputs or
1468
+ # tracking outcomes on this frame (only do it under `run_mem_encoder=True`,
1469
+ # i.e. when we need to build the memory for tracking).
1470
+ if run_mem_encoder:
1471
+ # fill object pointer with a dummy pointer (based on an empty mask)
1472
+ consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = self._get_empty_mask_ptr(frame_idx)
1473
+ continue
1474
+ # Add the temporary object output mask to consolidated output mask
1475
+ consolidated_out["pred_masks"][obj_idx : obj_idx + 1] = out["pred_masks"]
1476
+ consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = out["obj_ptr"]
1477
+
1478
+ # Optionally, apply non-overlapping constraints on the consolidated scores and rerun the memory encoder
1479
+ if run_mem_encoder:
1480
+ high_res_masks = F.interpolate(
1481
+ consolidated_out["pred_masks"],
1482
+ size=self.imgsz,
1483
+ mode="bilinear",
1484
+ align_corners=False,
1485
+ )
1486
+ if self.model.non_overlap_masks_for_mem_enc:
1487
+ high_res_masks = self.model._apply_non_overlapping_constraints(high_res_masks)
1488
+ consolidated_out["maskmem_features"], consolidated_out["maskmem_pos_enc"] = self._run_memory_encoder(
1489
+ batch_size=batch_size,
1490
+ high_res_masks=high_res_masks,
1491
+ is_mask_from_pts=True, # these frames are what the user interacted with
1492
+ object_score_logits=consolidated_out["object_score_logits"],
1493
+ )
1494
+
1495
+ return consolidated_out
1496
+
1497
+ def _get_empty_mask_ptr(self, frame_idx):
1498
+ """
1499
+ Get a dummy object pointer based on an empty mask on the current frame.
1500
+
1501
+ Args:
1502
+ frame_idx (int): The index of the current frame for which to generate the dummy object pointer.
1503
+
1504
+ Returns:
1505
+ (torch.Tensor): A tensor representing the dummy object pointer generated from the empty mask.
1506
+ """
1507
+ # Retrieve correct image features
1508
+ current_vision_feats, current_vision_pos_embeds, feat_sizes = self.get_im_features(self.inference_state["im"])
1509
+
1510
+ # Feed the empty mask and image feature above to get a dummy object pointer
1511
+ current_out = self.model.track_step(
1512
+ frame_idx=frame_idx,
1513
+ is_init_cond_frame=True,
1514
+ current_vision_feats=current_vision_feats,
1515
+ current_vision_pos_embeds=current_vision_pos_embeds,
1516
+ feat_sizes=feat_sizes,
1517
+ point_inputs=None,
1518
+ # A dummy (empty) mask with a single object
1519
+ mask_inputs=torch.zeros((1, 1, *self.imgsz), dtype=torch.float32, device=self.device),
1520
+ output_dict={},
1521
+ num_frames=self.inference_state["num_frames"],
1522
+ track_in_reverse=False,
1523
+ run_mem_encoder=False,
1524
+ prev_sam_mask_logits=None,
1525
+ )
1526
+ return current_out["obj_ptr"]
1527
+
1528
+ def _run_memory_encoder(self, batch_size, high_res_masks, object_score_logits, is_mask_from_pts):
1529
+ """
1530
+ Run the memory encoder on masks.
1531
+
1532
+ This is usually after applying non-overlapping constraints to object scores. Since their scores changed, their
1533
+ memory also needs to be computed again with the memory encoder.
1534
+
1535
+ Args:
1536
+ batch_size (int): The batch size for processing the frame.
1537
+ high_res_masks (torch.Tensor): High-resolution masks for which to compute the memory.
1538
+ object_score_logits (torch.Tensor): Logits representing the object scores.
1539
+ is_mask_from_pts (bool): Indicates if the mask is derived from point interactions.
1540
+
1541
+ Returns:
1542
+ (tuple[torch.Tensor, torch.Tensor]): A tuple containing the encoded mask features and positional encoding.
1543
+ """
1544
+ # Retrieve correct image features
1545
+ current_vision_feats, _, feat_sizes = self.get_im_features(self.inference_state["im"], batch_size)
1546
+ maskmem_features, maskmem_pos_enc = self.model._encode_new_memory(
1547
+ current_vision_feats=current_vision_feats,
1548
+ feat_sizes=feat_sizes,
1549
+ pred_masks_high_res=high_res_masks,
1550
+ is_mask_from_pts=is_mask_from_pts,
1551
+ object_score_logits=object_score_logits,
1552
+ )
1553
+
1554
+ # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
1555
+ maskmem_pos_enc = self._get_maskmem_pos_enc(maskmem_pos_enc)
1556
+ return maskmem_features.to(dtype=torch.float16, device=self.device, non_blocking=True), maskmem_pos_enc
1557
+
1558
+ def _add_output_per_object(self, frame_idx, current_out, storage_key):
1559
+ """
1560
+ Split a multi-object output into per-object output slices and add them into Output_Dict_Per_Obj.
1561
+
1562
+ The resulting slices share the same tensor storage.
1563
+
1564
+ Args:
1565
+ frame_idx (int): The index of the current frame.
1566
+ current_out (Dict): The current output dictionary containing multi-object outputs.
1567
+ storage_key (str): The key used to store the output in the per-object output dictionary.
1568
+ """
1569
+ maskmem_features = current_out["maskmem_features"]
1570
+ assert maskmem_features is None or isinstance(maskmem_features, torch.Tensor)
1571
+
1572
+ maskmem_pos_enc = current_out["maskmem_pos_enc"]
1573
+ assert maskmem_pos_enc is None or isinstance(maskmem_pos_enc, list)
1574
+
1575
+ for obj_idx, obj_output_dict in self.inference_state["output_dict_per_obj"].items():
1576
+ obj_slice = slice(obj_idx, obj_idx + 1)
1577
+ obj_out = {
1578
+ "maskmem_features": None,
1579
+ "maskmem_pos_enc": None,
1580
+ "pred_masks": current_out["pred_masks"][obj_slice],
1581
+ "obj_ptr": current_out["obj_ptr"][obj_slice],
1582
+ }
1583
+ if maskmem_features is not None:
1584
+ obj_out["maskmem_features"] = maskmem_features[obj_slice]
1585
+ if maskmem_pos_enc is not None:
1586
+ obj_out["maskmem_pos_enc"] = [x[obj_slice] for x in maskmem_pos_enc]
1587
+ obj_output_dict[storage_key][frame_idx] = obj_out
1588
+
1589
+ def _clear_non_cond_mem_around_input(self, frame_idx):
1590
+ """
1591
+ Remove the non-conditioning memory around the input frame.
1592
+
1593
+ When users provide correction clicks, the surrounding frames' non-conditioning memories can still contain outdated
1594
+ object appearance information and could confuse the model. This method clears those non-conditioning memories
1595
+ surrounding the interacted frame to avoid giving the model both old and new information about the object.
1596
+
1597
+ Args:
1598
+ frame_idx (int): The index of the current frame where user interaction occurred.
1599
+ """
1600
+ r = self.model.memory_temporal_stride_for_eval
1601
+ frame_idx_begin = frame_idx - r * self.model.num_maskmem
1602
+ frame_idx_end = frame_idx + r * self.model.num_maskmem
1603
+ for t in range(frame_idx_begin, frame_idx_end + 1):
1604
+ self.inference_state["output_dict"]["non_cond_frame_outputs"].pop(t, None)
1605
+ for obj_output_dict in self.inference_state["output_dict_per_obj"].values():
1606
+ obj_output_dict["non_cond_frame_outputs"].pop(t, None)