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