dgenerate-ultralytics-headless 8.3.236__py3-none-any.whl → 8.3.239__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.
Files changed (117) hide show
  1. {dgenerate_ultralytics_headless-8.3.236.dist-info → dgenerate_ultralytics_headless-8.3.239.dist-info}/METADATA +1 -1
  2. {dgenerate_ultralytics_headless-8.3.236.dist-info → dgenerate_ultralytics_headless-8.3.239.dist-info}/RECORD +117 -105
  3. tests/test_exports.py +3 -1
  4. tests/test_python.py +2 -2
  5. tests/test_solutions.py +6 -6
  6. ultralytics/__init__.py +1 -1
  7. ultralytics/cfg/__init__.py +4 -4
  8. ultralytics/cfg/datasets/Argoverse.yaml +7 -6
  9. ultralytics/cfg/datasets/DOTAv1.5.yaml +1 -1
  10. ultralytics/cfg/datasets/DOTAv1.yaml +1 -1
  11. ultralytics/cfg/datasets/VOC.yaml +15 -16
  12. ultralytics/cfg/datasets/african-wildlife.yaml +1 -1
  13. ultralytics/cfg/datasets/coco128-seg.yaml +1 -1
  14. ultralytics/cfg/datasets/dota8-multispectral.yaml +1 -1
  15. ultralytics/cfg/datasets/dota8.yaml +2 -2
  16. ultralytics/cfg/datasets/kitti.yaml +1 -1
  17. ultralytics/cfg/datasets/xView.yaml +16 -16
  18. ultralytics/cfg/models/11/yolo11-pose.yaml +1 -1
  19. ultralytics/cfg/models/11/yoloe-11-seg.yaml +2 -2
  20. ultralytics/cfg/models/11/yoloe-11.yaml +2 -2
  21. ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +9 -6
  22. ultralytics/cfg/models/v8/yoloe-v8.yaml +9 -6
  23. ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +1 -1
  24. ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +1 -1
  25. ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +2 -2
  26. ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +2 -2
  27. ultralytics/cfg/models/v8/yolov8-ghost.yaml +2 -2
  28. ultralytics/cfg/models/v8/yolov8-obb.yaml +1 -1
  29. ultralytics/cfg/models/v8/yolov8-p2.yaml +1 -1
  30. ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +1 -1
  31. ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +1 -1
  32. ultralytics/cfg/models/v8/yolov8-world.yaml +1 -1
  33. ultralytics/cfg/models/v8/yolov8-worldv2.yaml +6 -6
  34. ultralytics/data/augment.py +1 -1
  35. ultralytics/data/base.py +4 -2
  36. ultralytics/data/build.py +4 -4
  37. ultralytics/data/loaders.py +17 -12
  38. ultralytics/data/utils.py +4 -4
  39. ultralytics/engine/exporter.py +40 -25
  40. ultralytics/engine/predictor.py +8 -6
  41. ultralytics/engine/results.py +12 -13
  42. ultralytics/engine/trainer.py +10 -2
  43. ultralytics/engine/tuner.py +2 -3
  44. ultralytics/engine/validator.py +2 -2
  45. ultralytics/models/fastsam/model.py +2 -2
  46. ultralytics/models/fastsam/predict.py +2 -3
  47. ultralytics/models/fastsam/val.py +4 -4
  48. ultralytics/models/rtdetr/predict.py +2 -3
  49. ultralytics/models/rtdetr/val.py +10 -5
  50. ultralytics/models/sam/__init__.py +14 -1
  51. ultralytics/models/sam/build.py +22 -13
  52. ultralytics/models/sam/build_sam3.py +377 -0
  53. ultralytics/models/sam/model.py +13 -5
  54. ultralytics/models/sam/modules/blocks.py +20 -8
  55. ultralytics/models/sam/modules/decoders.py +2 -3
  56. ultralytics/models/sam/modules/encoders.py +4 -1
  57. ultralytics/models/sam/modules/memory_attention.py +6 -2
  58. ultralytics/models/sam/modules/sam.py +159 -10
  59. ultralytics/models/sam/modules/utils.py +134 -4
  60. ultralytics/models/sam/predict.py +2073 -139
  61. ultralytics/models/sam/sam3/__init__.py +3 -0
  62. ultralytics/models/sam/sam3/decoder.py +546 -0
  63. ultralytics/models/sam/sam3/encoder.py +535 -0
  64. ultralytics/models/sam/sam3/geometry_encoders.py +415 -0
  65. ultralytics/models/sam/sam3/maskformer_segmentation.py +286 -0
  66. ultralytics/models/sam/sam3/model_misc.py +198 -0
  67. ultralytics/models/sam/sam3/necks.py +129 -0
  68. ultralytics/models/sam/sam3/sam3_image.py +339 -0
  69. ultralytics/models/sam/sam3/text_encoder_ve.py +307 -0
  70. ultralytics/models/sam/sam3/vitdet.py +546 -0
  71. ultralytics/models/sam/sam3/vl_combiner.py +160 -0
  72. ultralytics/models/yolo/classify/val.py +1 -1
  73. ultralytics/models/yolo/detect/train.py +1 -1
  74. ultralytics/models/yolo/detect/val.py +7 -7
  75. ultralytics/models/yolo/obb/val.py +19 -8
  76. ultralytics/models/yolo/pose/val.py +1 -1
  77. ultralytics/models/yolo/segment/val.py +1 -1
  78. ultralytics/nn/autobackend.py +9 -9
  79. ultralytics/nn/modules/block.py +1 -1
  80. ultralytics/nn/modules/transformer.py +21 -1
  81. ultralytics/nn/tasks.py +3 -3
  82. ultralytics/nn/text_model.py +2 -7
  83. ultralytics/solutions/ai_gym.py +1 -1
  84. ultralytics/solutions/analytics.py +6 -6
  85. ultralytics/solutions/config.py +1 -1
  86. ultralytics/solutions/distance_calculation.py +1 -1
  87. ultralytics/solutions/object_counter.py +1 -1
  88. ultralytics/solutions/object_cropper.py +3 -6
  89. ultralytics/solutions/parking_management.py +21 -17
  90. ultralytics/solutions/queue_management.py +5 -5
  91. ultralytics/solutions/region_counter.py +2 -2
  92. ultralytics/solutions/security_alarm.py +1 -1
  93. ultralytics/solutions/solutions.py +45 -22
  94. ultralytics/solutions/speed_estimation.py +1 -1
  95. ultralytics/trackers/basetrack.py +1 -1
  96. ultralytics/trackers/bot_sort.py +4 -3
  97. ultralytics/trackers/byte_tracker.py +4 -4
  98. ultralytics/trackers/utils/gmc.py +6 -7
  99. ultralytics/trackers/utils/kalman_filter.py +2 -1
  100. ultralytics/trackers/utils/matching.py +4 -3
  101. ultralytics/utils/__init__.py +12 -3
  102. ultralytics/utils/benchmarks.py +2 -2
  103. ultralytics/utils/callbacks/tensorboard.py +19 -25
  104. ultralytics/utils/checks.py +4 -3
  105. ultralytics/utils/downloads.py +1 -1
  106. ultralytics/utils/export/tensorflow.py +16 -2
  107. ultralytics/utils/files.py +13 -12
  108. ultralytics/utils/logger.py +62 -27
  109. ultralytics/utils/metrics.py +1 -1
  110. ultralytics/utils/ops.py +7 -9
  111. ultralytics/utils/patches.py +3 -3
  112. ultralytics/utils/plotting.py +7 -12
  113. ultralytics/utils/tuner.py +1 -1
  114. {dgenerate_ultralytics_headless-8.3.236.dist-info → dgenerate_ultralytics_headless-8.3.239.dist-info}/WHEEL +0 -0
  115. {dgenerate_ultralytics_headless-8.3.236.dist-info → dgenerate_ultralytics_headless-8.3.239.dist-info}/entry_points.txt +0 -0
  116. {dgenerate_ultralytics_headless-8.3.236.dist-info → dgenerate_ultralytics_headless-8.3.239.dist-info}/licenses/LICENSE +0 -0
  117. {dgenerate_ultralytics_headless-8.3.236.dist-info → dgenerate_ultralytics_headless-8.3.239.dist-info}/top_level.txt +0 -0
@@ -10,7 +10,8 @@ segmentation tasks.
10
10
 
11
11
  from __future__ import annotations
12
12
 
13
- from collections import OrderedDict
13
+ from collections import OrderedDict, defaultdict
14
+ from copy import deepcopy
14
15
  from typing import Any
15
16
 
16
17
  import cv2
@@ -21,7 +22,8 @@ import torch.nn.functional as F
21
22
  from ultralytics.data.augment import LetterBox
22
23
  from ultralytics.engine.predictor import BasePredictor
23
24
  from ultralytics.engine.results import Results
24
- from ultralytics.utils import DEFAULT_CFG, ops
25
+ from ultralytics.utils import DEFAULT_CFG, LOGGER, ops
26
+ from ultralytics.utils.metrics import box_iou, mask_iou
25
27
  from ultralytics.utils.torch_utils import select_device, smart_inference_mode
26
28
 
27
29
  from .amg import (
@@ -35,6 +37,7 @@ from .amg import (
35
37
  uncrop_boxes_xyxy,
36
38
  uncrop_masks,
37
39
  )
40
+ from .sam3.geometry_encoders import Prompt
38
41
 
39
42
 
40
43
  class Predictor(BasePredictor):
@@ -79,6 +82,8 @@ class Predictor(BasePredictor):
79
82
  >>> results = predictor(bboxes=bboxes)
80
83
  """
81
84
 
85
+ stride = 16
86
+
82
87
  def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):
83
88
  """Initialize the Predictor with configuration, overrides, and callbacks.
84
89
 
@@ -105,10 +110,12 @@ class Predictor(BasePredictor):
105
110
  """Preprocess the input image for model inference.
106
111
 
107
112
  This method prepares the input image by applying transformations and normalization. It supports both
108
- torch.Tensor and list of np.ndarray as input formats.
113
+ torch.Tensor and list of np.ndarray as input formats. For OpenCV-loaded images, the input is typically BGR and
114
+ is converted to RGB during preprocessing.
109
115
 
110
116
  Args:
111
- im (torch.Tensor | list[np.ndarray]): Input image(s) in BCHW tensor format or list of HWC numpy arrays.
117
+ im (torch.Tensor | list[np.ndarray]): Input image(s) in BCHW tensor format or a list of HWC NumPy arrays.
118
+ NumPy arrays are expected to be in BGR order (as returned by OpenCV) and will be converted to RGB.
112
119
 
113
120
  Returns:
114
121
  (torch.Tensor): The preprocessed image tensor, normalized and converted to the appropriate dtype.
@@ -156,7 +163,7 @@ class Predictor(BasePredictor):
156
163
  1
157
164
  """
158
165
  assert len(im) == 1, "SAM model does not currently support batched inference"
159
- letterbox = LetterBox(self.args.imgsz, auto=False, center=False)
166
+ letterbox = LetterBox(self.imgsz, auto=False, center=False)
160
167
  return [letterbox(image=x) for x in im]
161
168
 
162
169
  def inference(self, im, bboxes=None, points=None, labels=None, masks=None, multimask_output=False, *args, **kwargs):
@@ -520,30 +527,6 @@ class Predictor(BasePredictor):
520
527
  self.segment_all = False
521
528
  return results
522
529
 
523
- def setup_source(self, source):
524
- """Set up the data source for inference.
525
-
526
- This method configures the data source from which images will be fetched for inference. It supports various
527
- input types such as image files, directories, video files, and other compatible data sources.
528
-
529
- Args:
530
- source (str | Path | None): The path or identifier for the image data source. Can be a file path, directory
531
- path, URL, or other supported source types.
532
-
533
- Examples:
534
- >>> predictor = Predictor()
535
- >>> predictor.setup_source("path/to/images")
536
- >>> predictor.setup_source("video.mp4")
537
- >>> predictor.setup_source(None) # Uses default source if available
538
-
539
- Notes:
540
- - If source is None, the method may use a default source if configured.
541
- - The method adapts to different source types and prepares them for subsequent inference steps.
542
- - Supported source types may include local files, directories, URLs, and video streams.
543
- """
544
- if source is not None:
545
- super().setup_source(source)
546
-
547
530
  def set_image(self, image):
548
531
  """Preprocess and set a single image for inference.
549
532
 
@@ -553,7 +536,7 @@ class Predictor(BasePredictor):
553
536
 
554
537
  Args:
555
538
  image (str | np.ndarray): Path to the image file as a string, or a numpy array representing an image read by
556
- cv2.
539
+ cv2 (BGR channel order).
557
540
 
558
541
  Raises:
559
542
  AssertionError: If more than one image is attempted to be set.
@@ -576,12 +559,18 @@ class Predictor(BasePredictor):
576
559
  self.features = self.get_im_features(im)
577
560
  break
578
561
 
579
- def get_im_features(self, im):
580
- """Extract image features using the SAM model's image encoder for subsequent mask prediction."""
562
+ def setup_source(self, source):
563
+ """Set up the data source for SAM inference."""
564
+ if source is None: # handle the situation when set_imgsz in advance
565
+ return
566
+ super().setup_source(source, self.stride)
581
567
  assert isinstance(self.imgsz, (tuple, list)) and self.imgsz[0] == self.imgsz[1], (
582
568
  f"SAM models only support square image size, but got {self.imgsz}."
583
569
  )
584
570
  self.model.set_imgsz(self.imgsz)
571
+
572
+ def get_im_features(self, im):
573
+ """Extract image features using the SAM model's image encoder for subsequent mask prediction."""
585
574
  return self.model.image_encoder(im)
586
575
 
587
576
  def set_prompts(self, prompts):
@@ -726,6 +715,7 @@ class SAM2Predictor(Predictor):
726
715
  (128, 128),
727
716
  (64, 64),
728
717
  ]
718
+ stride = 16
729
719
 
730
720
  def get_model(self):
731
721
  """Retrieve and initialize the Segment Anything Model 2 (SAM2) for image segmentation tasks."""
@@ -767,45 +757,13 @@ class SAM2Predictor(Predictor):
767
757
  points, labels = bboxes, bbox_labels
768
758
  return points, labels, masks
769
759
 
770
- def set_image(self, image):
771
- """Preprocess and set a single image for inference using the SAM2 model.
772
-
773
- This method initializes the model if not already done, configures the data source to the specified image, and
774
- preprocesses the image for feature extraction. It supports setting only one image at a time.
775
-
776
- Args:
777
- image (str | np.ndarray): Path to the image file as a string, or a numpy array representing the image.
778
-
779
- Raises:
780
- AssertionError: If more than one image is attempted to be set.
781
-
782
- Examples:
783
- >>> predictor = SAM2Predictor()
784
- >>> predictor.set_image("path/to/image.jpg")
785
- >>> predictor.set_image(np.array([...])) # Using a numpy array
786
-
787
- Notes:
788
- - This method must be called before performing any inference on a new image.
789
- - The method caches the extracted features for efficient subsequent inferences on the same image.
790
- - Only one image can be set at a time. To process multiple images, call this method for each new image.
791
- """
792
- if self.model is None:
793
- self.setup_model(model=None)
794
- self.setup_source(image)
795
- assert len(self.dataset) == 1, "`set_image` only supports setting one image!"
796
- for batch in self.dataset:
797
- im = self.preprocess(batch[1])
798
- self.features = self.get_im_features(im)
799
- break
760
+ def setup_source(self, source):
761
+ """Set up the data source and image size for SAM2 inference."""
762
+ super().setup_source(source)
763
+ self._bb_feat_sizes = [[int(x / (self.stride * i)) for x in self.imgsz] for i in [1 / 4, 1 / 2, 1]]
800
764
 
801
765
  def get_im_features(self, im):
802
766
  """Extract image features from the SAM image encoder for subsequent processing."""
803
- assert isinstance(self.imgsz, (tuple, list)) and self.imgsz[0] == self.imgsz[1], (
804
- f"SAM 2 models only support square image size, but got {self.imgsz}."
805
- )
806
- self.model.set_imgsz(self.imgsz)
807
- self._bb_feat_sizes = [[x // (4 * i) for x in self.imgsz] for i in [1, 2, 4]]
808
-
809
767
  backbone_out = self.model.forward_image(im)
810
768
  _, vision_feats, _, _ = self.model._prepare_backbone_features(backbone_out)
811
769
  if self.model.directly_add_no_mem_embed:
@@ -1037,6 +995,7 @@ class SAM2VideoPredictor(SAM2Predictor):
1037
995
  labels=None,
1038
996
  masks=None,
1039
997
  frame_idx=0,
998
+ inference_state: dict[str, Any] | None = None,
1040
999
  ):
1041
1000
  """Add new points or masks to a specific frame for a given object ID.
1042
1001
 
@@ -1051,6 +1010,8 @@ class SAM2VideoPredictor(SAM2Predictor):
1051
1010
  labels (torch.Tensor, optional): The labels corresponding to the points.
1052
1011
  masks (torch.Tensor, optional): Binary masks for the object.
1053
1012
  frame_idx (int, optional): The index of the frame to which the prompts are applied.
1013
+ inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
1014
+ inference state.
1054
1015
 
1055
1016
  Returns:
1056
1017
  pred_masks (torch.Tensor): The flattened predicted masks.
@@ -1064,24 +1025,25 @@ class SAM2VideoPredictor(SAM2Predictor):
1064
1025
  - If the frame is being tracked for the first time, it is treated as an initial conditioning frame.
1065
1026
  - The method handles the consolidation of outputs and resizing of masks to the original video resolution.
1066
1027
  """
1028
+ inference_state = inference_state or self.inference_state
1067
1029
  assert (masks is None) ^ (points is None), "'masks' and 'points' prompts are not compatible with each other."
1068
- obj_idx = self._obj_id_to_idx(obj_id)
1030
+ obj_idx = self._obj_id_to_idx(obj_id, inference_state)
1069
1031
 
1070
1032
  point_inputs = None
1071
1033
  pop_key = "point_inputs_per_obj"
1072
1034
  if points is not None:
1073
1035
  point_inputs = {"point_coords": points, "point_labels": labels}
1074
- self.inference_state["point_inputs_per_obj"][obj_idx][frame_idx] = point_inputs
1036
+ inference_state["point_inputs_per_obj"][obj_idx][frame_idx] = point_inputs
1075
1037
  pop_key = "mask_inputs_per_obj"
1076
- self.inference_state["mask_inputs_per_obj"][obj_idx][frame_idx] = masks
1077
- self.inference_state[pop_key][obj_idx].pop(frame_idx, None)
1038
+ inference_state["mask_inputs_per_obj"][obj_idx][frame_idx] = masks
1039
+ inference_state[pop_key][obj_idx].pop(frame_idx, None)
1078
1040
  # If this frame hasn't been tracked before, we treat it as an initial conditioning
1079
1041
  # frame, meaning that the inputs points are to generate segments on this frame without
1080
1042
  # using any memory from other frames, like in SAM. Otherwise (if it has been tracked),
1081
1043
  # the input points will be used to correct the already tracked masks.
1082
- is_init_cond_frame = frame_idx not in self.inference_state["frames_already_tracked"]
1083
- obj_output_dict = self.inference_state["output_dict_per_obj"][obj_idx]
1084
- obj_temp_output_dict = self.inference_state["temp_output_dict_per_obj"][obj_idx]
1044
+ is_init_cond_frame = frame_idx not in inference_state["frames_already_tracked"]
1045
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
1046
+ obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
1085
1047
  # Add a frame to conditioning output if it's an initial conditioning frame or
1086
1048
  # if the model sees all frames receiving clicks/mask as conditioning frames.
1087
1049
  is_cond = is_init_cond_frame or self.model.add_all_frames_to_correct_as_cond
@@ -1119,6 +1081,7 @@ class SAM2VideoPredictor(SAM2Predictor):
1119
1081
  # them into memory.
1120
1082
  run_mem_encoder=False,
1121
1083
  prev_sam_mask_logits=prev_sam_mask_logits,
1084
+ inference_state=inference_state,
1122
1085
  )
1123
1086
  # Add the output to the output dict (to be used as future memory)
1124
1087
  obj_temp_output_dict[storage_key][frame_idx] = current_out
@@ -1128,31 +1091,37 @@ class SAM2VideoPredictor(SAM2Predictor):
1128
1091
  frame_idx,
1129
1092
  is_cond=is_cond,
1130
1093
  run_mem_encoder=False,
1094
+ inference_state=inference_state,
1131
1095
  )
1132
1096
  pred_masks = consolidated_out["pred_masks"].flatten(0, 1)
1133
1097
  return pred_masks.flatten(0, 1), torch.ones(1, dtype=pred_masks.dtype, device=pred_masks.device)
1134
1098
 
1135
1099
  @smart_inference_mode()
1136
- def propagate_in_video_preflight(self):
1100
+ def propagate_in_video_preflight(self, inference_state: dict[str, Any] | None = None):
1137
1101
  """Prepare inference_state and consolidate temporary outputs before tracking.
1138
1102
 
1139
1103
  This method marks the start of tracking, disallowing the addition of new objects until the session is reset. It
1140
1104
  consolidates temporary outputs from `temp_output_dict_per_obj` and merges them into `output_dict`. Additionally,
1141
1105
  it clears non-conditioning memory around input frames and ensures that the state is consistent with the provided
1142
1106
  inputs.
1107
+
1108
+ Args:
1109
+ inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
1110
+ inference state.
1143
1111
  """
1112
+ inference_state = inference_state or self.inference_state
1144
1113
  # Tracking has started and we don't allow adding new objects until session is reset.
1145
- self.inference_state["tracking_has_started"] = True
1146
- batch_size = len(self.inference_state["obj_idx_to_id"])
1114
+ inference_state["tracking_has_started"] = True
1115
+ batch_size = len(inference_state["obj_idx_to_id"])
1147
1116
 
1148
1117
  # Consolidate per-object temporary outputs in "temp_output_dict_per_obj" and
1149
1118
  # add them into "output_dict".
1150
- temp_output_dict_per_obj = self.inference_state["temp_output_dict_per_obj"]
1151
- output_dict = self.inference_state["output_dict"]
1119
+ temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"]
1120
+ output_dict = inference_state["output_dict"]
1152
1121
  # "consolidated_frame_inds" contains indices of those frames where consolidated
1153
1122
  # temporary outputs have been added (either in this call or any previous calls
1154
1123
  # to `propagate_in_video_preflight`).
1155
- consolidated_frame_inds = self.inference_state["consolidated_frame_inds"]
1124
+ consolidated_frame_inds = inference_state["consolidated_frame_inds"]
1156
1125
  for is_cond in {False, True}:
1157
1126
  # Separately consolidate conditioning and non-conditioning temp outputs
1158
1127
  storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
@@ -1166,11 +1135,11 @@ class SAM2VideoPredictor(SAM2Predictor):
1166
1135
  # consolidate the temporary output across all objects on this frame
1167
1136
  for frame_idx in temp_frame_inds:
1168
1137
  consolidated_out = self._consolidate_temp_output_across_obj(
1169
- frame_idx, is_cond=is_cond, run_mem_encoder=True
1138
+ frame_idx, is_cond=is_cond, run_mem_encoder=True, inference_state=inference_state
1170
1139
  )
1171
1140
  # merge them into "output_dict" and also create per-object slices
1172
1141
  output_dict[storage_key][frame_idx] = consolidated_out
1173
- self._add_output_per_object(frame_idx, consolidated_out, storage_key)
1142
+ self._add_output_per_object(frame_idx, consolidated_out, storage_key, inference_state=inference_state)
1174
1143
  if self.clear_non_cond_mem_around_input and (self.clear_non_cond_mem_for_multi_obj or batch_size <= 1):
1175
1144
  # clear non-conditioning memory of the surrounding frames
1176
1145
  self._clear_non_cond_mem_around_input(frame_idx)
@@ -1183,7 +1152,7 @@ class SAM2VideoPredictor(SAM2Predictor):
1183
1152
  # output on the same frame in "non_cond_frame_outputs"
1184
1153
  for frame_idx in output_dict["cond_frame_outputs"]:
1185
1154
  output_dict["non_cond_frame_outputs"].pop(frame_idx, None)
1186
- for obj_output_dict in self.inference_state["output_dict_per_obj"].values():
1155
+ for obj_output_dict in inference_state["output_dict_per_obj"].values():
1187
1156
  for frame_idx in obj_output_dict["cond_frame_outputs"]:
1188
1157
  obj_output_dict["non_cond_frame_outputs"].pop(frame_idx, None)
1189
1158
  for frame_idx in consolidated_frame_inds["cond_frame_outputs"]:
@@ -1196,9 +1165,9 @@ class SAM2VideoPredictor(SAM2Predictor):
1196
1165
  consolidated_frame_inds["cond_frame_outputs"] | consolidated_frame_inds["non_cond_frame_outputs"]
1197
1166
  )
1198
1167
  input_frames_inds = set()
1199
- for point_inputs_per_frame in self.inference_state["point_inputs_per_obj"].values():
1168
+ for point_inputs_per_frame in inference_state["point_inputs_per_obj"].values():
1200
1169
  input_frames_inds.update(point_inputs_per_frame.keys())
1201
- for mask_inputs_per_frame in self.inference_state["mask_inputs_per_obj"].values():
1170
+ for mask_inputs_per_frame in inference_state["mask_inputs_per_obj"].values():
1202
1171
  input_frames_inds.update(mask_inputs_per_frame.keys())
1203
1172
  assert all_consolidated_frame_inds == input_frames_inds
1204
1173
 
@@ -1217,9 +1186,21 @@ class SAM2VideoPredictor(SAM2Predictor):
1217
1186
  return
1218
1187
  assert predictor.dataset is not None
1219
1188
  assert predictor.dataset.mode == "video"
1189
+ predictor.inference_state = predictor._init_state(predictor.dataset.frames)
1190
+
1191
+ @staticmethod
1192
+ def _init_state(num_frames):
1193
+ """Initialize an inference state.
1220
1194
 
1195
+ This function sets up the initial state required for performing inference on video data. It includes
1196
+ initializing various dictionaries and ordered dictionaries that will store inputs, outputs, and other metadata
1197
+ relevant to the tracking process.
1198
+
1199
+ Args:
1200
+ num_frames (int): The number of frames in the video.
1201
+ """
1221
1202
  inference_state = {
1222
- "num_frames": predictor.dataset.frames,
1203
+ "num_frames": num_frames, # TODO: see if there's any chance to remove it
1223
1204
  "point_inputs_per_obj": {}, # inputs points on each frame
1224
1205
  "mask_inputs_per_obj": {}, # inputs mask on each frame
1225
1206
  "constants": {}, # values that don't change across frames (so we only need to hold one copy of them)
@@ -1247,7 +1228,7 @@ class SAM2VideoPredictor(SAM2Predictor):
1247
1228
  "tracking_has_started": False,
1248
1229
  "frames_already_tracked": [],
1249
1230
  }
1250
- predictor.inference_state = inference_state
1231
+ return inference_state
1251
1232
 
1252
1233
  def get_im_features(self, im, batch=1):
1253
1234
  """Extract and process image features using SAM2's image encoder for subsequent segmentation tasks.
@@ -1265,22 +1246,20 @@ class SAM2VideoPredictor(SAM2Predictor):
1265
1246
  - If `batch` is greater than 1, the features are expanded to fit the batch size.
1266
1247
  - The method leverages the model's `_prepare_backbone_features` method to prepare the backbone features.
1267
1248
  """
1268
- self.model.set_imgsz(self.imgsz)
1269
- backbone_out = self.model.forward_image(im)
1270
- if batch > 1: # expand features if there's more than one prompt
1271
- for i, feat in enumerate(backbone_out["backbone_fpn"]):
1272
- backbone_out["backbone_fpn"][i] = feat.expand(batch, -1, -1, -1)
1273
- for i, pos in enumerate(backbone_out["vision_pos_enc"]):
1274
- pos = pos.expand(batch, -1, -1, -1)
1275
- backbone_out["vision_pos_enc"][i] = pos
1276
- _, vis_feats, vis_pos_embed, feat_sizes = self.model._prepare_backbone_features(backbone_out)
1249
+ # check if there's precomputed backbone output
1250
+ backbone_out = getattr(self, "backbone_out", None)
1251
+ if backbone_out is None:
1252
+ backbone_out = self.model.forward_image(im)
1253
+ _, vis_feats, vis_pos_embed, feat_sizes = self.model._prepare_backbone_features(backbone_out, batch=batch)
1277
1254
  return vis_feats, vis_pos_embed, feat_sizes
1278
1255
 
1279
- def _obj_id_to_idx(self, obj_id):
1256
+ def _obj_id_to_idx(self, obj_id, inference_state: dict[str, Any] | None = None):
1280
1257
  """Map client-side object id to model-side object index.
1281
1258
 
1282
1259
  Args:
1283
1260
  obj_id (int): The unique identifier of the object provided by the client side.
1261
+ inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
1262
+ inference state.
1284
1263
 
1285
1264
  Returns:
1286
1265
  (int): The index of the object on the model side.
@@ -1295,27 +1274,28 @@ class SAM2VideoPredictor(SAM2Predictor):
1295
1274
  - It maintains two-way mappings between IDs and indices (`obj_id_to_idx` and `obj_idx_to_id`).
1296
1275
  - Additional data structures are initialized for the new object to store inputs and outputs.
1297
1276
  """
1298
- obj_idx = self.inference_state["obj_id_to_idx"].get(obj_id, None)
1277
+ inference_state = inference_state or self.inference_state
1278
+ obj_idx = inference_state["obj_id_to_idx"].get(obj_id, None)
1299
1279
  if obj_idx is not None:
1300
1280
  return obj_idx
1301
1281
 
1302
1282
  # This is a new object id not sent to the server before. We only allow adding
1303
1283
  # new objects *before* the tracking starts.
1304
- allow_new_object = not self.inference_state["tracking_has_started"]
1284
+ allow_new_object = not inference_state["tracking_has_started"]
1305
1285
  if allow_new_object:
1306
1286
  # get the next object slot
1307
- obj_idx = len(self.inference_state["obj_id_to_idx"])
1308
- self.inference_state["obj_id_to_idx"][obj_id] = obj_idx
1309
- self.inference_state["obj_idx_to_id"][obj_idx] = obj_id
1310
- self.inference_state["obj_ids"] = list(self.inference_state["obj_id_to_idx"])
1287
+ obj_idx = len(inference_state["obj_id_to_idx"])
1288
+ inference_state["obj_id_to_idx"][obj_id] = obj_idx
1289
+ inference_state["obj_idx_to_id"][obj_idx] = obj_id
1290
+ inference_state["obj_ids"] = list(inference_state["obj_id_to_idx"])
1311
1291
  # set up input and output structures for this object
1312
- self.inference_state["point_inputs_per_obj"][obj_idx] = {}
1313
- self.inference_state["mask_inputs_per_obj"][obj_idx] = {}
1314
- self.inference_state["output_dict_per_obj"][obj_idx] = {
1292
+ inference_state["point_inputs_per_obj"][obj_idx] = {}
1293
+ inference_state["mask_inputs_per_obj"][obj_idx] = {}
1294
+ inference_state["output_dict_per_obj"][obj_idx] = {
1315
1295
  "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
1316
1296
  "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
1317
1297
  }
1318
- self.inference_state["temp_output_dict_per_obj"][obj_idx] = {
1298
+ inference_state["temp_output_dict_per_obj"][obj_idx] = {
1319
1299
  "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
1320
1300
  "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
1321
1301
  }
@@ -1323,7 +1303,7 @@ class SAM2VideoPredictor(SAM2Predictor):
1323
1303
  else:
1324
1304
  raise RuntimeError(
1325
1305
  f"Cannot add new object id {obj_id} after tracking starts. "
1326
- f"All existing object ids: {self.inference_state['obj_ids']}. "
1306
+ f"All existing object ids: {inference_state['obj_ids']}. "
1327
1307
  f"Please call 'reset_state' to restart from scratch."
1328
1308
  )
1329
1309
 
@@ -1338,6 +1318,7 @@ class SAM2VideoPredictor(SAM2Predictor):
1338
1318
  reverse,
1339
1319
  run_mem_encoder,
1340
1320
  prev_sam_mask_logits=None,
1321
+ inference_state: dict[str, Any] | None = None,
1341
1322
  ):
1342
1323
  """Run tracking on a single frame based on current inputs and previous memory.
1343
1324
 
@@ -1351,6 +1332,8 @@ class SAM2VideoPredictor(SAM2Predictor):
1351
1332
  reverse (bool): Indicates if the tracking should be performed in reverse order.
1352
1333
  run_mem_encoder (bool): Indicates if the memory encoder should be executed.
1353
1334
  prev_sam_mask_logits (torch.Tensor | None): Previous mask logits for the current object.
1335
+ inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
1336
+ inference state.
1354
1337
 
1355
1338
  Returns:
1356
1339
  (dict): A dictionary containing the output of the tracking step, including updated features and predictions.
@@ -1364,9 +1347,10 @@ class SAM2VideoPredictor(SAM2Predictor):
1364
1347
  - The `maskmem_pos_enc` is assumed to be constant across frames, hence only one copy is stored.
1365
1348
  - The `fill_holes_in_mask_scores` function is commented out and currently unsupported due to CUDA extension requirements.
1366
1349
  """
1350
+ inference_state = inference_state or self.inference_state
1367
1351
  # Retrieve correct image features
1368
1352
  current_vision_feats, current_vision_pos_embeds, feat_sizes = self.get_im_features(
1369
- self.inference_state["im"], batch_size
1353
+ inference_state["im"], batch_size
1370
1354
  )
1371
1355
 
1372
1356
  # point and mask should not appear as input simultaneously on the same frame
@@ -1380,7 +1364,7 @@ class SAM2VideoPredictor(SAM2Predictor):
1380
1364
  point_inputs=point_inputs,
1381
1365
  mask_inputs=mask_inputs,
1382
1366
  output_dict=output_dict,
1383
- num_frames=self.inference_state["num_frames"],
1367
+ num_frames=inference_state["num_frames"],
1384
1368
  track_in_reverse=reverse,
1385
1369
  run_mem_encoder=run_mem_encoder,
1386
1370
  prev_sam_mask_logits=prev_sam_mask_logits,
@@ -1398,10 +1382,10 @@ class SAM2VideoPredictor(SAM2Predictor):
1398
1382
  # pred_masks = fill_holes_in_mask_scores(pred_masks, self.fill_hole_area)
1399
1383
 
1400
1384
  # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
1401
- current_out["maskmem_pos_enc"] = self._get_maskmem_pos_enc(current_out["maskmem_pos_enc"])
1385
+ current_out["maskmem_pos_enc"] = self._get_maskmem_pos_enc(current_out["maskmem_pos_enc"], inference_state)
1402
1386
  return current_out
1403
1387
 
1404
- def _get_maskmem_pos_enc(self, out_maskmem_pos_enc):
1388
+ def _get_maskmem_pos_enc(self, out_maskmem_pos_enc, inference_state: dict[str, Any] | None = None):
1405
1389
  """Cache and manage the positional encoding for mask memory across frames and objects.
1406
1390
 
1407
1391
  This method optimizes storage by caching the positional encoding (`maskmem_pos_enc`) for mask memory, which is
@@ -1413,6 +1397,8 @@ class SAM2VideoPredictor(SAM2Predictor):
1413
1397
  Args:
1414
1398
  out_maskmem_pos_enc (list[torch.Tensor] | None): The positional encoding for mask memory. Should be a list
1415
1399
  of tensors or None.
1400
+ inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
1401
+ inference state.
1416
1402
 
1417
1403
  Returns:
1418
1404
  (list[torch.Tensor]): The positional encoding for mask memory, either cached or expanded.
@@ -1423,7 +1409,8 @@ class SAM2VideoPredictor(SAM2Predictor):
1423
1409
  - The method checks if the positional encoding has already been cached in the session's constants.
1424
1410
  - If the batch size is greater than one, the cached encoding is expanded to fit the batch size.
1425
1411
  """
1426
- model_constants = self.inference_state["constants"]
1412
+ inference_state = inference_state or self.inference_state
1413
+ model_constants = inference_state["constants"]
1427
1414
  # "out_maskmem_pos_enc" should be either a list of tensors or None
1428
1415
  if out_maskmem_pos_enc is not None:
1429
1416
  if "maskmem_pos_enc" not in model_constants:
@@ -1444,6 +1431,7 @@ class SAM2VideoPredictor(SAM2Predictor):
1444
1431
  frame_idx,
1445
1432
  is_cond=False,
1446
1433
  run_mem_encoder=False,
1434
+ inference_state: dict[str, Any] | None = None,
1447
1435
  ):
1448
1436
  """Consolidate per-object temporary outputs into a single output for all objects.
1449
1437
 
@@ -1457,6 +1445,8 @@ class SAM2VideoPredictor(SAM2Predictor):
1457
1445
  is_cond (bool, optional): Indicates if the frame is considered a conditioning frame.
1458
1446
  run_mem_encoder (bool, optional): Specifies whether to run the memory encoder after consolidating the
1459
1447
  outputs.
1448
+ inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
1449
+ inference state.
1460
1450
 
1461
1451
  Returns:
1462
1452
  (dict): A consolidated output dictionary containing the combined results for all objects.
@@ -1467,7 +1457,8 @@ class SAM2VideoPredictor(SAM2Predictor):
1467
1457
  - If `run_mem_encoder` is True, it applies non-overlapping constraints and re-runs the memory encoder.
1468
1458
  - The `maskmem_features` and `maskmem_pos_enc` are only populated when `run_mem_encoder` is True.
1469
1459
  """
1470
- batch_size = len(self.inference_state["obj_idx_to_id"])
1460
+ inference_state = inference_state or self.inference_state
1461
+ batch_size = len(inference_state["obj_idx_to_id"])
1471
1462
  storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
1472
1463
 
1473
1464
  # Initialize `consolidated_out`. Its "maskmem_features" and "maskmem_pos_enc"
@@ -1478,7 +1469,8 @@ class SAM2VideoPredictor(SAM2Predictor):
1478
1469
  "maskmem_features": None,
1479
1470
  "maskmem_pos_enc": None,
1480
1471
  "pred_masks": torch.full(
1481
- size=(batch_size, 1, self.imgsz[0] // 4, self.imgsz[1] // 4),
1472
+ # size=(batch_size, 1, self.imgsz[0] // 4, self.imgsz[1] // 4),
1473
+ size=(batch_size, 1, *self._bb_feat_sizes[0]),
1482
1474
  fill_value=-1024.0,
1483
1475
  dtype=self.torch_dtype,
1484
1476
  device=self.device,
@@ -1499,8 +1491,8 @@ class SAM2VideoPredictor(SAM2Predictor):
1499
1491
  ),
1500
1492
  }
1501
1493
  for obj_idx in range(batch_size):
1502
- obj_temp_output_dict = self.inference_state["temp_output_dict_per_obj"][obj_idx]
1503
- obj_output_dict = self.inference_state["output_dict_per_obj"][obj_idx]
1494
+ obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
1495
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
1504
1496
  out = (
1505
1497
  obj_temp_output_dict[storage_key].get(frame_idx)
1506
1498
  # If the object doesn't appear in "temp_output_dict_per_obj" on this frame,
@@ -1540,21 +1532,25 @@ class SAM2VideoPredictor(SAM2Predictor):
1540
1532
  high_res_masks=high_res_masks,
1541
1533
  is_mask_from_pts=True, # these frames are what the user interacted with
1542
1534
  object_score_logits=consolidated_out["object_score_logits"],
1535
+ inference_state=inference_state,
1543
1536
  )
1544
1537
 
1545
1538
  return consolidated_out
1546
1539
 
1547
- def _get_empty_mask_ptr(self, frame_idx):
1540
+ def _get_empty_mask_ptr(self, frame_idx, inference_state: dict[str, Any] | None = None):
1548
1541
  """Get a dummy object pointer based on an empty mask on the current frame.
1549
1542
 
1550
1543
  Args:
1551
1544
  frame_idx (int): The index of the current frame for which to generate the dummy object pointer.
1545
+ inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
1546
+ inference state.
1552
1547
 
1553
1548
  Returns:
1554
1549
  (torch.Tensor): A tensor representing the dummy object pointer generated from the empty mask.
1555
1550
  """
1551
+ inference_state = inference_state or self.inference_state
1556
1552
  # Retrieve correct image features
1557
- current_vision_feats, current_vision_pos_embeds, feat_sizes = self.get_im_features(self.inference_state["im"])
1553
+ current_vision_feats, current_vision_pos_embeds, feat_sizes = self.get_im_features(inference_state["im"])
1558
1554
 
1559
1555
  # Feed the empty mask and image feature above to get a dummy object pointer
1560
1556
  current_out = self.model.track_step(
@@ -1567,14 +1563,21 @@ class SAM2VideoPredictor(SAM2Predictor):
1567
1563
  # A dummy (empty) mask with a single object
1568
1564
  mask_inputs=torch.zeros((1, 1, *self.imgsz), dtype=self.torch_dtype, device=self.device),
1569
1565
  output_dict={},
1570
- num_frames=self.inference_state["num_frames"],
1566
+ num_frames=inference_state["num_frames"],
1571
1567
  track_in_reverse=False,
1572
1568
  run_mem_encoder=False,
1573
1569
  prev_sam_mask_logits=None,
1574
1570
  )
1575
1571
  return current_out["obj_ptr"]
1576
1572
 
1577
- def _run_memory_encoder(self, batch_size, high_res_masks, object_score_logits, is_mask_from_pts):
1573
+ def _run_memory_encoder(
1574
+ self,
1575
+ batch_size,
1576
+ high_res_masks,
1577
+ object_score_logits,
1578
+ is_mask_from_pts,
1579
+ inference_state: dict[str, Any] | None = None,
1580
+ ):
1578
1581
  """Run the memory encoder on masks.
1579
1582
 
1580
1583
  This is usually after applying non-overlapping constraints to object scores. Since their scores changed, their
@@ -1585,13 +1588,16 @@ class SAM2VideoPredictor(SAM2Predictor):
1585
1588
  high_res_masks (torch.Tensor): High-resolution masks for which to compute the memory.
1586
1589
  object_score_logits (torch.Tensor): Logits representing the object scores.
1587
1590
  is_mask_from_pts (bool): Indicates if the mask is derived from point interactions.
1591
+ inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
1592
+ inference state.
1588
1593
 
1589
1594
  Returns:
1590
1595
  maskmem_features (torch.Tensor): The encoded mask features.
1591
1596
  maskmem_pos_enc (torch.Tensor): The positional encoding.
1592
1597
  """
1598
+ inference_state = inference_state or self.inference_state
1593
1599
  # Retrieve correct image features
1594
- current_vision_feats, _, feat_sizes = self.get_im_features(self.inference_state["im"], batch_size)
1600
+ current_vision_feats, _, feat_sizes = self.get_im_features(inference_state["im"], batch_size)
1595
1601
  maskmem_features, maskmem_pos_enc = self.model._encode_new_memory(
1596
1602
  current_vision_feats=current_vision_feats,
1597
1603
  feat_sizes=feat_sizes,
@@ -1601,12 +1607,14 @@ class SAM2VideoPredictor(SAM2Predictor):
1601
1607
  )
1602
1608
 
1603
1609
  # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
1604
- maskmem_pos_enc = self._get_maskmem_pos_enc(maskmem_pos_enc)
1610
+ maskmem_pos_enc = self._get_maskmem_pos_enc(maskmem_pos_enc, inference_state)
1605
1611
  return maskmem_features.to(
1606
1612
  dtype=torch.float16, device=self.device, non_blocking=self.device.type == "cuda"
1607
1613
  ), maskmem_pos_enc
1608
1614
 
1609
- def _add_output_per_object(self, frame_idx, current_out, storage_key):
1615
+ def _add_output_per_object(
1616
+ self, frame_idx, current_out, storage_key, inference_state: dict[str, Any] | None = None
1617
+ ):
1610
1618
  """Split a multi-object output into per-object output slices and add them into Output_Dict_Per_Obj.
1611
1619
 
1612
1620
  The resulting slices share the same tensor storage.
@@ -1615,14 +1623,17 @@ class SAM2VideoPredictor(SAM2Predictor):
1615
1623
  frame_idx (int): The index of the current frame.
1616
1624
  current_out (dict): The current output dictionary containing multi-object outputs.
1617
1625
  storage_key (str): The key used to store the output in the per-object output dictionary.
1626
+ inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
1627
+ inference state.
1618
1628
  """
1629
+ inference_state = inference_state or self.inference_state
1619
1630
  maskmem_features = current_out["maskmem_features"]
1620
1631
  assert maskmem_features is None or isinstance(maskmem_features, torch.Tensor)
1621
1632
 
1622
1633
  maskmem_pos_enc = current_out["maskmem_pos_enc"]
1623
1634
  assert maskmem_pos_enc is None or isinstance(maskmem_pos_enc, list)
1624
1635
 
1625
- for obj_idx, obj_output_dict in self.inference_state["output_dict_per_obj"].items():
1636
+ for obj_idx, obj_output_dict in inference_state["output_dict_per_obj"].items():
1626
1637
  obj_slice = slice(obj_idx, obj_idx + 1)
1627
1638
  obj_out = {
1628
1639
  "maskmem_features": None,
@@ -1636,7 +1647,7 @@ class SAM2VideoPredictor(SAM2Predictor):
1636
1647
  obj_out["maskmem_pos_enc"] = [x[obj_slice] for x in maskmem_pos_enc]
1637
1648
  obj_output_dict[storage_key][frame_idx] = obj_out
1638
1649
 
1639
- def _clear_non_cond_mem_around_input(self, frame_idx):
1650
+ def _clear_non_cond_mem_around_input(self, frame_idx, inference_state: dict[str, Any] | None = None):
1640
1651
  """Remove the non-conditioning memory around the input frame.
1641
1652
 
1642
1653
  When users provide correction clicks, the surrounding frames' non-conditioning memories can still contain
@@ -1646,15 +1657,179 @@ class SAM2VideoPredictor(SAM2Predictor):
1646
1657
 
1647
1658
  Args:
1648
1659
  frame_idx (int): The index of the current frame where user interaction occurred.
1660
+ inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
1661
+ inference state.
1649
1662
  """
1663
+ inference_state = inference_state or self.inference_state
1650
1664
  r = self.model.memory_temporal_stride_for_eval
1651
1665
  frame_idx_begin = frame_idx - r * self.model.num_maskmem
1652
1666
  frame_idx_end = frame_idx + r * self.model.num_maskmem
1653
1667
  for t in range(frame_idx_begin, frame_idx_end + 1):
1654
- self.inference_state["output_dict"]["non_cond_frame_outputs"].pop(t, None)
1655
- for obj_output_dict in self.inference_state["output_dict_per_obj"].values():
1668
+ inference_state["output_dict"]["non_cond_frame_outputs"].pop(t, None)
1669
+ for obj_output_dict in inference_state["output_dict_per_obj"].values():
1656
1670
  obj_output_dict["non_cond_frame_outputs"].pop(t, None)
1657
1671
 
1672
+ @smart_inference_mode()
1673
+ def remove_object(self, inference_state, obj_id, strict=False):
1674
+ """Remove an object id from the tracking state. If strict is True, we check whether the object id actually
1675
+ exists and raise an error if it doesn't exist.
1676
+ """
1677
+ old_obj_idx_to_rm = inference_state["obj_id_to_idx"].get(obj_id, None)
1678
+ # Check whether this object_id to remove actually exists and possibly raise an error.
1679
+ if old_obj_idx_to_rm is None:
1680
+ if not strict:
1681
+ return inference_state["obj_ids"]
1682
+ raise RuntimeError(
1683
+ f"Cannot remove object id {obj_id} as it doesn't exist. "
1684
+ f"All existing object ids: {inference_state['obj_ids']}."
1685
+ )
1686
+
1687
+ # If this is the only remaining object id, we simply reset the state.
1688
+ if len(inference_state["obj_id_to_idx"]) == 1:
1689
+ self.clear_all_points_in_video(inference_state)
1690
+ return inference_state["obj_ids"]
1691
+
1692
+ # There are still remaining objects after removing this object id. In this case,
1693
+ # we need to delete the object storage from inference state tensors.
1694
+ # Step 0: clear the input on those frames where this object id has point or mask input
1695
+ # (note that this step is required as it might downgrade conditioning frames to
1696
+ # non-conditioning ones)
1697
+ obj_input_frames_inds = set()
1698
+ obj_input_frames_inds.update(inference_state["point_inputs_per_obj"][old_obj_idx_to_rm])
1699
+ obj_input_frames_inds.update(inference_state["mask_inputs_per_obj"][old_obj_idx_to_rm])
1700
+ for frame_idx in obj_input_frames_inds:
1701
+ self.clear_all_points_in_frame(inference_state, frame_idx, obj_id)
1702
+
1703
+ # Step 1: Update the object id mapping (note that it must be done after Step 0,
1704
+ # since Step 0 still requires the old object id mappings in inference_state)
1705
+ old_obj_ids = inference_state["obj_ids"]
1706
+ old_obj_inds = list(range(len(old_obj_ids)))
1707
+ remain_old_obj_inds = old_obj_inds.copy()
1708
+ remain_old_obj_inds.remove(old_obj_idx_to_rm)
1709
+ new_obj_ids = [old_obj_ids[old_idx] for old_idx in remain_old_obj_inds]
1710
+ new_obj_inds = list(range(len(new_obj_ids)))
1711
+ # build new mappings
1712
+ old_idx_to_new_idx = dict(zip(remain_old_obj_inds, new_obj_inds))
1713
+ inference_state["obj_id_to_idx"] = dict(zip(new_obj_ids, new_obj_inds))
1714
+ inference_state["obj_idx_to_id"] = dict(zip(new_obj_inds, new_obj_ids))
1715
+ inference_state["obj_ids"] = new_obj_ids
1716
+
1717
+ # Step 2: For per-object tensor storage, we shift their obj_idx in the dict keys.
1718
+ # (note that "consolidated_frame_inds" doesn't need to be updated in this step as
1719
+ # it's already handled in Step 0)
1720
+ def _map_keys(container):
1721
+ new_kvs = []
1722
+ for k in old_obj_inds:
1723
+ v = container.pop(k)
1724
+ if k in old_idx_to_new_idx:
1725
+ new_kvs.append((old_idx_to_new_idx[k], v))
1726
+ container.update(new_kvs)
1727
+
1728
+ _map_keys(inference_state["point_inputs_per_obj"])
1729
+ _map_keys(inference_state["mask_inputs_per_obj"])
1730
+ _map_keys(inference_state["output_dict_per_obj"])
1731
+ _map_keys(inference_state["temp_output_dict_per_obj"])
1732
+
1733
+ # Step 3: For packed tensor storage, we index the remaining ids and rebuild the per-object slices.
1734
+ def _slice_state(output_dict, storage_key):
1735
+ for frame_idx, out in output_dict[storage_key].items():
1736
+ out["maskmem_features"] = out["maskmem_features"][remain_old_obj_inds]
1737
+ out["maskmem_pos_enc"] = [x[remain_old_obj_inds] for x in out["maskmem_pos_enc"]]
1738
+ # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
1739
+ out["maskmem_pos_enc"] = self._get_maskmem_pos_enc(out["maskmem_pos_enc"], inference_state)
1740
+ out["pred_masks"] = out["pred_masks"][remain_old_obj_inds]
1741
+ out["obj_ptr"] = out["obj_ptr"][remain_old_obj_inds]
1742
+ out["object_score_logits"] = out["object_score_logits"][remain_old_obj_inds]
1743
+ # also update the per-object slices
1744
+ self._add_output_per_object(frame_idx, out, storage_key, inference_state=inference_state)
1745
+
1746
+ _slice_state(inference_state["output_dict"], "cond_frame_outputs")
1747
+ _slice_state(inference_state["output_dict"], "non_cond_frame_outputs")
1748
+
1749
+ return inference_state["obj_ids"]
1750
+
1751
+ @smart_inference_mode()
1752
+ def clear_all_points_in_frame(self, inference_state, frame_idx, obj_id):
1753
+ """Remove all input points or mask in a specific frame for a given object."""
1754
+ obj_idx = self._obj_id_to_idx(obj_id, inference_state)
1755
+
1756
+ # Clear the conditioning information on the given frame
1757
+ inference_state["point_inputs_per_obj"][obj_idx].pop(frame_idx, None)
1758
+ inference_state["mask_inputs_per_obj"][obj_idx].pop(frame_idx, None)
1759
+
1760
+ temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"]
1761
+ temp_output_dict_per_obj[obj_idx]["cond_frame_outputs"].pop(frame_idx, None)
1762
+ temp_output_dict_per_obj[obj_idx]["non_cond_frame_outputs"].pop(frame_idx, None)
1763
+
1764
+ # Check and see if there are still any inputs left on this frame
1765
+ batch_size = len(inference_state["obj_idx_to_id"])
1766
+ frame_has_input = False
1767
+ for obj_idx2 in range(batch_size):
1768
+ if frame_idx in inference_state["point_inputs_per_obj"][obj_idx2]:
1769
+ frame_has_input = True
1770
+ break
1771
+ if frame_idx in inference_state["mask_inputs_per_obj"][obj_idx2]:
1772
+ frame_has_input = True
1773
+ break
1774
+
1775
+ # If this frame has no remaining inputs for any objects, we further clear its
1776
+ # conditioning frame status
1777
+ if not frame_has_input:
1778
+ output_dict = inference_state["output_dict"]
1779
+ consolidated_frame_inds = inference_state["consolidated_frame_inds"]
1780
+ consolidated_frame_inds["cond_frame_outputs"].discard(frame_idx)
1781
+ consolidated_frame_inds["non_cond_frame_outputs"].discard(frame_idx)
1782
+ # Remove the frame's conditioning output (possibly downgrading it to non-conditioning)
1783
+ out = output_dict["cond_frame_outputs"].pop(frame_idx, None)
1784
+ if out is not None:
1785
+ # The frame is not a conditioning frame anymore since it's not receiving inputs,
1786
+ # so we "downgrade" its output (if exists) to a non-conditioning frame output.
1787
+ output_dict["non_cond_frame_outputs"][frame_idx] = out
1788
+ inference_state["frames_already_tracked"].pop(frame_idx, None)
1789
+ # Similarly, do it for the sliced output on each object.
1790
+ for obj_idx2 in range(batch_size):
1791
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx2]
1792
+ obj_out = obj_output_dict["cond_frame_outputs"].pop(frame_idx, None)
1793
+ if obj_out is not None:
1794
+ obj_output_dict["non_cond_frame_outputs"][frame_idx] = obj_out
1795
+
1796
+ # If all the conditioning frames have been removed, we also clear the tracking outputs
1797
+ if len(output_dict["cond_frame_outputs"]) == 0:
1798
+ self._reset_tracking_results(inference_state)
1799
+
1800
+ @smart_inference_mode()
1801
+ def clear_all_points_in_video(self, inference_state):
1802
+ """Remove all input points or mask in all frames throughout the video."""
1803
+ self._reset_tracking_results(inference_state)
1804
+ # Remove all object ids
1805
+ inference_state["obj_id_to_idx"].clear()
1806
+ inference_state["obj_idx_to_id"].clear()
1807
+ inference_state["obj_ids"].clear()
1808
+ inference_state["point_inputs_per_obj"].clear()
1809
+ inference_state["mask_inputs_per_obj"].clear()
1810
+ inference_state["output_dict_per_obj"].clear()
1811
+ inference_state["temp_output_dict_per_obj"].clear()
1812
+
1813
+ def _reset_tracking_results(self, inference_state):
1814
+ """Reset all tracking inputs and results across the videos."""
1815
+ for v in inference_state["point_inputs_per_obj"].values():
1816
+ v.clear()
1817
+ for v in inference_state["mask_inputs_per_obj"].values():
1818
+ v.clear()
1819
+ for v in inference_state["output_dict_per_obj"].values():
1820
+ v["cond_frame_outputs"].clear()
1821
+ v["non_cond_frame_outputs"].clear()
1822
+ for v in inference_state["temp_output_dict_per_obj"].values():
1823
+ v["cond_frame_outputs"].clear()
1824
+ v["non_cond_frame_outputs"].clear()
1825
+ inference_state["output_dict"]["cond_frame_outputs"].clear()
1826
+ inference_state["output_dict"]["non_cond_frame_outputs"].clear()
1827
+ inference_state["consolidated_frame_inds"]["cond_frame_outputs"].clear()
1828
+ inference_state["consolidated_frame_inds"]["non_cond_frame_outputs"].clear()
1829
+ inference_state["tracking_has_started"] = False
1830
+ inference_state["frames_already_tracked"].clear()
1831
+ inference_state["first_ann_frame_idx"] = None
1832
+
1658
1833
 
1659
1834
  class SAM2DynamicInteractivePredictor(SAM2Predictor):
1660
1835
  """SAM2DynamicInteractivePredictor extends SAM2Predictor to support dynamic interactions with video frames or a
@@ -1879,11 +2054,12 @@ class SAM2DynamicInteractivePredictor(SAM2Predictor):
1879
2054
  self.memory_bank.append(consolidated_out)
1880
2055
 
1881
2056
  def _prepare_memory_conditioned_features(self, obj_idx: int | None) -> torch.Tensor:
1882
- """Prepare the memory-conditioned features for the current image state. If obj_idx is provided, it supposes to
1883
- prepare features for a specific prompted object in the image. If obj_idx is None, it prepares features
1884
- for all objects in the image. If there is no memory, it will directly add a no-memory embedding to the
1885
- current vision features. If there is memory, it will use the memory features from previous frames to
1886
- condition the current vision features using a transformer attention mechanism.
2057
+ """Prepare memory-conditioned features for the current image state.
2058
+
2059
+ If ``obj_idx`` is provided, features are prepared for a specific prompted object in the image. If ``obj_idx`` is
2060
+ None, features are prepared for all objects. If no memory is available, a no-memory embedding is added to the
2061
+ current vision features. Otherwise, memory from previous frames is used to condition the current vision features
2062
+ via a transformer attention mechanism.
1887
2063
 
1888
2064
  Args:
1889
2065
  obj_idx (int | None): The index of the object for which to prepare the features.
@@ -1892,8 +2068,8 @@ class SAM2DynamicInteractivePredictor(SAM2Predictor):
1892
2068
  pix_feat_with_mem (torch.Tensor): The memory-conditioned pixel features.
1893
2069
  """
1894
2070
  if len(self.memory_bank) == 0 or isinstance(obj_idx, int):
1895
- # for initial conditioning frames with, encode them without using any previous memory
1896
- # directly add no-mem embedding (instead of using the transformer encoder)
2071
+ # For initial conditioning frames, encode without using any previous memory.
2072
+ # Directly add the no-memory embedding (instead of using the transformer encoder).
1897
2073
  pix_feat_with_mem = self.vision_feats[-1] + self.model.no_mem_embed
1898
2074
  else:
1899
2075
  # for inference frames, use the memory features from previous frames
@@ -1905,7 +2081,7 @@ class SAM2DynamicInteractivePredictor(SAM2Predictor):
1905
2081
  memory_pos=memory_pos_embed,
1906
2082
  num_obj_ptr_tokens=0, # num_obj_ptr_tokens
1907
2083
  )
1908
- # reshape the output (HW)BC => BCHW
2084
+ # Reshape output (HW)BC => BCHW
1909
2085
  return pix_feat_with_mem.permute(1, 2, 0).view(
1910
2086
  self._max_obj_num,
1911
2087
  self.model.memory_attention.d_model,
@@ -1969,9 +2145,9 @@ class SAM2DynamicInteractivePredictor(SAM2Predictor):
1969
2145
  pix_feat = pix_feat.view(-1, self.model.memory_attention.d_model, *self.feat_sizes[-1])
1970
2146
  _, _, _, low_res_masks, high_res_masks, obj_ptr, object_score_logits = self.model._use_mask_as_output(mask)
1971
2147
  else:
1972
- # fused the visual feature with previous memory features in the memory bank
2148
+ # Fuse visual features with previous memory features in the memory bank.
1973
2149
  pix_feat_with_mem = self._prepare_memory_conditioned_features(obj_idx)
1974
- # calculate the first feature if adding obj_idx exists(means adding prompts)
2150
+ # If ``obj_idx`` is provided (i.e., prompts are being added), keep only the first feature map.
1975
2151
  pix_feat_with_mem = pix_feat_with_mem[:1] if obj_idx is not None else pix_feat_with_mem
1976
2152
  _, _, _, low_res_masks, high_res_masks, obj_ptr, object_score_logits = self.model._forward_sam_heads(
1977
2153
  backbone_features=pix_feat_with_mem,
@@ -1986,3 +2162,1761 @@ class SAM2DynamicInteractivePredictor(SAM2Predictor):
1986
2162
  "obj_ptr": obj_ptr,
1987
2163
  "object_score_logits": object_score_logits,
1988
2164
  }
2165
+
2166
+
2167
+ class SAM3Predictor(SAM2Predictor):
2168
+ """Segment Anything Model 3 (SAM3) Interactive Predictor for image segmentation tasks."""
2169
+
2170
+ _bb_feat_sizes = [
2171
+ (288, 288),
2172
+ (144, 144),
2173
+ (72, 72),
2174
+ ]
2175
+ stride = 14
2176
+
2177
+ def setup_model(self, model=None, verbose=True):
2178
+ """Setup the SAM3 model with appropriate mean and standard deviation for preprocessing."""
2179
+ super().setup_model(model, verbose)
2180
+ # update mean and std
2181
+ self.mean = torch.tensor([127.5, 127.5, 127.5]).view(-1, 1, 1).to(self.device)
2182
+ self.std = torch.tensor([127.5, 127.5, 127.5]).view(-1, 1, 1).to(self.device)
2183
+
2184
+ def get_model(self):
2185
+ """Retrieve and initialize the Segment Anything Model 3 (SAM3) for image segmentation tasks."""
2186
+ from .build_sam3 import build_interactive_sam3 # slow import
2187
+
2188
+ return build_interactive_sam3(self.args.model, compile=self.args.compile)
2189
+
2190
+
2191
+ class SAM3SemanticPredictor(SAM3Predictor):
2192
+ """Segment Anything Model 3 (SAM3) Predictor for image segmentation tasks."""
2193
+
2194
+ def get_model(self):
2195
+ """Retrieve and initialize the Segment Anything Model 3 (SAM3) for image segmentation tasks."""
2196
+ from .build_sam3 import build_sam3_image_model # slow import
2197
+
2198
+ return build_sam3_image_model(self.args.model, compile=self.args.compile)
2199
+
2200
+ @smart_inference_mode()
2201
+ def get_im_features(self, im):
2202
+ """Extract image features using the model's backbone."""
2203
+ return self.model.backbone.forward_image(im)
2204
+
2205
+ def pre_transform(self, im):
2206
+ """Perform initial transformations on the input image for preprocessing.
2207
+
2208
+ This method applies transformations such as resizing to prepare the image for further preprocessing. Currently,
2209
+ batched inference is not supported; hence the list length should be 1.
2210
+
2211
+ Args:
2212
+ im (list[np.ndarray]): List containing a single image in HWC numpy array format.
2213
+
2214
+ Returns:
2215
+ (list[np.ndarray]): List containing the transformed image.
2216
+
2217
+ Raises:
2218
+ AssertionError: If the input list contains more than one image.
2219
+
2220
+ Examples:
2221
+ >>> predictor = Predictor()
2222
+ >>> image = np.random.rand(480, 640, 3) # Single HWC image
2223
+ >>> transformed = predictor.pre_transform([image])
2224
+ >>> print(len(transformed))
2225
+ 1
2226
+ """
2227
+ assert len(im) == 1, "SAM model does not currently support batched inference"
2228
+ letterbox = LetterBox(self.imgsz, auto=False, center=False, scale_fill=True) # hardcode here for sam3
2229
+ return [letterbox(image=x) for x in im]
2230
+
2231
+ def _prepare_geometric_prompts(self, src_shape, bboxes=None, labels=None):
2232
+ """Prepare prompts by normalizing bounding boxes and points to the destination shape."""
2233
+ if bboxes is not None:
2234
+ bboxes = torch.as_tensor(bboxes, dtype=self.torch_dtype, device=self.device)
2235
+ bboxes = bboxes[None] if bboxes.ndim == 1 else bboxes
2236
+ # needs xywh as input
2237
+ bboxes = ops.xyxy2xywh(bboxes)
2238
+ bboxes[:, 0::2] /= src_shape[1]
2239
+ bboxes[:, 1::2] /= src_shape[0]
2240
+ # Assuming labels are all positive if users don't pass labels.
2241
+ if labels is None:
2242
+ labels = np.ones(bboxes.shape[:-1])
2243
+ labels = torch.as_tensor(labels, dtype=torch.int32, device=self.device)
2244
+ assert bboxes.shape[-2] == labels.shape[-1], (
2245
+ f"Number of points {bboxes.shape[-2]} should match number of labels {labels.shape[-1]}."
2246
+ )
2247
+ bboxes = bboxes.view(-1, 1, 4) # (N, 1, 4)
2248
+ labels = labels.view(-1, 1) # (N, 1)
2249
+ return bboxes, labels
2250
+
2251
+ def _inference_features(self, features, bboxes=None, labels=None, text: list[str] | None = None):
2252
+ """Run inference on the extracted features with optional bounding boxes and labels."""
2253
+ # NOTE: priority: bboxes > text > pre-set classes
2254
+ nc = 1 if bboxes is not None else len(text) if text is not None else len(self.model.names)
2255
+ geometric_prompt = self._get_dummy_prompt(nc)
2256
+ if bboxes is not None:
2257
+ for i in range(len(bboxes)):
2258
+ geometric_prompt.append_boxes(bboxes[[i]], labels[[i]])
2259
+ if text is None:
2260
+ text = ["visual"] # bboxes needs this `visual` text prompt if no text passed
2261
+ if text is not None and self.model.names != text:
2262
+ self.model.set_classes(text=text)
2263
+ outputs = self.model.forward_grounding(
2264
+ backbone_out=features,
2265
+ text_ids=torch.arange(nc, device=self.device, dtype=torch.long),
2266
+ geometric_prompt=geometric_prompt,
2267
+ )
2268
+ return outputs
2269
+
2270
+ def postprocess(self, preds, img, orig_imgs):
2271
+ """Post-process the predictions to apply non-overlapping constraints if required."""
2272
+ pred_boxes = preds["pred_boxes"] # (nc, num_query, 4)
2273
+ pred_logits = preds["pred_logits"]
2274
+ pred_masks = preds["pred_masks"]
2275
+ pred_scores = pred_logits.sigmoid()
2276
+ presence_score = preds["presence_logit_dec"].sigmoid().unsqueeze(1)
2277
+ pred_scores = (pred_scores * presence_score).squeeze(-1)
2278
+ pred_cls = torch.tensor(
2279
+ list(range(pred_scores.shape[0])),
2280
+ dtype=pred_scores.dtype,
2281
+ device=pred_scores.device,
2282
+ )[:, None].expand_as(pred_scores)
2283
+ pred_boxes = torch.cat([pred_boxes, pred_scores[..., None], pred_cls[..., None]], dim=-1)
2284
+
2285
+ keep = pred_scores > self.args.conf
2286
+ pred_masks = pred_masks[keep]
2287
+ pred_boxes = pred_boxes[keep]
2288
+ pred_boxes[:, :4] = ops.xywh2xyxy(pred_boxes[:, :4])
2289
+
2290
+ names = getattr(self.model, "names", [str(i) for i in range(pred_scores.shape[0])])
2291
+ if not isinstance(orig_imgs, list): # input images are a torch.Tensor, not a list
2292
+ orig_imgs = ops.convert_torch2numpy_batch(orig_imgs)
2293
+ results = []
2294
+ for masks, boxes, orig_img, img_path in zip([pred_masks], [pred_boxes], orig_imgs, self.batch[0]):
2295
+ if masks.shape[0] == 0:
2296
+ masks, boxes = None, torch.zeros((0, 6), device=pred_masks.device)
2297
+ else:
2298
+ masks = F.interpolate(masks.float()[None], orig_img.shape[:2], mode="bilinear")[0] > 0.5
2299
+ boxes[..., [0, 2]] *= orig_img.shape[1]
2300
+ boxes[..., [1, 3]] *= orig_img.shape[0]
2301
+ results.append(Results(orig_img, path=img_path, names=names, masks=masks, boxes=boxes))
2302
+ return results
2303
+
2304
+ def inference(self, im, bboxes=None, labels=None, text: list[str] | None = None, *args, **kwargs):
2305
+ """Perform inference on a single image with optional prompts."""
2306
+ bboxes = self.prompts.pop("bboxes", bboxes)
2307
+ labels = self.prompts.pop("labels", labels)
2308
+ text = self.prompts.pop("text", text)
2309
+ features = self.get_im_features(im) if self.features is None else self.features
2310
+ prompts = self._prepare_geometric_prompts(self.batch[1][0].shape[:2], bboxes, labels)
2311
+ return self._inference_features(features, *prompts, text=text)
2312
+
2313
+ @smart_inference_mode()
2314
+ def inference_features(
2315
+ self,
2316
+ features,
2317
+ src_shape,
2318
+ bboxes=None,
2319
+ labels=None,
2320
+ text: list[str] | None = None,
2321
+ ):
2322
+ """Perform prompts preprocessing and inference on provided image features using the SAM model.
2323
+
2324
+ Args:
2325
+ features (dict[str, Any]): Extracted image features from the SAM3 model image encoder.
2326
+ src_shape (tuple[int, int]): The source shape (height, width) of the input image.
2327
+ bboxes (np.ndarray | list[list[float]] | None): Bounding boxes in xyxy format with shape (N, 4). pixels.
2328
+ labels (np.ndarray | list[int] | None): Point prompt labels with shape (N, ).
2329
+ text (list[str] | None): List of text prompts corresponding to the classes.
2330
+
2331
+ Returns:
2332
+ pred_masks (torch.Tensor): The output masks in shape (C, H, W), where C is the number of generated masks.
2333
+ pred_bboxes (torch.Tensor): Bounding boxes for each mask with shape (N, 6), where N is the number of boxes.
2334
+ Each box is in xyxy format with additional columns for score and class.
2335
+
2336
+ Notes:
2337
+ - The input features is a torch.Tensor of shape (B, C, H, W) if performing on SAM, or a dict[str, Any] if performing on SAM2.
2338
+ """
2339
+ prompts = self._prepare_geometric_prompts(src_shape[:2], bboxes, labels)
2340
+ preds = self._inference_features(features, *prompts, text=text)
2341
+ pred_boxes = preds["pred_boxes"] # (nc, num_query, 4)
2342
+ pred_logits = preds["pred_logits"]
2343
+ pred_masks = preds["pred_masks"]
2344
+ pred_scores = pred_logits.sigmoid()
2345
+ presence_score = preds["presence_logit_dec"].sigmoid().unsqueeze(1)
2346
+ pred_scores = (pred_scores * presence_score).squeeze(-1)
2347
+ pred_cls = torch.tensor(
2348
+ list(range(pred_scores.shape[0])),
2349
+ dtype=pred_scores.dtype,
2350
+ device=pred_scores.device,
2351
+ )[:, None].expand_as(pred_scores)
2352
+ pred_boxes = torch.cat([pred_boxes, pred_scores[..., None], pred_cls[..., None]], dim=-1)
2353
+
2354
+ keep = pred_scores > self.args.conf
2355
+ pred_masks = pred_masks[keep]
2356
+ pred_boxes = pred_boxes[keep]
2357
+ pred_boxes[:, :4] = ops.xywh2xyxy(pred_boxes[:, :4])
2358
+
2359
+ if pred_masks.shape[0] == 0:
2360
+ pred_masks, pred_boxes = None, torch.zeros((0, 6), device=pred_masks.device)
2361
+ else:
2362
+ pred_masks = F.interpolate(pred_masks.float()[None], src_shape[:2], mode="bilinear")[0] > 0.5
2363
+ pred_boxes[..., 0] *= src_shape[1]
2364
+ pred_boxes[..., 1] *= src_shape[0]
2365
+ pred_boxes[..., 2] *= src_shape[1]
2366
+ pred_boxes[..., 3] *= src_shape[0]
2367
+ return pred_masks, pred_boxes
2368
+
2369
+ def reset_prompts(self):
2370
+ """Reset the prompts for the predictor."""
2371
+ self.prompts = {}
2372
+ self.model.text_embeddings = {}
2373
+
2374
+ def _get_dummy_prompt(self, num_prompts=1):
2375
+ """Get a dummy geometric prompt with zero boxes."""
2376
+ geometric_prompt = Prompt(
2377
+ box_embeddings=torch.zeros(0, num_prompts, 4, device=self.device),
2378
+ box_mask=torch.zeros(num_prompts, 0, device=self.device, dtype=torch.bool),
2379
+ )
2380
+ return geometric_prompt
2381
+
2382
+
2383
+ class SAM3VideoPredictor(SAM2VideoPredictor, SAM3Predictor):
2384
+ """Segment Anything Model 3 (SAM3) Video Predictor for video segmentation tasks."""
2385
+
2386
+ def propagate_in_video(self, inference_state, frame_idx):
2387
+ """Perform image segmentation inference based on the given input cues, using the currently loaded image. This
2388
+ method leverages SAM's (Segment Anything Model) architecture consisting of image encoder, prompt
2389
+ encoder, and mask decoder for real-time and promptable segmentation tasks.
2390
+
2391
+ Args:
2392
+ inference_state (dict): The current state of inference, including input cues and previous outputs.
2393
+ frame_idx (int): The index of the current frame in the video sequence.
2394
+ """
2395
+ frame = frame_idx
2396
+ output_dict = inference_state["output_dict"]
2397
+ obj_ids = inference_state["obj_ids"]
2398
+ consolidated_frame_inds = inference_state["consolidated_frame_inds"]
2399
+ batch_size = len(inference_state["obj_idx_to_id"])
2400
+ if len(output_dict["cond_frame_outputs"]) == 0:
2401
+ raise RuntimeError("No points are provided; please add points first")
2402
+
2403
+ if frame in consolidated_frame_inds["cond_frame_outputs"]:
2404
+ storage_key = "cond_frame_outputs"
2405
+ current_out = output_dict[storage_key][frame]
2406
+ if self.clear_non_cond_mem_around_input and (self.clear_non_cond_mem_for_multi_obj or batch_size <= 1):
2407
+ # clear non-conditioning memory of the surrounding frames
2408
+ self._clear_non_cond_mem_around_input(frame)
2409
+ elif frame in consolidated_frame_inds["non_cond_frame_outputs"]:
2410
+ storage_key = "non_cond_frame_outputs"
2411
+ current_out = output_dict[storage_key][frame]
2412
+ else:
2413
+ storage_key = "non_cond_frame_outputs"
2414
+ current_out = self._run_single_frame_inference(
2415
+ output_dict=output_dict,
2416
+ frame_idx=frame,
2417
+ batch_size=batch_size,
2418
+ is_init_cond_frame=False,
2419
+ point_inputs=None,
2420
+ mask_inputs=None,
2421
+ reverse=False,
2422
+ run_mem_encoder=True,
2423
+ inference_state=inference_state,
2424
+ )
2425
+ output_dict[storage_key][frame] = current_out
2426
+ # Create slices of per-object outputs for subsequent interaction with each
2427
+ # individual object after tracking.
2428
+ self._add_output_per_object(frame, current_out, storage_key, inference_state=inference_state)
2429
+ inference_state["frames_already_tracked"].append(frame)
2430
+ pred_masks = current_out["pred_masks"].flatten(0, 1)
2431
+ obj_scores = current_out["object_score_logits"]
2432
+
2433
+ return obj_ids, pred_masks, obj_scores
2434
+
2435
+
2436
+ class SAM3VideoSemanticPredictor(SAM3SemanticPredictor):
2437
+ """Segment Anything Model 3 (SAM3) Video Semantic Predictor."""
2438
+
2439
+ HIGH_CONF_THRESH = 0.8
2440
+ HIGH_IOU_THRESH = 0.8
2441
+ NO_OBJ_LOGIT = -10.0
2442
+ NEVER_OCCLUDED = -1
2443
+ ALWAYS_OCCLUDED = 100000
2444
+
2445
+ UNCONFIRMED = 1 # newly added masklet, not confirmed by any detection yet
2446
+ CONFIRMED = 2 # confirmed by at least one detection
2447
+ _bb_feat_sizes = [
2448
+ (288, 288),
2449
+ (144, 144),
2450
+ (72, 72),
2451
+ ]
2452
+ stride = 14
2453
+
2454
+ def __init__(
2455
+ self,
2456
+ cfg=DEFAULT_CFG,
2457
+ overrides=None,
2458
+ _callbacks=None,
2459
+ # prob threshold for detection outputs -- only keep detections above this threshold
2460
+ # enters NMS and det-to-track matching
2461
+ score_threshold_detection=0.5,
2462
+ # IoU threshold for detection NMS
2463
+ det_nms_thresh=0.0,
2464
+ # IoU threshold for det-to-track matching -- a detection is considered "matched" to a tracklet it
2465
+ # overlaps with a tracklet above this threshold -- it is often a loose threshold like 0.1
2466
+ assoc_iou_thresh=0.5,
2467
+ # IoU threshold for det-to-track matching, which is used to determine whether a masklet is "unmatched"
2468
+ # by any detections -- it is often a stricter threshold like 0.5
2469
+ trk_assoc_iou_thresh=0.5,
2470
+ # prob threshold for a detection to be added as a new object
2471
+ new_det_thresh=0.0,
2472
+ # hotstart parameters: we hold off the outputs for `hotstart_delay` frames and
2473
+ # 1) remove those tracklets unmatched by any detections based on `hotstart_unmatch_thresh`
2474
+ # 2) remove those tracklets overlapping with one another based on `hotstart_dup_thresh`
2475
+ hotstart_delay=0,
2476
+ hotstart_unmatch_thresh=3,
2477
+ hotstart_dup_thresh=3,
2478
+ # Whether to suppress masks only within hotstart. If False, we can suppress masks even if they start before hotstart period.
2479
+ suppress_unmatched_only_within_hotstart=True,
2480
+ init_trk_keep_alive=0,
2481
+ max_trk_keep_alive=8,
2482
+ min_trk_keep_alive=-4,
2483
+ # Threshold for suppressing overlapping objects based on recent occlusion
2484
+ suppress_overlapping_based_on_recent_occlusion_threshold=0.0,
2485
+ decrease_trk_keep_alive_for_empty_masklets=False,
2486
+ o2o_matching_masklets_enable=False, # Enable hungarian matching to match existing masklets
2487
+ suppress_det_close_to_boundary=False,
2488
+ fill_hole_area=16,
2489
+ # The maximum number of objects (masklets) to track across all GPUs (for no limit, set it to -1)
2490
+ max_num_objects=-1,
2491
+ recondition_every_nth_frame=-1,
2492
+ # masket confirmation status (to suppress unconfirmed masklets)
2493
+ masklet_confirmation_enable=False,
2494
+ # a masklet is confirmed after being consecutively detected and matched for
2495
+ # `masklet_confirmation_consecutive_det_thresh`
2496
+ masklet_confirmation_consecutive_det_thresh=3,
2497
+ # bbox heuristic parameters
2498
+ reconstruction_bbox_iou_thresh=0.0,
2499
+ reconstruction_bbox_det_score=0.0,
2500
+ ):
2501
+ """Initialize the SAM3VideoSemanticPredictor with configuration and optional overrides."""
2502
+ super().__init__(cfg, overrides, _callbacks)
2503
+ self.score_threshold_detection = score_threshold_detection
2504
+ self.det_nms_thresh = det_nms_thresh
2505
+ self.assoc_iou_thresh = assoc_iou_thresh
2506
+ self.trk_assoc_iou_thresh = trk_assoc_iou_thresh
2507
+ self.new_det_thresh = new_det_thresh
2508
+
2509
+ # hotstart parameters
2510
+ if hotstart_delay > 0:
2511
+ assert hotstart_unmatch_thresh <= hotstart_delay
2512
+ assert hotstart_dup_thresh <= hotstart_delay
2513
+ self.hotstart_delay = hotstart_delay
2514
+ self.hotstart_unmatch_thresh = hotstart_unmatch_thresh
2515
+ self.hotstart_dup_thresh = hotstart_dup_thresh
2516
+ self.suppress_unmatched_only_within_hotstart = suppress_unmatched_only_within_hotstart
2517
+ self.init_trk_keep_alive = init_trk_keep_alive
2518
+ self.max_trk_keep_alive = max_trk_keep_alive
2519
+ self.min_trk_keep_alive = min_trk_keep_alive
2520
+ self.suppress_overlapping_based_on_recent_occlusion_threshold = (
2521
+ suppress_overlapping_based_on_recent_occlusion_threshold
2522
+ )
2523
+ self.suppress_det_close_to_boundary = suppress_det_close_to_boundary
2524
+ self.decrease_trk_keep_alive_for_empty_masklets = decrease_trk_keep_alive_for_empty_masklets
2525
+ self.o2o_matching_masklets_enable = o2o_matching_masklets_enable
2526
+ self.fill_hole_area = fill_hole_area
2527
+ self._dist_pg_cpu = None # CPU process group (lazy-initialized on first use)
2528
+
2529
+ max_num_objects = 10000 # no limit
2530
+ num_obj_for_compile = 16
2531
+ self.max_num_objects = max_num_objects
2532
+ self.num_obj_for_compile = num_obj_for_compile
2533
+ self.recondition_every_nth_frame = recondition_every_nth_frame
2534
+ self.masklet_confirmation_enable = masklet_confirmation_enable
2535
+ self.masklet_confirmation_consecutive_det_thresh = masklet_confirmation_consecutive_det_thresh
2536
+ self.reconstruction_bbox_iou_thresh = reconstruction_bbox_iou_thresh
2537
+ self.reconstruction_bbox_det_score = reconstruction_bbox_det_score
2538
+
2539
+ # build SAM3 tracker
2540
+ self.tracker = SAM3VideoPredictor(overrides=overrides)
2541
+
2542
+ self.inference_state = {}
2543
+ self.callbacks["on_predict_start"].append(self.init_state)
2544
+
2545
+ def setup_model(self, model=None, verbose=True):
2546
+ """Setup the SAM3VideoSemanticPredictor model."""
2547
+ super().setup_model(model, verbose)
2548
+ from .build_sam3 import build_interactive_sam3
2549
+
2550
+ # Initialize the SAM3 tracker model without backbone (backbone is handled in the detector)
2551
+ model = build_interactive_sam3(self.args.model, with_backbone=False)
2552
+ self.tracker.setup_model(model=model, verbose=False)
2553
+
2554
+ def setup_source(self, source):
2555
+ """Setup the source for the SAM3VideoSemanticPredictor model."""
2556
+ super().setup_source(source)
2557
+ self.tracker.imgsz = self.imgsz
2558
+ self.tracker.model.set_imgsz(self.imgsz)
2559
+ self.tracker._bb_feat_sizes = [[int(x / (self.stride * i)) for x in self.imgsz] for i in [1 / 4, 1 / 2, 1]]
2560
+ self.interpol_size = self.tracker.model.memory_encoder.mask_downsampler.interpol_size
2561
+
2562
+ @staticmethod
2563
+ def init_state(predictor):
2564
+ """Initialize an inference state for the predictor.
2565
+
2566
+ This function sets up the initial state required for performing inference on video data. It includes
2567
+ initializing various dictionaries and ordered dictionaries that will store inputs, outputs, and other metadata
2568
+ relevant to the tracking process.
2569
+
2570
+ Args:
2571
+ predictor (SAM3VideoSemanticPredictor): The predictor object for which to initialize the state.
2572
+ """
2573
+ if len(predictor.inference_state) > 0: # means initialized
2574
+ return
2575
+ assert predictor.dataset is not None
2576
+ assert predictor.dataset.mode == "video"
2577
+ num_frames = predictor.dataset.frames
2578
+ inference_state = {
2579
+ "num_frames": num_frames,
2580
+ "tracker_inference_states": [],
2581
+ "tracker_metadata": {},
2582
+ }
2583
+ inference_state["text_prompt"] = None
2584
+ inference_state["per_frame_geometric_prompt"] = [None] * num_frames
2585
+ predictor.inference_state = inference_state
2586
+
2587
+ def inference(self, im, bboxes=None, labels=None, text: list[str] | None = None, *args, **kwargs):
2588
+ """Perform inference on a video sequence with optional prompts."""
2589
+ frame = self.dataset.frame - 1 # align frame index to be 0-based
2590
+ self.inference_state["im"] = im # only pass image for subsequent frames
2591
+ if "text_ids" not in self.inference_state: # first frame processing
2592
+ self.add_prompt(frame_idx=frame, text=text, bboxes=bboxes, labels=labels)
2593
+ return self._run_single_frame_inference(frame, reverse=False)
2594
+
2595
+ def postprocess(self, preds, img, orig_imgs):
2596
+ """Post-process the predictions to apply non-overlapping constraints if required."""
2597
+ obj_id_to_mask = preds["obj_id_to_mask"] # low res masks
2598
+ curr_obj_ids = sorted(obj_id_to_mask.keys())
2599
+ if not isinstance(orig_imgs, list): # input images are a torch.Tensor, not a list
2600
+ orig_imgs = ops.convert_torch2numpy_batch(orig_imgs)
2601
+
2602
+ if len(curr_obj_ids) == 0:
2603
+ pred_masks, pred_boxes = None, torch.zeros((0, 7), device=self.device)
2604
+ else:
2605
+ pred_masks = torch.cat([obj_id_to_mask[obj_id] for obj_id in curr_obj_ids], dim=0)
2606
+ pred_masks = F.interpolate(pred_masks.float()[None], orig_imgs[0].shape[:2], mode="bilinear")[0] > 0.5
2607
+ pred_ids = torch.tensor(curr_obj_ids, dtype=torch.int32, device=pred_masks.device)
2608
+ pred_scores = torch.tensor(
2609
+ [preds["obj_id_to_score"][obj_id] for obj_id in curr_obj_ids], device=pred_masks.device
2610
+ )
2611
+ pred_cls = torch.tensor(
2612
+ [preds["obj_id_to_cls"][obj_id] for obj_id in curr_obj_ids], device=pred_masks.device
2613
+ )
2614
+ keep = (pred_scores > self.args.conf) & pred_masks.any(dim=(1, 2))
2615
+ pred_masks = pred_masks[keep]
2616
+ pred_boxes = batched_mask_to_box(pred_masks)
2617
+ pred_boxes = torch.cat(
2618
+ [pred_boxes, pred_ids[keep][:, None], pred_scores[keep][..., None], pred_cls[keep][..., None]], dim=-1
2619
+ )
2620
+ if pred_masks.shape[0] > 1:
2621
+ tracker_scores = torch.tensor(
2622
+ [
2623
+ (
2624
+ preds["obj_id_to_tracker_score"][obj_id]
2625
+ if obj_id in preds["obj_id_to_tracker_score"]
2626
+ else 0.0
2627
+ )
2628
+ for obj_id in curr_obj_ids
2629
+ ],
2630
+ device=pred_masks.device,
2631
+ )[keep]
2632
+ pred_masks = (
2633
+ self._apply_object_wise_non_overlapping_constraints(
2634
+ pred_masks.unsqueeze(1),
2635
+ tracker_scores.unsqueeze(1),
2636
+ background_value=0,
2637
+ ).squeeze(1)
2638
+ ) > 0
2639
+
2640
+ # names = getattr(self.model, "names", [str(i) for i in range(pred_scores.shape[0])])
2641
+ names = dict(enumerate(str(i) for i in range(pred_masks.shape[0])))
2642
+ results = []
2643
+ for masks, boxes, orig_img, img_path in zip([pred_masks], [pred_boxes], orig_imgs, self.batch[0]):
2644
+ results.append(Results(orig_img, path=img_path, names=names, masks=masks, boxes=boxes))
2645
+ return results
2646
+
2647
+ def _run_single_frame_inference(self, frame_idx, reverse=False, inference_state=None):
2648
+ """Perform inference on a single frame and get its inference results."""
2649
+ inference_state = inference_state or self.inference_state
2650
+ # prepare inputs
2651
+ tracker_states_local = inference_state["tracker_inference_states"]
2652
+ has_text_prompt = inference_state["text_prompt"] is not None
2653
+ has_geometric_prompt = inference_state["per_frame_geometric_prompt"][frame_idx] is not None
2654
+ # run inference for the current frame
2655
+ (
2656
+ obj_id_to_mask,
2657
+ obj_id_to_score,
2658
+ obj_id_to_cls,
2659
+ tracker_states_local_new,
2660
+ tracker_metadata_new,
2661
+ frame_stats,
2662
+ _,
2663
+ ) = self._det_track_one_frame(
2664
+ frame_idx=frame_idx,
2665
+ num_frames=inference_state["num_frames"],
2666
+ reverse=reverse,
2667
+ im=inference_state["im"],
2668
+ text_ids=inference_state["text_ids"],
2669
+ geometric_prompt=(
2670
+ self._get_dummy_prompt(num_prompts=len(inference_state["text_ids"]))
2671
+ if not has_geometric_prompt
2672
+ else inference_state["per_frame_geometric_prompt"][frame_idx]
2673
+ ),
2674
+ tracker_states_local=tracker_states_local,
2675
+ tracker_metadata_prev=inference_state["tracker_metadata"],
2676
+ allow_new_detections=has_text_prompt or has_geometric_prompt,
2677
+ )
2678
+ # update inference state
2679
+ inference_state["tracker_inference_states"] = tracker_states_local_new
2680
+ inference_state["tracker_metadata"] = tracker_metadata_new
2681
+
2682
+ out = {
2683
+ "obj_id_to_mask": obj_id_to_mask,
2684
+ "obj_id_to_score": obj_id_to_score, # first frame detection score
2685
+ "obj_id_to_cls": obj_id_to_cls, # first frame detection score
2686
+ "obj_id_to_tracker_score": tracker_metadata_new["obj_id_to_tracker_score_frame_wise"][frame_idx],
2687
+ }
2688
+ # removed_obj_ids is only needed on rank 0 to handle hotstart delay buffer
2689
+ metadata = tracker_metadata_new["metadata"]
2690
+ removed_obj_ids = metadata["removed_obj_ids"]
2691
+ out["removed_obj_ids"] = removed_obj_ids
2692
+ out["suppressed_obj_ids"] = metadata["suppressed_obj_ids"][frame_idx]
2693
+ out["frame_stats"] = frame_stats
2694
+ if self.masklet_confirmation_enable:
2695
+ status = metadata["masklet_confirmation"]["status"]
2696
+ is_unconfirmed = status == self.UNCONFIRMED
2697
+ out["unconfirmed_obj_ids"] = tracker_metadata_new["obj_ids_all_gpu"][is_unconfirmed].tolist()
2698
+ else:
2699
+ out["unconfirmed_obj_ids"] = []
2700
+ return out
2701
+
2702
+ @smart_inference_mode()
2703
+ def add_prompt(
2704
+ self,
2705
+ frame_idx,
2706
+ text=None,
2707
+ bboxes=None,
2708
+ labels=None,
2709
+ inference_state=None,
2710
+ ):
2711
+ """Add text, point or box prompts on a single frame. This method returns the inference outputs only on the
2712
+ prompted frame.
2713
+
2714
+ Note that text prompts are NOT associated with a particular frame (i.e. they apply
2715
+ to all frames). However, we only run inference on the frame specified in `frame_idx`.
2716
+ """
2717
+ inference_state = inference_state or self.inference_state
2718
+ assert text is not None or bboxes is not None, "at least one type of prompt (text, boxes) must be provided"
2719
+
2720
+ # 1) handle text prompt
2721
+ use_text = text is not None
2722
+ text = text if use_text else "visual"
2723
+ text_batch = [text] if isinstance(text, str) else text
2724
+ inference_state["text_prompt"] = text if use_text else None
2725
+ n = len(text_batch)
2726
+ text_ids = torch.arange(n, device=self.device, dtype=torch.long)
2727
+ inference_state["text_ids"] = text_ids
2728
+ if text is not None and self.model.names != text:
2729
+ self.model.set_classes(text=text)
2730
+
2731
+ # 2) handle box prompt
2732
+ bboxes, labels = self._prepare_geometric_prompts(self.batch[1][0].shape[:2], bboxes, labels)
2733
+ assert (bboxes is not None) == (labels is not None)
2734
+ geometric_prompt = self._get_dummy_prompt(num_prompts=n)
2735
+ if bboxes is not None:
2736
+ for i in range(len(bboxes)):
2737
+ geometric_prompt.append_boxes(bboxes[[i]], labels[[i]])
2738
+ inference_state["per_frame_geometric_prompt"][frame_idx] = geometric_prompt
2739
+ out = self._run_single_frame_inference(frame_idx, reverse=False, inference_state=inference_state)
2740
+ return frame_idx, out
2741
+
2742
+ def _apply_object_wise_non_overlapping_constraints(self, pred_masks, obj_scores, background_value=-10.0):
2743
+ """Applies non-overlapping constraints object wise (i.e. only one object can claim the overlapping region)."""
2744
+ # Replace pixel scores with object scores
2745
+ pred_masks_single_score = torch.where(pred_masks > 0, obj_scores[..., None, None], background_value)
2746
+ # Apply pixel-wise non-overlapping constraint based on mask scores
2747
+ pixel_level_non_overlapping_masks = self.tracker.model._apply_non_overlapping_constraints(
2748
+ pred_masks_single_score
2749
+ )
2750
+ # Replace object scores with pixel scores. Note, that now only one object can claim the overlapping region
2751
+ pred_masks = torch.where(
2752
+ pixel_level_non_overlapping_masks > 0,
2753
+ pred_masks,
2754
+ torch.clamp(pred_masks, max=background_value),
2755
+ )
2756
+ return pred_masks
2757
+
2758
+ def _det_track_one_frame(
2759
+ self,
2760
+ im: torch.Tensor,
2761
+ text_ids: torch.Tensor,
2762
+ frame_idx: int,
2763
+ num_frames: int,
2764
+ reverse: bool,
2765
+ geometric_prompt: Prompt,
2766
+ tracker_states_local: list[Any],
2767
+ tracker_metadata_prev: dict[str, Any],
2768
+ allow_new_detections: bool = True,
2769
+ ):
2770
+ """This function handles one-step inference for the DenseTracking model in an SPMD manner. At a high-level, all
2771
+ GPUs execute the same function calls as if it's done on a single GPU, while under the hood, some
2772
+ function calls involve distributed computation based on sharded SAM2 states.
2773
+
2774
+ - `input_batch` contains image and other inputs on the entire video; it should be identical across GPUs
2775
+ - `tracker_states_local` holds the local masklet information in this GPU shard
2776
+ - `tracker_metadata_prev` manages the metadata for SAM2 objects, such as which masklet is hold on which GPUs
2777
+ it contains both global and local masklet information
2778
+ """
2779
+ # Step 1: run backbone and detector in a distributed manner -- this is done via Sam3ImageOnVideoMultiGPU,
2780
+ # a MultiGPU model (assigned to `self.detector`) that shards frames in a round-robin manner.
2781
+ det_out = self.run_backbone_and_detection(
2782
+ im=im,
2783
+ text_ids=text_ids,
2784
+ geometric_prompt=geometric_prompt,
2785
+ allow_new_detections=allow_new_detections,
2786
+ )
2787
+
2788
+ # Step 2: each GPU propagates its local SAM2 states to get the SAM2 prediction masks.
2789
+ # the returned `tracker_low_res_masks_global` contains the concatenated masklet predictions
2790
+ # gathered from all GPUs (as if they are propagated on a single GPU). Note that this step only
2791
+ # runs the SAM2 propagation step, but doesn't encode new memory for the predicted masks;
2792
+ # we defer memory encoding to `run_tracker_update_execution_phase` after resolving all heuristics.
2793
+ if tracker_metadata_prev == {}:
2794
+ # initialize masklet metadata if it's uninitialized (empty dict)
2795
+ tracker_metadata_prev.update(self._initialize_metadata())
2796
+ tracker_low_res_masks_global, tracker_obj_scores_global = self.run_tracker_propagation(
2797
+ frame_idx=frame_idx,
2798
+ tracker_states_local=tracker_states_local,
2799
+ tracker_metadata_prev=tracker_metadata_prev,
2800
+ )
2801
+
2802
+ # Step 3: based on detection outputs and the propagated SAM2 prediction masks, we make plans
2803
+ # for SAM2 masklet updates (i.e. which objects to add and remove, how to load-balance them, etc).
2804
+ # We also run SAM2 memory encoder globally in this step to resolve non-overlapping constraints.
2805
+ # **This step should involve all the heuristics needed for any updates.** Most of the update
2806
+ # planning will be done on the master rank (GPU 0) and the resulting plan `tracker_update_plan` is
2807
+ # broadcasted to other GPUs (to be executed in a distributed manner). This step also generates the
2808
+ # new masklet metadata `tracker_metadata_new` (based on its previous version `tracker_metadata_prev`).
2809
+ tracker_update_plan, tracker_metadata_new = self.run_tracker_update_planning_phase(
2810
+ frame_idx=frame_idx,
2811
+ reverse=reverse,
2812
+ det_out=det_out,
2813
+ tracker_low_res_masks_global=tracker_low_res_masks_global,
2814
+ tracker_obj_scores_global=tracker_obj_scores_global,
2815
+ tracker_metadata_prev=tracker_metadata_prev,
2816
+ tracker_states_local=tracker_states_local,
2817
+ )
2818
+
2819
+ # Get reconditioning info from the update plan
2820
+ reconditioned_obj_ids = tracker_update_plan.get("reconditioned_obj_ids", set())
2821
+
2822
+ # Step 4: based on `tracker_update_plan`, each GPU executes the update w.r.t. its local SAM2 inference states
2823
+ tracker_states_local_new = self.run_tracker_update_execution_phase(
2824
+ frame_idx=frame_idx,
2825
+ num_frames=num_frames,
2826
+ det_out=det_out,
2827
+ tracker_states_local=tracker_states_local,
2828
+ tracker_update_plan=tracker_update_plan,
2829
+ )
2830
+
2831
+ # Step 5: finally, build the outputs for this frame (it only needs to be done on GPU 0 since
2832
+ # only GPU 0 will send outputs to the server).
2833
+ obj_id_to_mask = self.build_outputs(
2834
+ det_out=det_out,
2835
+ tracker_low_res_masks_global=tracker_low_res_masks_global,
2836
+ tracker_metadata_prev=tracker_metadata_prev,
2837
+ tracker_update_plan=tracker_update_plan,
2838
+ reconditioned_obj_ids=reconditioned_obj_ids,
2839
+ )
2840
+ obj_id_to_score = tracker_metadata_new["obj_id_to_score"]
2841
+ obj_id_to_cls = tracker_metadata_new["obj_id_to_cls"]
2842
+ # a few statistics for the current frame as a part of the output
2843
+ frame_stats = {
2844
+ "num_obj_tracked": np.sum(tracker_metadata_new["num_obj"]),
2845
+ "num_obj_dropped": tracker_update_plan["num_obj_dropped_due_to_limit"],
2846
+ }
2847
+ # add tracker scores to metadata, it should be fired for frames except the first frame
2848
+ if tracker_obj_scores_global.shape[0] > 0:
2849
+ # Convert tracker_obj_scores_global to sigmoid scores before updating
2850
+ tracker_obj_scores_global = tracker_obj_scores_global.sigmoid().tolist()
2851
+ tracker_obj_ids = tracker_metadata_prev["obj_ids"]
2852
+ tracker_metadata_new["obj_id_to_tracker_score_frame_wise"][frame_idx].update(
2853
+ dict(zip(tracker_obj_ids, tracker_obj_scores_global))
2854
+ )
2855
+ return (
2856
+ obj_id_to_mask, # a dict: obj_id --> output mask
2857
+ obj_id_to_score, # a dict: obj_id --> output score (prob)
2858
+ obj_id_to_cls, # a dict: obj_id --> output cls (int)
2859
+ tracker_states_local_new,
2860
+ tracker_metadata_new,
2861
+ frame_stats,
2862
+ tracker_obj_scores_global, # a dict: obj_id --> tracker frame-level scores
2863
+ )
2864
+
2865
+ def _suppress_detections_close_to_boundary(self, boxes, margin=0.025):
2866
+ """Suppress detections too close to image edges (for normalized boxes).
2867
+
2868
+ boxes: (N, 4) in xyxy format, normalized [0,1]
2869
+ margin: fraction of image
2870
+ """
2871
+ x_min, y_min, x_max, y_max = boxes.unbind(-1)
2872
+ x_c = (x_min + x_max) / 2
2873
+ y_c = (y_min + y_max) / 2
2874
+ keep = (x_c > margin) & (x_c < 1.0 - margin) & (y_c > margin) & (y_c < 1.0 - margin)
2875
+
2876
+ return keep
2877
+
2878
+ def run_backbone_and_detection(
2879
+ self, im: torch.Tensor, text_ids: torch.Tensor, geometric_prompt: Prompt, allow_new_detections: bool
2880
+ ):
2881
+ """Run backbone and detection for a single frame."""
2882
+ features = self.get_im_features(im)
2883
+ sam3_image_out = self.model.forward_grounding(
2884
+ backbone_out=features, text_ids=text_ids, geometric_prompt=geometric_prompt
2885
+ )
2886
+ det_out = self._extract_detection_outputs(sam3_image_out, allow_new_detections)
2887
+ self._cache_backbone_features(sam3_image_out)
2888
+ return det_out
2889
+
2890
+ def _extract_detection_outputs(self, sam3_image_out, allow_new_detections):
2891
+ """Extract and filter detection outputs."""
2892
+ pred_probs = sam3_image_out["pred_logits"].squeeze(-1).sigmoid()
2893
+ if not allow_new_detections:
2894
+ pred_probs = pred_probs - 1e8
2895
+
2896
+ pred_cls = torch.tensor(
2897
+ list(range(pred_probs.shape[0])),
2898
+ dtype=pred_probs.dtype,
2899
+ device=pred_probs.device,
2900
+ )[:, None].expand_as(pred_probs)
2901
+
2902
+ pred_boxes_xyxy = sam3_image_out["pred_boxes_xyxy"]
2903
+ pred_masks = sam3_image_out["pred_masks"]
2904
+
2905
+ keep = pred_probs > self.score_threshold_detection
2906
+ return {
2907
+ "bbox": pred_boxes_xyxy[keep],
2908
+ "mask": pred_masks[keep],
2909
+ "scores": pred_probs[keep],
2910
+ "cls": pred_cls[keep],
2911
+ }
2912
+
2913
+ def _cache_backbone_features(self, sam3_image_out):
2914
+ """Build and cache SAM2 backbone features."""
2915
+ sam_mask_decoder = self.tracker.model.sam_mask_decoder
2916
+ feats = sam3_image_out["backbone_out"]["sam2_backbone_out"]
2917
+ tracker_backbone_fpn = [
2918
+ sam_mask_decoder.conv_s0(feats["backbone_fpn"][0]),
2919
+ sam_mask_decoder.conv_s1(feats["backbone_fpn"][1]),
2920
+ feats["backbone_fpn"][2],
2921
+ ]
2922
+ tracker_backbone_out = {
2923
+ "vision_features": tracker_backbone_fpn[-1],
2924
+ "vision_pos_enc": feats["vision_pos_enc"],
2925
+ "backbone_fpn": tracker_backbone_fpn,
2926
+ }
2927
+ # cache the SAM2 backbone features for `frame_idx` in the tracker
2928
+ self.tracker.backbone_out = tracker_backbone_out
2929
+
2930
+ def run_tracker_propagation(
2931
+ self, frame_idx: int, tracker_states_local: list[Any], tracker_metadata_prev: dict[str, np.ndarray]
2932
+ ):
2933
+ """Run the tracker propagation phase for a single frame in an SPMD manner."""
2934
+ # Step 1: propagate the local SAM2 states to get the current frame's prediction
2935
+ # `low_res_masks_local` of the existing masklets on this GPU
2936
+ # - obj_ids_local: list[int] -- list of object IDs
2937
+ # - low_res_masks_local: Tensor -- (num_local_obj, H_mask, W_mask)
2938
+ obj_ids_local, low_res_masks_local, obj_scores_local = self._propogate_tracker_one_frame_local_gpu(
2939
+ tracker_states_local, frame_idx=frame_idx
2940
+ )
2941
+
2942
+ assert np.all(obj_ids_local == tracker_metadata_prev["obj_ids"]), "{} != {}".format(
2943
+ obj_ids_local, tracker_metadata_prev["obj_ids"]
2944
+ )
2945
+
2946
+ # Step 2: all-gather `low_res_masks_local` into `low_res_masks_global`
2947
+ # - low_res_masks_global: Tensor -- (num_global_obj, H_mask, W_mask)
2948
+ low_res_masks_global = low_res_masks_local
2949
+ obj_scores_global = obj_scores_local
2950
+ return low_res_masks_global, obj_scores_global
2951
+
2952
+ def _recondition_masklets(
2953
+ self,
2954
+ frame_idx,
2955
+ det_out: dict[str, torch.Tensor],
2956
+ trk_id_to_max_iou_high_conf_det: list[int],
2957
+ tracker_states_local: list[Any],
2958
+ tracker_metadata: dict[str, np.ndarray],
2959
+ tracker_obj_scores_global: torch.Tensor,
2960
+ ):
2961
+ """Recondition masklets based on new high-confidence detections."""
2962
+ # Recondition the masklets based on the new detections
2963
+ for trk_obj_id, det_idx in trk_id_to_max_iou_high_conf_det.items():
2964
+ new_mask = det_out["mask"][det_idx : det_idx + 1]
2965
+ new_mask_binary = (
2966
+ F.interpolate(new_mask.unsqueeze(1), size=self.interpol_size, mode="bilinear", align_corners=False) > 0
2967
+ )
2968
+ HIGH_CONF_THRESH = 0.8
2969
+ reconditioned_states_idx = set()
2970
+ obj_idx = np.where(tracker_metadata["obj_ids"] == trk_obj_id)[0].item()
2971
+ obj_score = tracker_obj_scores_global[obj_idx]
2972
+ for state_idx, inference_state in enumerate(tracker_states_local):
2973
+ if (
2974
+ trk_obj_id in inference_state["obj_ids"]
2975
+ # NOTE: Goal of this condition is to avoid reconditioning masks that are occluded/low qualiy.
2976
+ # Unfortunately, these can get reconditioned anyway due to batching. We should consider removing these heuristics.
2977
+ and obj_score > HIGH_CONF_THRESH
2978
+ ):
2979
+ LOGGER.debug(
2980
+ f"Adding new mask for track {trk_obj_id} at frame {frame_idx}. Objects {inference_state['obj_ids']} are all reconditioned."
2981
+ )
2982
+ self.tracker.add_new_prompts(
2983
+ inference_state=inference_state,
2984
+ frame_idx=frame_idx,
2985
+ obj_id=trk_obj_id,
2986
+ masks=new_mask_binary,
2987
+ )
2988
+ reconditioned_states_idx.add(state_idx)
2989
+
2990
+ for idx in reconditioned_states_idx:
2991
+ self.tracker.propagate_in_video_preflight(tracker_states_local[idx])
2992
+ return tracker_states_local
2993
+
2994
+ def run_tracker_update_planning_phase(
2995
+ self,
2996
+ frame_idx: int,
2997
+ reverse: bool,
2998
+ det_out: dict[str, torch.Tensor],
2999
+ tracker_low_res_masks_global: torch.Tensor,
3000
+ tracker_obj_scores_global: torch.Tensor,
3001
+ tracker_metadata_prev: dict[str, np.ndarray],
3002
+ tracker_states_local: list[Any],
3003
+ ):
3004
+ """Run the tracker update planning phase for a single frame in an SPMD manner."""
3005
+ # initialize new metadata from previous metadata (its values will be updated later)
3006
+ tracker_metadata_new = {
3007
+ "obj_ids": deepcopy(tracker_metadata_prev["obj_ids"]),
3008
+ "num_obj": deepcopy(tracker_metadata_prev["num_obj"]),
3009
+ "obj_id_to_score": deepcopy(tracker_metadata_prev["obj_id_to_score"]),
3010
+ "obj_id_to_cls": deepcopy(tracker_metadata_prev["obj_id_to_cls"]),
3011
+ "obj_id_to_tracker_score_frame_wise": deepcopy(tracker_metadata_prev["obj_id_to_tracker_score_frame_wise"]),
3012
+ "obj_id_to_last_occluded": {}, # will be filled later
3013
+ "max_obj_id": deepcopy(tracker_metadata_prev["max_obj_id"]),
3014
+ }
3015
+
3016
+ # Initialize reconditioned_obj_ids early to avoid UnboundLocalError
3017
+ reconditioned_obj_ids = set()
3018
+
3019
+ # Step 1: make the update plan and resolve heuristics on GPU 0
3020
+ det_mask_preds: torch.Tensor = det_out["mask"] # low-res mask logits
3021
+ det_scores_np: np.ndarray = det_out["scores"].float().cpu().numpy()
3022
+ det_cls_np: np.ndarray = det_out["cls"].float().cpu().numpy()
3023
+ det_bbox_xyxy: torch.Tensor = det_out["bbox"]
3024
+ # a) match detector and tracker masks and find new objects
3025
+ (
3026
+ new_det_fa_inds,
3027
+ unmatched_trk_obj_ids,
3028
+ det_to_matched_trk_obj_ids,
3029
+ trk_id_to_max_iou_high_conf_det,
3030
+ empty_trk_obj_ids,
3031
+ ) = self._associate_det_trk(
3032
+ det_masks=det_mask_preds,
3033
+ det_scores_np=det_scores_np,
3034
+ trk_masks=tracker_low_res_masks_global,
3035
+ trk_obj_ids=tracker_metadata_prev["obj_ids"],
3036
+ )
3037
+ if self.suppress_det_close_to_boundary:
3038
+ keep = self._suppress_detections_close_to_boundary(det_bbox_xyxy[new_det_fa_inds])
3039
+ new_det_fa_inds = new_det_fa_inds[keep.cpu().numpy()]
3040
+
3041
+ # check whether we've hit the maximum number of objects we can track (and if so, drop some detections)
3042
+ prev_obj_num = np.sum(tracker_metadata_prev["num_obj"])
3043
+ new_det_num = len(new_det_fa_inds)
3044
+ num_obj_dropped_due_to_limit = 0
3045
+ if prev_obj_num + new_det_num > self.max_num_objects:
3046
+ LOGGER.warning(f"hitting {self.max_num_objects=} with {new_det_num=} and {prev_obj_num=}")
3047
+ new_det_num_to_keep = self.max_num_objects - prev_obj_num
3048
+ num_obj_dropped_due_to_limit = new_det_num - new_det_num_to_keep
3049
+ new_det_fa_inds = self._drop_new_det_with_obj_limit(new_det_fa_inds, det_scores_np, new_det_num_to_keep)
3050
+ assert len(new_det_fa_inds) == new_det_num_to_keep
3051
+ new_det_num = len(new_det_fa_inds)
3052
+
3053
+ # assign object IDs to new detections and decide which GPU to place them
3054
+ new_det_obj_ids = tracker_metadata_prev["max_obj_id"] + 1 + np.arange(new_det_num)
3055
+
3056
+ # b) handle hotstart heuristics to remove objects
3057
+ # here `metadata` contains metadata stored on (and only accessible to) GPU 0;
3058
+ # we avoid broadcasting them to other GPUs to save communication cost, assuming
3059
+ # that `metadata` is not needed by other GPUs
3060
+ metadata_new = deepcopy(tracker_metadata_prev["metadata"])
3061
+ if not hasattr(self, "_warm_up_complete") or self._warm_up_complete:
3062
+ obj_ids_newly_removed, metadata_new = self._process_hotstart(
3063
+ frame_idx=frame_idx,
3064
+ reverse=reverse,
3065
+ det_to_matched_trk_obj_ids=det_to_matched_trk_obj_ids,
3066
+ new_det_obj_ids=new_det_obj_ids,
3067
+ empty_trk_obj_ids=empty_trk_obj_ids,
3068
+ unmatched_trk_obj_ids=unmatched_trk_obj_ids,
3069
+ metadata=metadata_new,
3070
+ )
3071
+ else:
3072
+ # if warm-up is not complete, we don't remove any objects
3073
+ obj_ids_newly_removed = set()
3074
+ tracker_metadata_new["metadata"] = metadata_new
3075
+
3076
+ # `tracker_update_plan` should be identical on all GPUs after broadcasting
3077
+ tracker_update_plan = {
3078
+ "new_det_fa_inds": new_det_fa_inds, # np.ndarray
3079
+ "new_det_obj_ids": new_det_obj_ids, # np.ndarray
3080
+ # "new_det_gpu_ids": new_det_gpu_ids, # np.ndarray
3081
+ "unmatched_trk_obj_ids": unmatched_trk_obj_ids, # np.ndarray
3082
+ "det_to_matched_trk_obj_ids": det_to_matched_trk_obj_ids, # dict
3083
+ "obj_ids_newly_removed": obj_ids_newly_removed, # set
3084
+ "num_obj_dropped_due_to_limit": num_obj_dropped_due_to_limit, # int
3085
+ "trk_id_to_max_iou_high_conf_det": trk_id_to_max_iou_high_conf_det, # dict
3086
+ "reconditioned_obj_ids": reconditioned_obj_ids, # set
3087
+ }
3088
+
3089
+ # Step 3 (optional): recondition masklets based on high-confidence detections before memory encoding
3090
+ # NOTE: Running this in execution phase (after memory encoding) can lead to suboptimal results
3091
+ should_recondition_iou = False
3092
+
3093
+ # Evaluate tracklets for reconditioning based on bbox IoU mismatch with detections
3094
+ if self.reconstruction_bbox_iou_thresh > 0 and len(trk_id_to_max_iou_high_conf_det) > 0:
3095
+ for trk_obj_id, det_idx in trk_id_to_max_iou_high_conf_det.items():
3096
+ det_box = det_out["bbox"][det_idx]
3097
+ det_score = det_out["scores"][det_idx]
3098
+
3099
+ try:
3100
+ trk_idx = list(tracker_metadata_prev["obj_ids"]).index(trk_obj_id)
3101
+ except ValueError:
3102
+ continue # Skip if tracklet not found
3103
+
3104
+ tracker_mask = tracker_low_res_masks_global[trk_idx]
3105
+ mask_binary = tracker_mask > 0
3106
+ mask_area = mask_binary.sum().item()
3107
+
3108
+ if mask_area == 0:
3109
+ continue # Skip tracklets with zero mask area
3110
+
3111
+ # Get bounding box from SAM2 mask and convert to normalized coordinates
3112
+ tracker_box_pixels = batched_mask_to_box(mask_binary.unsqueeze(0)).squeeze(0)
3113
+ mask_height, mask_width = tracker_mask.shape[-2:]
3114
+ tracker_box_normalized = torch.tensor(
3115
+ [
3116
+ tracker_box_pixels[0] / mask_width,
3117
+ tracker_box_pixels[1] / mask_height,
3118
+ tracker_box_pixels[2] / mask_width,
3119
+ tracker_box_pixels[3] / mask_height,
3120
+ ],
3121
+ device=tracker_box_pixels.device,
3122
+ )
3123
+
3124
+ # Compute IoU between detection and SAM2 tracklet bounding boxes
3125
+ det_box_batch = det_box.unsqueeze(0)
3126
+ tracker_box_batch = tracker_box_normalized.unsqueeze(0)
3127
+ iou = box_iou(det_box_batch, tracker_box_batch)[0]
3128
+
3129
+ if iou < self.reconstruction_bbox_iou_thresh and det_score >= self.reconstruction_bbox_det_score:
3130
+ should_recondition_iou = True
3131
+ reconditioned_obj_ids.add(trk_obj_id)
3132
+
3133
+ should_recondition_periodic = (
3134
+ self.recondition_every_nth_frame > 0
3135
+ and frame_idx % self.recondition_every_nth_frame == 0
3136
+ and len(trk_id_to_max_iou_high_conf_det) > 0
3137
+ )
3138
+
3139
+ # Recondition if periodic or IoU condition met
3140
+ if should_recondition_periodic or should_recondition_iou:
3141
+ self._recondition_masklets(
3142
+ frame_idx,
3143
+ det_out,
3144
+ trk_id_to_max_iou_high_conf_det,
3145
+ tracker_states_local,
3146
+ tracker_metadata_prev,
3147
+ tracker_obj_scores_global,
3148
+ )
3149
+
3150
+ # Step 4: Run SAM2 memory encoder on the current frame's prediction masks
3151
+ # This is done on all GPUs
3152
+ batch_size = tracker_low_res_masks_global.size(0)
3153
+ if batch_size > 0:
3154
+ if not hasattr(self, "_warm_up_complete") or self._warm_up_complete:
3155
+ if self.suppress_overlapping_based_on_recent_occlusion_threshold > 0.0:
3156
+ # NOTE: tracker_low_res_masks_global is updated in-place then returned
3157
+ tracker_low_res_masks_global = self._suppress_overlapping_based_on_recent_occlusion(
3158
+ frame_idx,
3159
+ tracker_low_res_masks_global,
3160
+ tracker_metadata_prev,
3161
+ tracker_metadata_new,
3162
+ obj_ids_newly_removed,
3163
+ reverse,
3164
+ )
3165
+
3166
+ self._tracker_update_memories(tracker_states_local, frame_idx, low_res_masks=tracker_low_res_masks_global)
3167
+
3168
+ # Step 4: update the SAM2 metadata based on the update plan
3169
+ updated_obj_ids_this_gpu = tracker_metadata_new["obj_ids"]
3170
+ if len(new_det_obj_ids) > 0:
3171
+ updated_obj_ids_this_gpu = np.concatenate([updated_obj_ids_this_gpu, new_det_obj_ids])
3172
+ if len(obj_ids_newly_removed) > 0:
3173
+ is_removed = np.isin(updated_obj_ids_this_gpu, list(obj_ids_newly_removed))
3174
+ updated_obj_ids_this_gpu = updated_obj_ids_this_gpu[~is_removed]
3175
+ tracker_metadata_new["obj_ids"] = updated_obj_ids_this_gpu
3176
+ tracker_metadata_new["num_obj"] = len(updated_obj_ids_this_gpu)
3177
+ # update object scores and the maximum object ID assigned so far
3178
+ if len(new_det_obj_ids) > 0:
3179
+ tracker_metadata_new["obj_id_to_score"].update(zip(new_det_obj_ids, det_scores_np[new_det_fa_inds]))
3180
+ tracker_metadata_new["obj_id_to_cls"].update(zip(new_det_obj_ids, det_cls_np[new_det_fa_inds]))
3181
+ # tracker scores are not available for new objects, use det score instead.
3182
+ tracker_metadata_new["obj_id_to_tracker_score_frame_wise"][frame_idx].update(
3183
+ zip(new_det_obj_ids, det_scores_np[new_det_fa_inds])
3184
+ )
3185
+ tracker_metadata_new["max_obj_id"] = max(tracker_metadata_new["max_obj_id"], np.max(new_det_obj_ids))
3186
+ # for removed objects, we set their scores to a very low value (-1e4) but still
3187
+ # keep them in "obj_id_to_score" (it's easier to handle outputs this way)
3188
+ for obj_id in obj_ids_newly_removed:
3189
+ tracker_metadata_new["obj_id_to_score"][obj_id] = -1e4
3190
+ tracker_metadata_new["obj_id_to_tracker_score_frame_wise"][frame_idx][obj_id] = -1e4
3191
+ tracker_metadata_new["obj_id_to_last_occluded"].pop(obj_id, None)
3192
+ # check that "metadata" is in tracker_metadata_new if and only if it's GPU 0
3193
+ assert "metadata" in tracker_metadata_new
3194
+ if self.masklet_confirmation_enable:
3195
+ metadata = self.update_masklet_confirmation_status(
3196
+ metadata=tracker_metadata_new["metadata"],
3197
+ obj_ids_all_gpu_prev=tracker_metadata_prev["obj_ids"],
3198
+ obj_ids_all_gpu_updated=tracker_metadata_new["obj_ids"],
3199
+ det_to_matched_trk_obj_ids=det_to_matched_trk_obj_ids,
3200
+ new_det_obj_ids=new_det_obj_ids,
3201
+ )
3202
+ tracker_metadata_new["metadata"] = metadata
3203
+
3204
+ return tracker_update_plan, tracker_metadata_new
3205
+
3206
+ def _suppress_overlapping_based_on_recent_occlusion(
3207
+ self,
3208
+ frame_idx: int,
3209
+ tracker_low_res_masks_global: torch.Tensor,
3210
+ tracker_metadata_prev: dict[str, Any],
3211
+ tracker_metadata_new: dict[str, Any],
3212
+ obj_ids_newly_removed: set[int],
3213
+ reverse: bool = False,
3214
+ ):
3215
+ """Suppress overlapping masks based on the most recent occlusion information. If an object is removed by
3216
+ hotstart, we always suppress it if it overlaps with any other object.
3217
+
3218
+ Args:
3219
+ frame_idx (int): The current frame index.
3220
+ tracker_low_res_masks_global (torch.Tensor): The low-resolution masks for the current frame.
3221
+ tracker_metadata_prev (dict[str, Any]): The metadata from the previous frame.
3222
+ tracker_metadata_new (dict[str, Any]): The metadata for the current frame.
3223
+ obj_ids_newly_removed (set[int]): The object IDs that have been removed.
3224
+ reverse (bool): Whether the tracking is in reverse order.
3225
+
3226
+ Returns:
3227
+ (torch.Tensor): The updated low-resolution masks with some objects suppressed.
3228
+ """
3229
+ obj_ids_global = tracker_metadata_prev["obj_ids"]
3230
+ binary_tracker_low_res_masks_global = tracker_low_res_masks_global > 0
3231
+ batch_size = tracker_low_res_masks_global.size(0)
3232
+ if batch_size > 0:
3233
+ assert len(obj_ids_global) == batch_size, (
3234
+ f"Mismatch in number of objects: {len(obj_ids_global)} vs {batch_size}"
3235
+ )
3236
+ last_occluded_prev = torch.cat(
3237
+ [
3238
+ tracker_metadata_prev["obj_id_to_last_occluded"].get(
3239
+ obj_id,
3240
+ torch.full(
3241
+ (1,),
3242
+ fill_value=(
3243
+ self.NEVER_OCCLUDED if obj_id not in obj_ids_newly_removed else self.ALWAYS_OCCLUDED
3244
+ ),
3245
+ device=binary_tracker_low_res_masks_global.device,
3246
+ dtype=torch.long,
3247
+ ),
3248
+ )
3249
+ for obj_id in obj_ids_global
3250
+ ],
3251
+ dim=0,
3252
+ )
3253
+ to_suppress = self._get_objects_to_suppress_based_on_most_recently_occluded(
3254
+ binary_tracker_low_res_masks_global,
3255
+ last_occluded_prev,
3256
+ obj_ids_global,
3257
+ frame_idx,
3258
+ reverse,
3259
+ )
3260
+
3261
+ # Update metadata with occlusion information
3262
+ is_obj_occluded = ~(binary_tracker_low_res_masks_global.any(dim=(-1, -2)))
3263
+ is_obj_occluded_or_suppressed = is_obj_occluded | to_suppress
3264
+ last_occluded_new = last_occluded_prev.clone()
3265
+ last_occluded_new[is_obj_occluded_or_suppressed] = frame_idx
3266
+ # Slice out the last occluded frame for each object
3267
+ tracker_metadata_new["obj_id_to_last_occluded"] = {
3268
+ obj_id: last_occluded_new[obj_idx : obj_idx + 1] for obj_idx, obj_id in enumerate(obj_ids_global)
3269
+ }
3270
+
3271
+ # Zero out suppressed masks before memory encoding
3272
+ tracker_low_res_masks_global[to_suppress] = self.NO_OBJ_LOGIT
3273
+
3274
+ return tracker_low_res_masks_global
3275
+
3276
+ def run_tracker_update_execution_phase(
3277
+ self,
3278
+ frame_idx: int,
3279
+ num_frames: int,
3280
+ det_out: dict[str, torch.Tensor],
3281
+ tracker_states_local: list[Any],
3282
+ tracker_update_plan: dict[str, np.ndarray],
3283
+ ):
3284
+ """Execute the tracker update plan for a single frame in an SPMD manner."""
3285
+ # initialize tracking scores with detection scores
3286
+ new_det_fa_inds: np.ndarray = tracker_update_plan["new_det_fa_inds"]
3287
+ new_det_obj_ids: np.ndarray = tracker_update_plan["new_det_obj_ids"]
3288
+ # new_det_gpu_ids: np.ndarray = tracker_update_plan["new_det_gpu_ids"]
3289
+ new_det_obj_ids_local: np.ndarray = new_det_obj_ids
3290
+ new_det_fa_inds_local: np.ndarray = new_det_fa_inds
3291
+ obj_ids_newly_removed: set[int] = tracker_update_plan["obj_ids_newly_removed"]
3292
+
3293
+ # Step 1: add new objects from the detector to SAM2 inference states
3294
+ if len(new_det_fa_inds_local) > 0:
3295
+ new_det_fa_inds_local_t = torch.from_numpy(new_det_fa_inds_local)
3296
+ new_det_masks: torch.Tensor = det_out["mask"][new_det_fa_inds_local_t]
3297
+ # initialize SAM2 with new object masks
3298
+ tracker_states_local = self._tracker_add_new_objects(
3299
+ frame_idx=frame_idx,
3300
+ num_frames=num_frames,
3301
+ new_obj_ids=new_det_obj_ids_local,
3302
+ new_obj_masks=new_det_masks,
3303
+ tracker_states_local=tracker_states_local,
3304
+ )
3305
+
3306
+ # Step 2: remove from SAM2 inference states those objects removed by heuristics
3307
+ if len(obj_ids_newly_removed) > 0:
3308
+ self._tracker_remove_objects(tracker_states_local, obj_ids_newly_removed)
3309
+
3310
+ return tracker_states_local
3311
+
3312
+ def build_outputs(
3313
+ self,
3314
+ det_out: dict[str, torch.Tensor],
3315
+ tracker_low_res_masks_global: torch.Tensor,
3316
+ tracker_metadata_prev: dict[str, np.ndarray],
3317
+ tracker_update_plan: dict[str, np.ndarray],
3318
+ reconditioned_obj_ids: set | None = None,
3319
+ ):
3320
+ """Build the output masks for the current frame."""
3321
+ new_det_fa_inds: np.ndarray = tracker_update_plan["new_det_fa_inds"]
3322
+ new_det_obj_ids: np.ndarray = tracker_update_plan["new_det_obj_ids"]
3323
+ obj_id_to_mask = {} # obj_id --> output mask tensor
3324
+
3325
+ # Part 1: masks from previous SAM2 propagation
3326
+ existing_masklet_obj_ids = tracker_metadata_prev["obj_ids"]
3327
+ existing_masklet_binary = tracker_low_res_masks_global.unsqueeze(1)
3328
+ assert len(existing_masklet_obj_ids) == len(existing_masklet_binary)
3329
+ for obj_id, mask in zip(existing_masklet_obj_ids, existing_masklet_binary):
3330
+ obj_id_to_mask[obj_id] = mask # (1, H_video, W_video)
3331
+
3332
+ # Part 2: masks from new detections
3333
+ new_det_fa_inds_t = torch.from_numpy(new_det_fa_inds)
3334
+ new_det_low_res_masks = det_out["mask"][new_det_fa_inds_t].unsqueeze(1)
3335
+ assert len(new_det_obj_ids) == len(new_det_low_res_masks)
3336
+ for obj_id, mask in zip(new_det_obj_ids, new_det_low_res_masks):
3337
+ obj_id_to_mask[obj_id] = mask # (1, H_video, W_video)
3338
+
3339
+ # Part 3: Override masks for reconditioned objects using detection masks
3340
+ if reconditioned_obj_ids is not None and len(reconditioned_obj_ids) > 0:
3341
+ trk_id_to_max_iou_high_conf_det = tracker_update_plan.get("trk_id_to_max_iou_high_conf_det", {})
3342
+
3343
+ for obj_id in reconditioned_obj_ids:
3344
+ det_idx = trk_id_to_max_iou_high_conf_det.get(obj_id)
3345
+
3346
+ if det_idx is not None:
3347
+ obj_id_to_mask[obj_id] = det_out["mask"][det_idx].unsqueeze(0)
3348
+
3349
+ return obj_id_to_mask
3350
+
3351
+ def _get_objects_to_suppress_based_on_most_recently_occluded(
3352
+ self,
3353
+ binary_low_res_masks: torch.Tensor,
3354
+ last_occluded: list[int],
3355
+ obj_ids: list[int],
3356
+ frame_idx: int | None = None,
3357
+ reverse: bool = False,
3358
+ ):
3359
+ # Suppress overlapping masks for objects that were most recently occluded
3360
+ assert binary_low_res_masks.dtype == torch.bool, f"Expected boolean tensor, got {binary_low_res_masks.dtype}"
3361
+ to_suppress = torch.zeros(
3362
+ binary_low_res_masks.size(0),
3363
+ device=binary_low_res_masks.device,
3364
+ dtype=torch.bool,
3365
+ )
3366
+ if len(obj_ids) <= 1:
3367
+ return to_suppress
3368
+
3369
+ iou = mask_iou(binary_low_res_masks.flatten(1), binary_low_res_masks.flatten(1)) # [N,N]
3370
+
3371
+ # Create masks for upper triangular matrix (i < j) and IoU threshold
3372
+ mask_iou_thresh = iou >= self.suppress_overlapping_based_on_recent_occlusion_threshold
3373
+ overlapping_pairs = torch.triu(mask_iou_thresh, diagonal=1) # [N,N]
3374
+
3375
+ last_occ_expanded_i = last_occluded.unsqueeze(1) # (N, 1)
3376
+ last_occ_expanded_j = last_occluded.unsqueeze(0) # (1, N)
3377
+ # Suppress most recently occluded
3378
+ cmp_op = torch.gt if not reverse else torch.lt
3379
+ suppress_i_mask = (
3380
+ overlapping_pairs
3381
+ & cmp_op(last_occ_expanded_i, last_occ_expanded_j) # (last_occ_expanded_i > last_occ_expanded_j)
3382
+ & (last_occ_expanded_j > -1) # j can suppress i only if i was previously occluded
3383
+ )
3384
+ suppress_j_mask = (
3385
+ overlapping_pairs
3386
+ & cmp_op(last_occ_expanded_j, last_occ_expanded_i)
3387
+ & (last_occ_expanded_i > -1) # i can suppress j only if j was previously occluded
3388
+ )
3389
+ # Apply suppression
3390
+ to_suppress = suppress_i_mask.any(dim=1) | suppress_j_mask.any(dim=0)
3391
+
3392
+ # Log for debugging
3393
+ if LOGGER.isEnabledFor(10) and frame_idx is not None:
3394
+ suppress_i_mask = suppress_i_mask.cpu().numpy()
3395
+ suppress_j_mask = suppress_j_mask.cpu().numpy()
3396
+ last_occluded = last_occluded.cpu().numpy()
3397
+
3398
+ # Find all suppression pairs without using torch.where
3399
+ batch_size = suppress_i_mask.shape[0]
3400
+
3401
+ # Log i-suppression cases (where i gets suppressed in favor of j)
3402
+ for i in range(batch_size):
3403
+ for j in range(batch_size):
3404
+ if suppress_i_mask[i, j]:
3405
+ LOGGER.debug(
3406
+ f"{frame_idx=}: Suppressing obj {obj_ids[i]} last occluded {last_occluded[i]} in favor of {obj_ids[j]} last occluded {last_occluded[j]}"
3407
+ )
3408
+
3409
+ # Log j-suppression cases (where j gets suppressed in favor of i)
3410
+ for i in range(batch_size):
3411
+ for j in range(batch_size):
3412
+ if suppress_j_mask[i, j]:
3413
+ LOGGER.debug(
3414
+ f"{frame_idx=}: Suppressing obj {obj_ids[j]} last occluded {last_occluded[j]} in favor of {obj_ids[i]} last occluded {last_occluded[i]}"
3415
+ )
3416
+
3417
+ return to_suppress
3418
+
3419
+ def _propogate_tracker_one_frame_local_gpu(self, inference_states: list[Any], frame_idx: int):
3420
+ """Inference_states: list of inference states, each state corresponds to a different set of objects."""
3421
+ obj_ids_local = []
3422
+ low_res_masks_list = []
3423
+ obj_scores_list = []
3424
+ for inference_state in inference_states:
3425
+ if len(inference_state["obj_ids"]) == 0:
3426
+ continue # skip propagation on empty inference states
3427
+
3428
+ out_obj_ids, out_low_res_masks, out_obj_scores = self.tracker.propagate_in_video(
3429
+ inference_state, frame_idx=frame_idx
3430
+ )
3431
+ assert isinstance(out_obj_ids, list)
3432
+ obj_ids_local.extend(out_obj_ids)
3433
+ low_res_masks_list.append(out_low_res_masks.squeeze(1))
3434
+ obj_scores_list.append(out_obj_scores.squeeze(1))
3435
+
3436
+ # concatenate the output masklets from all local inference states
3437
+ if len(low_res_masks_list) > 0:
3438
+ low_res_masks_local = torch.cat(low_res_masks_list, dim=0)
3439
+ obj_scores_local = torch.cat(obj_scores_list, dim=0)
3440
+ low_res_masks_local = low_res_masks_local.squeeze(1)
3441
+ else:
3442
+ low_res_masks_local = torch.zeros(0, *self._bb_feat_sizes[0], device=self.device)
3443
+ obj_scores_local = torch.zeros(0, device=self.device)
3444
+
3445
+ return obj_ids_local, low_res_masks_local, obj_scores_local
3446
+
3447
+ def _associate_det_trk(
3448
+ self,
3449
+ det_masks: torch.Tensor,
3450
+ det_scores_np: np.ndarray,
3451
+ trk_masks: torch.Tensor,
3452
+ trk_obj_ids: np.ndarray,
3453
+ ):
3454
+ """Match detections on the current frame with the existing masklets.
3455
+
3456
+ Args:
3457
+ det_masks: (N, H, W) tensor of predicted masks
3458
+ det_scores_np: (N,) array of detection scores
3459
+ trk_masks: (M, H, W) tensor of track masks
3460
+ trk_obj_ids: (M,) array of object IDs corresponding to trk_masks
3461
+
3462
+ Returns:
3463
+ new_det_fa_inds: array of new object indices.
3464
+ unmatched_trk_obj_ids: array of existing masklet object IDs that are not matched to any detections on this
3465
+ frame (for unmatched, we only count masklets with >0 area)
3466
+ det_to_matched_trk_obj_ids: dict[int, np.ndarray]: mapping from detector's detection indices to the list of
3467
+ matched tracklet object IDs
3468
+ empty_trk_obj_ids: array of existing masklet object IDs with zero area in SAM2 prediction
3469
+ """
3470
+ iou_threshold = self.assoc_iou_thresh
3471
+ iou_threshold_trk = self.trk_assoc_iou_thresh
3472
+ new_det_thresh = self.new_det_thresh
3473
+
3474
+ assert det_masks.is_floating_point(), "float tensor expected (do not binarize)"
3475
+ assert trk_masks.is_floating_point(), "float tensor expected (do not binarize)"
3476
+ assert trk_masks.size(0) == len(trk_obj_ids), (
3477
+ f"trk_masks and trk_obj_ids should have the same length, {trk_masks.size(0)} vs {len(trk_obj_ids)}"
3478
+ )
3479
+ if trk_masks.size(0) == 0:
3480
+ # all detections are new
3481
+ new_det_fa_inds = np.arange(det_masks.size(0))
3482
+ unmatched_trk_obj_ids = np.array([], np.int64)
3483
+ empty_trk_obj_ids = np.array([], np.int64)
3484
+ det_to_matched_trk_obj_ids = {}
3485
+ trk_id_to_max_iou_high_conf_det = {}
3486
+ return (
3487
+ new_det_fa_inds,
3488
+ unmatched_trk_obj_ids,
3489
+ det_to_matched_trk_obj_ids,
3490
+ trk_id_to_max_iou_high_conf_det,
3491
+ empty_trk_obj_ids,
3492
+ )
3493
+ elif det_masks.size(0) == 0:
3494
+ # all previous tracklets are unmatched if they have a non-zero area
3495
+ new_det_fa_inds = np.array([], np.int64)
3496
+ trk_is_nonempty = (trk_masks > 0).any(dim=(1, 2)).cpu().numpy()
3497
+ unmatched_trk_obj_ids = trk_obj_ids[trk_is_nonempty]
3498
+ empty_trk_obj_ids = trk_obj_ids[~trk_is_nonempty]
3499
+ det_to_matched_trk_obj_ids = {}
3500
+ trk_id_to_max_iou_high_conf_det = {}
3501
+ return (
3502
+ new_det_fa_inds,
3503
+ unmatched_trk_obj_ids,
3504
+ det_to_matched_trk_obj_ids,
3505
+ trk_id_to_max_iou_high_conf_det,
3506
+ empty_trk_obj_ids,
3507
+ )
3508
+
3509
+ if det_masks.shape[-2:] != trk_masks.shape[-2:]:
3510
+ # resize to the smaller size to save GPU memory
3511
+ if np.prod(det_masks.shape[-2:]) < np.prod(trk_masks.shape[-2:]):
3512
+ trk_masks = F.interpolate(
3513
+ trk_masks.unsqueeze(1),
3514
+ size=det_masks.shape[-2:],
3515
+ mode="bilinear",
3516
+ align_corners=False,
3517
+ ).squeeze(1)
3518
+ else:
3519
+ # resize detections to track size
3520
+ det_masks = F.interpolate(
3521
+ det_masks.unsqueeze(1),
3522
+ size=trk_masks.shape[-2:],
3523
+ mode="bilinear",
3524
+ align_corners=False,
3525
+ ).squeeze(1)
3526
+
3527
+ det_masks_binary = det_masks > 0
3528
+ trk_masks_binary = trk_masks > 0
3529
+ ious = mask_iou(det_masks_binary.flatten(1).float(), trk_masks_binary.flatten(1).float()) # (N, M)
3530
+
3531
+ ious_np = ious.cpu().numpy()
3532
+ if self.o2o_matching_masklets_enable:
3533
+ from scipy.optimize import linear_sum_assignment
3534
+
3535
+ # Hungarian matching for tracks (one-to-one: each track matches at most one detection)
3536
+ cost_matrix = 1 - ious_np # Hungarian solves for minimum cost
3537
+ row_ind, col_ind = linear_sum_assignment(cost_matrix)
3538
+ trk_is_matched = np.zeros(trk_masks.size(0), dtype=bool)
3539
+ for d, t in zip(row_ind, col_ind):
3540
+ if ious_np[d, t] >= iou_threshold_trk:
3541
+ trk_is_matched[t] = True
3542
+ else:
3543
+ trk_is_matched = (ious_np >= iou_threshold_trk).any(axis=0)
3544
+ # Non-empty tracks not matched by Hungarian assignment above threshold are unmatched
3545
+ trk_is_nonempty = trk_masks_binary.any(dim=(1, 2)).cpu().numpy()
3546
+ trk_is_unmatched = np.logical_and(trk_is_nonempty, ~trk_is_matched)
3547
+ unmatched_trk_obj_ids = trk_obj_ids[trk_is_unmatched]
3548
+ # also record masklets that have zero area in SAM 2 prediction
3549
+ empty_trk_obj_ids = trk_obj_ids[~trk_is_nonempty]
3550
+
3551
+ # For detections: allow many tracks to match to the same detection (many-to-one)
3552
+ # So, a detection is 'new' if it does not match any track above threshold
3553
+ is_new_det = np.logical_and(
3554
+ det_scores_np >= new_det_thresh,
3555
+ np.logical_not(np.any(ious_np >= iou_threshold, axis=1)),
3556
+ )
3557
+ new_det_fa_inds = np.nonzero(is_new_det)[0]
3558
+
3559
+ # for each detection, which tracks it matched to (above threshold)
3560
+ det_to_matched_trk_obj_ids = {}
3561
+ trk_id_to_max_iou_high_conf_det = {} # trk id --> exactly one detection idx
3562
+ det_to_max_iou_trk_idx = np.argmax(ious_np, axis=1)
3563
+ det_is_high_conf = (det_scores_np >= self.HIGH_CONF_THRESH) & ~is_new_det
3564
+ det_is_high_iou = np.max(ious_np, axis=1) >= self.HIGH_IOU_THRESH
3565
+ det_is_high_conf_and_iou = set(np.nonzero(det_is_high_conf & det_is_high_iou)[0])
3566
+ for d in range(det_masks.size(0)):
3567
+ det_to_matched_trk_obj_ids[d] = trk_obj_ids[ious_np[d, :] >= iou_threshold]
3568
+ if d in det_is_high_conf_and_iou:
3569
+ trk_obj_id = trk_obj_ids[det_to_max_iou_trk_idx[d]].item()
3570
+ trk_id_to_max_iou_high_conf_det[trk_obj_id] = d
3571
+
3572
+ return (
3573
+ new_det_fa_inds,
3574
+ unmatched_trk_obj_ids,
3575
+ det_to_matched_trk_obj_ids,
3576
+ trk_id_to_max_iou_high_conf_det,
3577
+ empty_trk_obj_ids,
3578
+ )
3579
+
3580
+ def _process_hotstart(
3581
+ self,
3582
+ frame_idx: int,
3583
+ reverse: bool,
3584
+ det_to_matched_trk_obj_ids: dict[int, np.ndarray],
3585
+ new_det_obj_ids: np.ndarray,
3586
+ empty_trk_obj_ids: np.ndarray,
3587
+ unmatched_trk_obj_ids: np.ndarray,
3588
+ metadata: dict[str, Any],
3589
+ ):
3590
+ """Handle hotstart heuristics to remove unmatched or duplicated objects."""
3591
+ # obj_id --> first frame index where the object was detected
3592
+ obj_first_frame_idx = metadata["obj_first_frame_idx"]
3593
+ # obj_id --> [mismatched frame indices]
3594
+ unmatched_frame_inds = metadata["unmatched_frame_inds"]
3595
+ trk_keep_alive = metadata["trk_keep_alive"]
3596
+ # (first_appear_obj_id, obj_id) --> [overlap frame indices]
3597
+ overlap_pair_to_frame_inds = metadata["overlap_pair_to_frame_inds"]
3598
+ # removed_obj_ids: object IDs that are suppressed via hot-start
3599
+ removed_obj_ids = metadata["removed_obj_ids"]
3600
+ suppressed_obj_ids = metadata["suppressed_obj_ids"][frame_idx]
3601
+
3602
+ obj_ids_newly_removed = set() # object IDs to be newly removed on this frame
3603
+ hotstart_diff = frame_idx - self.hotstart_delay if not reverse else frame_idx + self.hotstart_delay
3604
+
3605
+ # Step 1: log the frame index where each object ID first appears
3606
+ for obj_id in new_det_obj_ids:
3607
+ if obj_id not in obj_first_frame_idx:
3608
+ obj_first_frame_idx[obj_id] = frame_idx
3609
+ assert obj_id not in trk_keep_alive
3610
+ trk_keep_alive[obj_id] = self.init_trk_keep_alive
3611
+
3612
+ matched_trks = set()
3613
+ # We use the det-->tracks list to check for matched objects. Otherwise, we need to compute areas to decide whether they're occluded
3614
+ for matched_trks_per_det in det_to_matched_trk_obj_ids.values():
3615
+ matched_trks.update(matched_trks_per_det)
3616
+ for obj_id in matched_trks:
3617
+ # NOTE: To minimize number of configurable params, we use the hotstart_unmatch_thresh to set the max value of trk_keep_alive
3618
+ trk_keep_alive[obj_id] = min(self.max_trk_keep_alive, trk_keep_alive[obj_id] + 1)
3619
+ for obj_id in unmatched_trk_obj_ids:
3620
+ unmatched_frame_inds[obj_id].append(frame_idx)
3621
+ # NOTE: To minimize number of configurable params, we use the hotstart_unmatch_thresh to set the min value of trk_keep_alive
3622
+ # The max keep alive is 2x the min, means the model prefers to keep the prediction rather than suppress it if it was matched long enough.
3623
+ trk_keep_alive[obj_id] = max(self.min_trk_keep_alive, trk_keep_alive[obj_id] - 1)
3624
+ if self.decrease_trk_keep_alive_for_empty_masklets:
3625
+ for obj_id in empty_trk_obj_ids:
3626
+ # NOTE: To minimize number of configurable params, we use the hotstart_unmatch_thresh to set the min value of trk_keep_alive
3627
+ trk_keep_alive[obj_id] = max(self.min_trk_keep_alive, trk_keep_alive[obj_id] - 1)
3628
+
3629
+ # Step 2: removed tracks that has not matched with detections for `hotstart_unmatch_thresh` frames with hotstart period
3630
+ # a) add unmatched frame indices for each existing object ID
3631
+ # note that `unmatched_trk_obj_ids` contains those frames where the SAM2 output mask
3632
+ # doesn't match any detection; it excludes those frames where SAM2 gives an empty mask
3633
+ # b) remove a masklet if it first appears after `hotstart_diff` and is unmatched for more
3634
+ # than `self.hotstart_unmatch_thresh` frames
3635
+ for obj_id, frame_indices in unmatched_frame_inds.items():
3636
+ if obj_id in removed_obj_ids or obj_id in obj_ids_newly_removed:
3637
+ continue # skip if the object is already removed
3638
+ if len(frame_indices) >= self.hotstart_unmatch_thresh:
3639
+ is_within_hotstart = (obj_first_frame_idx[obj_id] > hotstart_diff and not reverse) or (
3640
+ obj_first_frame_idx[obj_id] < hotstart_diff and reverse
3641
+ )
3642
+ if is_within_hotstart:
3643
+ obj_ids_newly_removed.add(obj_id)
3644
+ LOGGER.debug(
3645
+ f"Removing object {obj_id} at frame {frame_idx} "
3646
+ f"since it is unmatched for frames: {frame_indices}"
3647
+ )
3648
+ if (
3649
+ trk_keep_alive[obj_id] <= 0 # Object has not been matched for too long
3650
+ and not self.suppress_unmatched_only_within_hotstart
3651
+ and obj_id not in removed_obj_ids
3652
+ and obj_id not in obj_ids_newly_removed
3653
+ ):
3654
+ LOGGER.debug(f"Suppressing object {obj_id} at frame {frame_idx}, due to being unmatched")
3655
+ suppressed_obj_ids.add(obj_id)
3656
+
3657
+ # Step 3: removed tracks that overlaps with another track for `hotstart_dup_thresh` frames
3658
+ # a) find overlaps tracks -- we consider overlap if they match to the same detection
3659
+ for _, matched_trk_obj_ids in det_to_matched_trk_obj_ids.items():
3660
+ if len(matched_trk_obj_ids) < 2:
3661
+ continue # only count detections that are matched to multiple (>=2) masklets
3662
+ # if there are multiple matched track ids, we need to find the one that appeared first;
3663
+ # these later appearing ids may be removed since they may be considered as duplicates
3664
+ first_appear_obj_id = (
3665
+ min(matched_trk_obj_ids, key=lambda x: obj_first_frame_idx[x])
3666
+ if not reverse
3667
+ else max(matched_trk_obj_ids, key=lambda x: obj_first_frame_idx[x])
3668
+ )
3669
+ for obj_id in matched_trk_obj_ids:
3670
+ if obj_id != first_appear_obj_id:
3671
+ key = (first_appear_obj_id, obj_id)
3672
+ overlap_pair_to_frame_inds[key].append(frame_idx)
3673
+
3674
+ # b) remove a masklet if it first appears after `hotstart_diff` and it overlaps with another
3675
+ # masklet (that appears earlier) for more than `self.hotstart_dup_thresh` frames
3676
+ for (first_obj_id, obj_id), frame_indices in overlap_pair_to_frame_inds.items():
3677
+ if obj_id in removed_obj_ids or obj_id in obj_ids_newly_removed:
3678
+ continue # skip if the object is already removed
3679
+ if (obj_first_frame_idx[obj_id] > hotstart_diff and not reverse) or (
3680
+ obj_first_frame_idx[obj_id] < hotstart_diff and reverse
3681
+ ):
3682
+ if len(frame_indices) >= self.hotstart_dup_thresh:
3683
+ obj_ids_newly_removed.add(obj_id)
3684
+ LOGGER.debug(
3685
+ f"Removing object {obj_id} at frame {frame_idx} "
3686
+ f"since it overlaps with another track {first_obj_id} at frames: {frame_indices}"
3687
+ )
3688
+
3689
+ removed_obj_ids.update(obj_ids_newly_removed)
3690
+ return obj_ids_newly_removed, metadata
3691
+
3692
+ def _tracker_update_memories(
3693
+ self, tracker_inference_states: list[Any], frame_idx: int, low_res_masks: torch.Tensor
3694
+ ):
3695
+ """Run Sam2 memory encoder, enforcing non-overlapping constraints globally."""
3696
+ if len(tracker_inference_states) == 0:
3697
+ return
3698
+ # NOTE: inspect this part if we observe OOMs in the demo
3699
+ high_res_masks = F.interpolate(
3700
+ low_res_masks.unsqueeze(1),
3701
+ size=self.interpol_size,
3702
+ mode="bilinear",
3703
+ align_corners=False,
3704
+ )
3705
+ # We first apply non-overlapping constraints before memory encoding. This may include some suppression heuristics.
3706
+ if not hasattr(self, "_warm_up_complete") or self._warm_up_complete:
3707
+ high_res_masks = self.tracker.model._suppress_object_pw_area_shrinkage(high_res_masks)
3708
+ # Instead of gathering the predicted object scores, we use mask areas as a proxy.
3709
+ object_score_logits = torch.where((high_res_masks > 0).any(dim=(-1, -2)), 10.0, -10.0)
3710
+
3711
+ # Run the memory encoder on local slices for each GPU
3712
+ start_idx_gpu = 0
3713
+ start_idx_state = start_idx_gpu
3714
+ for tracker_state in tracker_inference_states:
3715
+ num_obj_per_state = len(tracker_state["obj_ids"])
3716
+ if num_obj_per_state == 0:
3717
+ continue
3718
+ # Get the local high-res masks and object score logits for this inference state
3719
+ end_idx_state = start_idx_state + num_obj_per_state
3720
+ local_high_res_masks = high_res_masks[start_idx_state:end_idx_state]
3721
+ local_object_score_logits = object_score_logits[start_idx_state:end_idx_state]
3722
+ local_batch_size = local_high_res_masks.size(0)
3723
+ # Run Sam2 memory encoder. Note that we do not re-enforce the non-overlapping constraint as it is turned off by default
3724
+
3725
+ encoded_mem = self.tracker._run_memory_encoder(
3726
+ local_batch_size,
3727
+ local_high_res_masks,
3728
+ local_object_score_logits,
3729
+ is_mask_from_pts=False,
3730
+ inference_state=tracker_state,
3731
+ )
3732
+ local_maskmem_features, local_maskmem_pos_enc = encoded_mem
3733
+ # Store encoded memories in the local inference state
3734
+ output_dict = tracker_state["output_dict"]
3735
+ for storage_key in ["cond_frame_outputs", "non_cond_frame_outputs"]:
3736
+ if frame_idx not in output_dict[storage_key]:
3737
+ continue
3738
+ output_dict[storage_key][frame_idx]["maskmem_features"] = local_maskmem_features
3739
+ output_dict[storage_key][frame_idx]["maskmem_pos_enc"] = [pos for pos in local_maskmem_pos_enc]
3740
+ # for batched inference state, we also need to add per-object
3741
+ # memory slides to support instance interactivity
3742
+ self.tracker._add_output_per_object(
3743
+ inference_state=tracker_state,
3744
+ frame_idx=frame_idx,
3745
+ current_out=output_dict[storage_key][frame_idx],
3746
+ storage_key=storage_key,
3747
+ )
3748
+ start_idx_state += num_obj_per_state
3749
+
3750
+ def _tracker_add_new_objects(
3751
+ self,
3752
+ frame_idx: int,
3753
+ num_frames: int,
3754
+ new_obj_ids: list[int],
3755
+ new_obj_masks: torch.Tensor,
3756
+ tracker_states_local: list[Any],
3757
+ ):
3758
+ """Add a new object to SAM2 inference states."""
3759
+ prev_tracker_state = tracker_states_local[0] if len(tracker_states_local) > 0 else None
3760
+
3761
+ # prepare inference_state
3762
+ # batch objects that first appear on the same frame together
3763
+ # Clear inference state. Keep the cached image features if available.
3764
+ new_tracker_state = self.tracker._init_state(num_frames=num_frames)
3765
+ # NOTE: adding image placeholder
3766
+ new_tracker_state["im"] = None
3767
+ new_tracker_state["backbone_out"] = (
3768
+ prev_tracker_state.get("backbone_out", None) if prev_tracker_state is not None else None
3769
+ )
3770
+
3771
+ assert len(new_obj_ids) == new_obj_masks.size(0)
3772
+ assert new_obj_masks.is_floating_point()
3773
+ new_obj_masks = F.interpolate(
3774
+ new_obj_masks.unsqueeze(0),
3775
+ size=self.interpol_size,
3776
+ mode="bilinear",
3777
+ align_corners=False,
3778
+ ).squeeze(0)
3779
+ new_obj_masks = new_obj_masks > 0
3780
+
3781
+ # add object one by one
3782
+ for new_obj_id, new_mask in zip(new_obj_ids, new_obj_masks):
3783
+ self.tracker.add_new_prompts(
3784
+ inference_state=new_tracker_state,
3785
+ frame_idx=frame_idx,
3786
+ obj_id=new_obj_id,
3787
+ masks=new_mask[None, None], # add bs, channel
3788
+ )
3789
+ # NOTE: we skip enforcing the non-overlapping constraint **globally** when adding new objects.
3790
+ self.tracker.propagate_in_video_preflight(new_tracker_state)
3791
+ tracker_states_local.append(new_tracker_state)
3792
+ return tracker_states_local
3793
+
3794
+ def _tracker_remove_objects(self, tracker_states_local: list[Any], obj_ids: list[int]):
3795
+ """Remove an object from SAM2 inference states. This would remove the object from all frames in the video."""
3796
+ if not obj_ids:
3797
+ return
3798
+ # Filter out states that become empty after removal
3799
+ active_states = []
3800
+ for state in tracker_states_local:
3801
+ for obj_id in obj_ids:
3802
+ # we try to remove `obj_id` on every inference state with `strict=False`
3803
+ # it will not do anything if an inference state doesn't contain `obj_id`
3804
+ self.tracker.remove_object(state, obj_id, strict=False)
3805
+
3806
+ if len(state["obj_ids"]) > 0:
3807
+ active_states.append(state)
3808
+
3809
+ # Update the list in-place
3810
+ tracker_states_local[:] = active_states
3811
+
3812
+ def _initialize_metadata(self):
3813
+ """Initialize metadata for the masklets."""
3814
+ tracker_metadata = {
3815
+ "obj_ids": np.array([], np.int32),
3816
+ "num_obj": np.zeros(1, np.int32),
3817
+ "max_obj_id": -1,
3818
+ "obj_id_to_score": {},
3819
+ "obj_id_to_cls": {},
3820
+ "obj_id_to_tracker_score_frame_wise": defaultdict(dict),
3821
+ "obj_id_to_last_occluded": {},
3822
+ }
3823
+ # "metadata" contains metadata that is only stored on (and accessible to) GPU 0
3824
+ # - obj_first_frame_idx: obj_id --> first frame index where the object was detected
3825
+ # - unmatched_frame_inds: obj_id --> [mismatched frame indices]
3826
+ # - overlap_pair_to_frame_inds: (first_appear_obj_id, obj_id) --> [overlap frame indices]
3827
+ # - removed_obj_ids: object IDs that are suppressed via hot-start
3828
+ metadata = {
3829
+ "obj_first_frame_idx": {},
3830
+ "unmatched_frame_inds": defaultdict(list),
3831
+ "trk_keep_alive": defaultdict(int), # This is used only for object suppression not for removal
3832
+ "overlap_pair_to_frame_inds": defaultdict(list),
3833
+ "removed_obj_ids": set(),
3834
+ # frame_idx --> set of objects with suppressed outputs, but still continue to be tracked
3835
+ "suppressed_obj_ids": defaultdict(set),
3836
+ }
3837
+ if self.masklet_confirmation_enable:
3838
+ # all the following are np.ndarray with the same shape as `obj_ids_all_gpu`
3839
+ metadata["masklet_confirmation"] = {
3840
+ # "status" is the confirmation status of each masklet
3841
+ "status": np.array([], np.int64),
3842
+ # "consecutive_det_num" is the number of consecutive frames where the masklet is
3843
+ # detected by the detector (with a matched detection)
3844
+ "consecutive_det_num": np.array([], np.int64),
3845
+ }
3846
+ tracker_metadata["metadata"] = metadata
3847
+
3848
+ return tracker_metadata
3849
+
3850
+ def update_masklet_confirmation_status(
3851
+ self,
3852
+ metadata: dict[str, Any],
3853
+ obj_ids_all_gpu_prev: np.ndarray,
3854
+ obj_ids_all_gpu_updated: np.ndarray,
3855
+ det_to_matched_trk_obj_ids: dict[int, np.ndarray],
3856
+ new_det_obj_ids: np.ndarray,
3857
+ ):
3858
+ """Update the confirmation status of masklets based on the current frame's detection results."""
3859
+ confirmation_data = metadata["masklet_confirmation"]
3860
+
3861
+ # a) first, expand "confirmation_data" to include new masklets added in this frame
3862
+ status_prev = confirmation_data["status"]
3863
+ consecutive_det_num_prev = confirmation_data["consecutive_det_num"]
3864
+ assert status_prev.shape == obj_ids_all_gpu_prev.shape, (
3865
+ f"Got {status_prev.shape} vs {obj_ids_all_gpu_prev.shape}"
3866
+ )
3867
+
3868
+ obj_id_to_updated_idx = {obj_id: idx for idx, obj_id in enumerate(obj_ids_all_gpu_updated)}
3869
+ prev_elem_is_in_updated = np.isin(obj_ids_all_gpu_prev, obj_ids_all_gpu_updated)
3870
+ prev_elem_obj_ids_in_updated = obj_ids_all_gpu_prev[prev_elem_is_in_updated]
3871
+ prev_elem_inds_in_updated = np.array(
3872
+ [obj_id_to_updated_idx[obj_id] for obj_id in prev_elem_obj_ids_in_updated],
3873
+ dtype=np.int64,
3874
+ )
3875
+ # newly added masklets are initialized to "UNCONFIRMED" status
3876
+ unconfirmed_val = self.UNCONFIRMED
3877
+ status = np.full_like(obj_ids_all_gpu_updated, fill_value=unconfirmed_val)
3878
+ status[prev_elem_inds_in_updated] = status_prev[prev_elem_is_in_updated]
3879
+ consecutive_det_num = np.zeros_like(obj_ids_all_gpu_updated)
3880
+ consecutive_det_num[prev_elem_inds_in_updated] = consecutive_det_num_prev[prev_elem_is_in_updated]
3881
+
3882
+ # b) update the confirmation status of all masklets based on the current frame
3883
+ # b.1) update "consecutive_det_num"
3884
+ # "is_matched": whether a masklet is matched to a detection on this frame
3885
+ is_matched = np.isin(obj_ids_all_gpu_updated, new_det_obj_ids)
3886
+ for matched_trk_obj_ids in det_to_matched_trk_obj_ids.values():
3887
+ is_matched |= np.isin(obj_ids_all_gpu_updated, matched_trk_obj_ids)
3888
+ consecutive_det_num = np.where(is_matched, consecutive_det_num + 1, 0)
3889
+
3890
+ # b.2) update "status"
3891
+ change_to_confirmed = consecutive_det_num >= self.masklet_confirmation_consecutive_det_thresh
3892
+ status[change_to_confirmed] = self.CONFIRMED
3893
+
3894
+ confirmation_data["status"] = status
3895
+ confirmation_data["consecutive_det_num"] = consecutive_det_num
3896
+ return metadata
3897
+
3898
+ def _load_checkpoint(self, ckpt_path: str, strict: bool = True):
3899
+ sd = torch.load(ckpt_path, map_location="cpu", weights_only=True)["model"]
3900
+ missing_keys, unexpected_keys = self.load_state_dict(sd, strict=strict)
3901
+ if len(missing_keys) > 0 or len(unexpected_keys) > 0:
3902
+ LOGGER.warning(f"Loaded ckpt with {missing_keys=}, {unexpected_keys=}")
3903
+ else:
3904
+ LOGGER.info("Loaded ckpt successfully without missing or unexpected keys")
3905
+
3906
+ def _encode_prompt(self, **kwargs):
3907
+ return self.model._encode_prompt(**kwargs)
3908
+
3909
+ def _drop_new_det_with_obj_limit(self, new_det_fa_inds, det_scores_np, num_to_keep):
3910
+ """Drop a few new detections based on the maximum number of objects. We drop new objects based on their
3911
+ detection scores, keeping the high-scoring ones and dropping the low-scoring ones.
3912
+ """
3913
+ assert 0 <= num_to_keep <= len(new_det_fa_inds)
3914
+ if num_to_keep == 0:
3915
+ return np.array([], np.int64) # keep none
3916
+ if num_to_keep == len(new_det_fa_inds):
3917
+ return new_det_fa_inds # keep all
3918
+
3919
+ # keep the top-scoring detections
3920
+ score_order = np.argsort(det_scores_np[new_det_fa_inds])[::-1]
3921
+ new_det_fa_inds = new_det_fa_inds[score_order[:num_to_keep]]
3922
+ return new_det_fa_inds